Skip to main content

nativeview_engine/
hotreload.rs

1use std::fmt;
2
3use nativeview_codec::{ByteReader, ByteWriter, CodecError, DEFAULT_MAX_BYTES};
4
5/// 16-byte wire magic identifying a binary `HotPatchMsg` frame (`NV_HOT_PATCH\0\0\0`).
6pub const HOT_PATCH_WIRE_MAGIC: [u8; 16] = *b"NV_HOT_PATCH\0\0\0\0";
7
8/// Wire protocol version immediately following [`HOT_PATCH_WIRE_MAGIC`].
9/// Version 2 replaces legacy CSS string `attr_updates` with binary `RowPatch` `u32` word payloads
10/// and 64-bit `xxh64` template identity keys.
11pub const HOT_PATCH_VERSION: u8 = 2;
12
13/// Maximum item count accepted per vector inside a binary `NV_HOT_PATCH` frame to prevent OOM on corrupt input.
14const MAX_WIRE_ITEMS: usize = 65_536;
15
16/// Error returned when decoding a binary `NV_HOT_PATCH` `HotPatchMsg` frame.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum HotPatchDecodeError {
19    Truncated,
20    InvalidMagic,
21    UnsupportedVersion(u8),
22    UnknownVariant(u8),
23    InvalidBool(u8),
24    InvalidUtf8,
25    LimitExceeded,
26    TrailingBytes(usize),
27}
28
29impl From<CodecError> for HotPatchDecodeError {
30    #[inline]
31    fn from(err: CodecError) -> Self {
32        match err {
33            CodecError::Truncated { .. } => Self::Truncated,
34            CodecError::BadMagic => Self::InvalidMagic,
35            CodecError::BadVersion(v) => Self::UnsupportedVersion(v as u8),
36            CodecError::BadEnum { raw, .. } => Self::UnknownVariant(raw as u8),
37            CodecError::BadBool(b) => Self::InvalidBool(b),
38            CodecError::InvalidUtf8 => Self::InvalidUtf8,
39            CodecError::LenOverflow { .. } => Self::LimitExceeded,
40            CodecError::TrailingBytes(n) => Self::TrailingBytes(n),
41            CodecError::NonZeroReserved(_) => Self::InvalidMagic,
42            CodecError::DepthExceeded { .. } => Self::LimitExceeded,
43        }
44    }
45}
46
47impl fmt::Display for HotPatchDecodeError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::Truncated => f.write_str("truncated NV_HOT_PATCH buffer"),
51            Self::InvalidMagic => f.write_str("invalid NV_HOT_PATCH magic"),
52            Self::UnsupportedVersion(v) => write!(
53                f,
54                "unsupported hot-patch wire version {v} (expected {HOT_PATCH_VERSION})"
55            ),
56            Self::UnknownVariant(v) => write!(f, "unknown NV_HOT_PATCH variant tag {v}"),
57            Self::InvalidBool(v) => write!(f, "invalid NV_HOT_PATCH boolean tag {v}"),
58            Self::InvalidUtf8 => f.write_str("invalid UTF-8 in NV_HOT_PATCH string"),
59            Self::LimitExceeded => f.write_str("NV_HOT_PATCH collection limit exceeded"),
60            Self::TrailingBytes(n) => write!(f, "trailing {n} byte(s) in NV_HOT_PATCH buffer"),
61        }
62    }
63}
64
65impl std::error::Error for HotPatchDecodeError {}
66
67/// Unified 2-tier hot-reload protocol broadcast by `nv dev` over WebSocket (binary v2
68/// frames, see [`HotPatchMsg::to_bytes`]) to Desktop Skia, iOS Simulator/Device, Android
69/// Emulator/Device, and Web clients, and handed to apps through `NvDevApi::apply_hot_patch`.
70/// There is no JSON form and no CSS attribute string payload.
71#[derive(Debug, Clone, PartialEq)]
72pub enum HotPatchMsg {
73    /// Tier 1 (<10ms, zero recompile, works on physical iOS devices & browsers):
74    /// Applies a binary `nativeview_store::RowPatch` and/or targeted text update directly onto matching
75    /// `NodeStore` nodes identified by `(template_key, node_path)` or `target_test_id`.
76    TemplatePatch {
77        generation: u64,
78        /// Collision-free `xxh64` template identity (`view!` `AnchorKey`); `0` if unkeyed.
79        template_key: u64,
80        /// Structural child-index path inside the template tree (from template root).
81        node_path: Vec<u16>,
82        /// Optional `test_id` / `data-testid` / `testID` fallback targeting a specific element.
83        target_test_id: Option<String>,
84        /// Flat `u32` words encoded by `nativeview_store::RowPatch::write_words` (validated via
85        /// `RowPatchView::from_words` and applied directly via `Transaction::apply_row_patch`).
86        row_patch_words: Vec<u32>,
87        /// Positional `(text_index, new_text)` updates.
88        text_updates: Vec<(usize, String)>,
89        /// Exact `(old_text, new_text)` static text replacements scoped to the target.
90        text_replacements: Vec<(String, String)>,
91    },
92    /// Tier 2 (150-400ms, desktop + iOS Simulator + Android):
93    /// Instructs the host shell to hot-swap the compiled Rust app cdylib while preserving state.
94    DylibReload {
95        generation: u64,
96        dylib_path: String,
97        build_ms: u64,
98    },
99    /// Heartbeat / diagnostic banner sent to the live on-screen HUD.
100    DevStatus {
101        message: String,
102        latency_ms: u64,
103    },
104    /// Client -> daemon acknowledgement emitted after a `TemplatePatch` or `DylibReload`
105    /// has been applied (and presented, when a visible surface exists) or failed.
106    ReloadAck {
107        generation: u64,
108        ok: bool,
109        applied: bool,
110        applied_ms: u64,
111        detail: String,
112    },
113    /// Client -> daemon greeting sent immediately on WebSocket open (including after a Web
114    /// Tier-2 `location.reload()`) so `nv dev` knows the host type and booted bundle hash.
115    ClientHello {
116        client_kind: String,
117        bundle_hash: String,
118        reloaded_generation: u64,
119    },
120}
121
122impl HotPatchMsg {
123    /// Encodes this hot-patch message into compact binary v2 framing.
124    pub fn to_bytes(&self) -> Result<Vec<u8>, CodecError> {
125        let mut w = ByteWriter::with_capacity(64);
126        w.write_raw(&HOT_PATCH_WIRE_MAGIC);
127        w.write_u8(HOT_PATCH_VERSION);
128        match self {
129            Self::TemplatePatch {
130                generation,
131                template_key,
132                node_path,
133                target_test_id,
134                row_patch_words,
135                text_updates,
136                text_replacements,
137            } => {
138                w.write_u8(1);
139                w.write_u64(*generation);
140                w.write_u64(*template_key);
141
142                w.write_len_max(node_path.len(), MAX_WIRE_ITEMS)?;
143                for &step in node_path {
144                    w.write_u16(step);
145                }
146
147                w.write_opt(target_test_id.as_deref(), |w, s| {
148                    w.write_str_max(s, DEFAULT_MAX_BYTES)
149                })?;
150
151                w.write_len_max(row_patch_words.len(), MAX_WIRE_ITEMS)?;
152                for &word in row_patch_words {
153                    w.write_u32(word);
154                }
155
156                w.write_len_max(text_updates.len(), MAX_WIRE_ITEMS)?;
157                for (idx, text) in text_updates {
158                    w.write_len(*idx)?;
159                    w.write_str_max(text, DEFAULT_MAX_BYTES)?;
160                }
161
162                w.write_len_max(text_replacements.len(), MAX_WIRE_ITEMS)?;
163                for (old_text, new_text) in text_replacements {
164                    w.write_str_max(old_text, DEFAULT_MAX_BYTES)?;
165                    w.write_str_max(new_text, DEFAULT_MAX_BYTES)?;
166                }
167            }
168            Self::DylibReload {
169                generation,
170                dylib_path,
171                build_ms,
172            } => {
173                w.write_u8(2);
174                w.write_u64(*generation);
175                w.write_str_max(dylib_path, DEFAULT_MAX_BYTES)?;
176                w.write_u64(*build_ms);
177            }
178            Self::DevStatus {
179                message,
180                latency_ms,
181            } => {
182                w.write_u8(3);
183                w.write_str_max(message, DEFAULT_MAX_BYTES)?;
184                w.write_u64(*latency_ms);
185            }
186            Self::ReloadAck {
187                generation,
188                ok,
189                applied,
190                applied_ms,
191                detail,
192            } => {
193                w.write_u8(4);
194                w.write_u64(*generation);
195                w.write_bool(*ok);
196                w.write_bool(*applied);
197                w.write_u64(*applied_ms);
198                w.write_str_max(detail, DEFAULT_MAX_BYTES)?;
199            }
200            Self::ClientHello {
201                client_kind,
202                bundle_hash,
203                reloaded_generation,
204            } => {
205                w.write_u8(5);
206                w.write_str_max(client_kind, DEFAULT_MAX_BYTES)?;
207                w.write_str_max(bundle_hash, DEFAULT_MAX_BYTES)?;
208                w.write_u64(*reloaded_generation);
209            }
210        }
211        Ok(w.into_bytes())
212    }
213
214    /// Decodes a compact binary v2 hot-patch frame.
215    pub fn from_bytes(raw: &[u8]) -> Result<Self, HotPatchDecodeError> {
216        let mut r = ByteReader::new(raw);
217        r.expect_magic(&HOT_PATCH_WIRE_MAGIC)?;
218        let version = r.read_u8()?;
219        if version != HOT_PATCH_VERSION {
220            return Err(HotPatchDecodeError::UnsupportedVersion(version));
221        }
222        let variant = r.read_u8()?;
223        let msg = match variant {
224            1 => {
225                let generation = r.read_u64()?;
226                let template_key = r.read_u64()?;
227
228                let node_path = r.read_vec(MAX_WIRE_ITEMS, 2, |r| r.read_u16())?;
229
230                let target_test_id = r.read_opt(|r| r.read_string(DEFAULT_MAX_BYTES))?;
231
232                let row_patch_words = r.read_vec(MAX_WIRE_ITEMS, 4, |r| r.read_u32())?;
233
234                let text_updates = r.read_vec(MAX_WIRE_ITEMS, 8, |r| {
235                    let idx = r.read_u32()? as usize;
236                    let text = r.read_string(DEFAULT_MAX_BYTES)?;
237                    Ok((idx, text))
238                })?;
239
240                let text_replacements = r.read_vec(MAX_WIRE_ITEMS, 8, |r| {
241                    let old_t = r.read_string(DEFAULT_MAX_BYTES)?;
242                    let new_t = r.read_string(DEFAULT_MAX_BYTES)?;
243                    Ok((old_t, new_t))
244                })?;
245
246                Self::TemplatePatch {
247                    generation,
248                    template_key,
249                    node_path,
250                    target_test_id,
251                    row_patch_words,
252                    text_updates,
253                    text_replacements,
254                }
255            }
256            2 => Self::DylibReload {
257                generation: r.read_u64()?,
258                dylib_path: r.read_string(DEFAULT_MAX_BYTES)?,
259                build_ms: r.read_u64()?,
260            },
261            3 => Self::DevStatus {
262                message: r.read_string(DEFAULT_MAX_BYTES)?,
263                latency_ms: r.read_u64()?,
264            },
265            4 => Self::ReloadAck {
266                generation: r.read_u64()?,
267                ok: r.read_bool()?,
268                applied: r.read_bool()?,
269                applied_ms: r.read_u64()?,
270                detail: r.read_string(DEFAULT_MAX_BYTES)?,
271            },
272            5 => Self::ClientHello {
273                client_kind: r.read_string(DEFAULT_MAX_BYTES)?,
274                bundle_hash: r.read_string(DEFAULT_MAX_BYTES)?,
275                reloaded_generation: r.read_u64()?,
276            },
277            other => return Err(HotPatchDecodeError::UnknownVariant(other)),
278        };
279        r.finish()?;
280        Ok(msg)
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    #[test]
289    fn hot_patch_v2_roundtrips_all_variants_and_rejects_corrupt_inputs() {
290        let key = 0x5EED_0000_0000_0002_u64;
291        let cases = vec![
292            HotPatchMsg::TemplatePatch {
293                generation: 42,
294                template_key: key,
295                node_path: vec![0, 2, 1],
296                target_test_id: Some("studio-panel".into()),
297                row_patch_words: vec![1, 0x1122_3344, 0x5566_7788, 1, 0, u32::MAX, 0x3F80_0000],
298                text_updates: vec![(0, "AETHER".into()), (3, "東京テスト".into())],
299                text_replacements: vec![("Old".into(), "New".into())],
300            },
301            HotPatchMsg::TemplatePatch {
302                generation: 1,
303                template_key: 0,
304                node_path: vec![],
305                target_test_id: None,
306                row_patch_words: vec![],
307                text_updates: vec![],
308                text_replacements: vec![],
309            },
310            HotPatchMsg::DylibReload {
311                generation: 99,
312                dylib_path: "target/debug/libnativeview_studio_workspace.dylib".into(),
313                build_ms: 287,
314            },
315            HotPatchMsg::DevStatus {
316                message: "watching 4 crates".into(),
317                latency_ms: 8,
318            },
319            HotPatchMsg::ReloadAck {
320                generation: 99,
321                ok: true,
322                applied: true,
323                applied_ms: 14,
324                detail: String::new(),
325            },
326            HotPatchMsg::ReloadAck {
327                generation: 100,
328                ok: false,
329                applied: false,
330                applied_ms: 3,
331                detail: "dlopen failed".into(),
332            },
333            HotPatchMsg::ClientHello {
334                client_kind: "web".into(),
335                bundle_hash: "a1b2c3d4e5f60718".into(),
336                reloaded_generation: 99,
337            },
338        ];
339
340        for msg in &cases {
341            let bin = msg.to_bytes().unwrap();
342            assert!(bin.starts_with(&HOT_PATCH_WIRE_MAGIC));
343            assert_eq!(bin[HOT_PATCH_WIRE_MAGIC.len()], HOT_PATCH_VERSION);
344            assert_eq!(HotPatchMsg::from_bytes(&bin).unwrap(), *msg);
345            for cut in 0..bin.len() {
346                assert_eq!(
347                    HotPatchMsg::from_bytes(&bin[..cut]),
348                    Err(HotPatchDecodeError::Truncated)
349                );
350            }
351            let mut extended = bin.clone();
352            extended.push(0xAA);
353            assert_eq!(
354                HotPatchMsg::from_bytes(&extended),
355                Err(HotPatchDecodeError::TrailingBytes(1))
356            );
357        }
358
359        assert_eq!(
360            HotPatchMsg::from_bytes(b"WRONG_MAGIC_1234\x02\x01"),
361            Err(HotPatchDecodeError::InvalidMagic)
362        );
363        // Older v1 frames (version byte = 1) are rejected cleanly as UnsupportedVersion.
364        let mut bad_ver = Vec::from(HOT_PATCH_WIRE_MAGIC);
365        bad_ver.extend_from_slice(&[1, 1]);
366        assert_eq!(
367            HotPatchMsg::from_bytes(&bad_ver),
368            Err(HotPatchDecodeError::UnsupportedVersion(1))
369        );
370        let mut bad_var = Vec::from(HOT_PATCH_WIRE_MAGIC);
371        bad_var.extend_from_slice(&[HOT_PATCH_VERSION, 0xFF]);
372        assert_eq!(
373            HotPatchMsg::from_bytes(&bad_var),
374            Err(HotPatchDecodeError::UnknownVariant(0xFF))
375        );
376        let mut bad_oom = Vec::from(HOT_PATCH_WIRE_MAGIC);
377        bad_oom.push(HOT_PATCH_VERSION);
378        bad_oom.push(1);
379        bad_oom.extend_from_slice(&1u64.to_le_bytes()); // generation
380        bad_oom.extend_from_slice(&0u64.to_le_bytes()); // template_key
381        bad_oom.extend_from_slice(&(u32::MAX).to_le_bytes()); // node_path len
382        assert_eq!(
383            HotPatchMsg::from_bytes(&bad_oom),
384            Err(HotPatchDecodeError::LimitExceeded)
385        );
386        assert_eq!(
387            HotPatchMsg::from_bytes(br#"{"type":"dev_status","message":"x","latency_ms":0}"#),
388            Err(HotPatchDecodeError::InvalidMagic)
389        );
390        let mut bad_utf8 = Vec::from(HOT_PATCH_WIRE_MAGIC);
391        bad_utf8.push(HOT_PATCH_VERSION);
392        bad_utf8.push(3);
393        bad_utf8.extend_from_slice(&2u32.to_le_bytes());
394        bad_utf8.extend_from_slice(&[0xFF, 0xFE]);
395        bad_utf8.extend_from_slice(&0u64.to_le_bytes());
396        assert_eq!(
397            HotPatchMsg::from_bytes(&bad_utf8),
398            Err(HotPatchDecodeError::InvalidUtf8)
399        );
400        let mut bad_bool = Vec::from(HOT_PATCH_WIRE_MAGIC);
401        bad_bool.push(HOT_PATCH_VERSION);
402        bad_bool.push(1);
403        bad_bool.extend_from_slice(&1u64.to_le_bytes()); // generation
404        bad_bool.extend_from_slice(&0u64.to_le_bytes()); // template_key
405        bad_bool.extend_from_slice(&0u32.to_le_bytes()); // node_path len = 0
406        bad_bool.push(7); // invalid Option tag for target_test_id
407        assert_eq!(
408            HotPatchMsg::from_bytes(&bad_bool),
409            Err(HotPatchDecodeError::InvalidBool(7))
410        );
411
412        // Encode-side cap matches decoder MAX_WIRE_ITEMS so oversized frames fail at encode time.
413        let oversized = HotPatchMsg::TemplatePatch {
414            generation: 1,
415            template_key: 0,
416            node_path: vec![0; MAX_WIRE_ITEMS + 1],
417            target_test_id: None,
418            row_patch_words: vec![],
419            text_updates: vec![],
420            text_replacements: vec![],
421        };
422        assert_eq!(
423            oversized.to_bytes(),
424            Err(CodecError::LenOverflow {
425                len: MAX_WIRE_ITEMS + 1,
426                max: MAX_WIRE_ITEMS,
427            })
428        );
429    }
430}