use std::fmt;
use nativeview_codec::{ByteReader, ByteWriter, CodecError, DEFAULT_MAX_BYTES};
pub const HOT_PATCH_WIRE_MAGIC: [u8; 16] = *b"NV_HOT_PATCH\0\0\0\0";
pub const HOT_PATCH_VERSION: u8 = 2;
const MAX_WIRE_ITEMS: usize = 65_536;
#[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 {}
#[derive(Debug, Clone, PartialEq)]
pub enum HotPatchMsg {
TemplatePatch {
generation: u64,
template_key: u64,
node_path: Vec<u16>,
target_test_id: Option<String>,
row_patch_words: Vec<u32>,
text_updates: Vec<(usize, String)>,
text_replacements: Vec<(String, String)>,
},
DylibReload {
generation: u64,
dylib_path: String,
build_ms: u64,
},
DevStatus {
message: String,
latency_ms: u64,
},
ReloadAck {
generation: u64,
ok: bool,
applied: bool,
applied_ms: u64,
detail: String,
},
ClientHello {
client_kind: String,
bundle_hash: String,
reloaded_generation: u64,
},
}
impl HotPatchMsg {
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())
}
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)
);
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()); bad_oom.extend_from_slice(&0u64.to_le_bytes()); bad_oom.extend_from_slice(&(u32::MAX).to_le_bytes()); 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()); bad_bool.extend_from_slice(&0u64.to_le_bytes()); bad_bool.extend_from_slice(&0u32.to_le_bytes()); bad_bool.push(7); assert_eq!(
HotPatchMsg::from_bytes(&bad_bool),
Err(HotPatchDecodeError::InvalidBool(7))
);
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,
})
);
}
}