From 90ba852a0cc2729138c5fab518b97afc893b951e Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Fri, 20 Nov 2026 21:04:37 +0100 Subject: [PATCH 1/2] feat(wasm,lsp): add client-side xtce-wasm decoder and xtce lsp server --- Cargo.lock | 9 + README.md | 3 +- crates/xtce-cli/README.md | 3 + crates/xtce-cli/src/lsp.rs | 609 +++++++++++++++++++++++++ crates/xtce-cli/src/main.rs | 5 + crates/xtce-wasm/Cargo.toml | 17 + crates/xtce-wasm/README.md | 20 + crates/xtce-wasm/src/lib.rs | 865 ++++++++++++++++++++++++++++++++++++ 8 files changed, 1530 insertions(+), 1 deletion(-) create mode 100644 crates/xtce-cli/src/lsp.rs create mode 100644 crates/xtce-wasm/Cargo.toml create mode 100644 crates/xtce-wasm/README.md create mode 100644 crates/xtce-wasm/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 2ff633f..e453264 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -981,6 +981,15 @@ dependencies = [ name = "xtce-pus" version = "0.2.1" +[[package]] +name = "xtce-wasm" +version = "0.2.1" +dependencies = [ + "xtce-decode", + "xtce-model", + "xtce-pus", +] + [[package]] name = "zerocopy" version = "0.8.56" diff --git a/README.md b/README.md index 9fe69f8..0e28a87 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,8 @@ validated against that same implementation packet for packet. | [`xtce-decode`](https://crates.io/crates/xtce-decode) | IR + `&[u8]` / `PacketReader` → parameter values | | [`xtce-codegen`](https://crates.io/crates/xtce-codegen) | IR → a static Rust decoder with every offset baked in | | [`xtce-pus`](https://crates.io/crates/xtce-pus) | `#![no_std]` ECSS-E-ST-70-41C (PUS-C) framing, CRC-16-CCITT, and HIL OBC responder | -| [`xtce-cli`](https://crates.io/crates/xtce-cli) | `xtce info`, `xtce decode`, `xtce codegen`, `xtce compile`, `xtce wireshark`, `xtce pcap`, `xtce encode`, `xtce pus`, `xtce diff`, `xtce validate`, `xtce sim`, `xtce bench` | +| [`xtce-cli`](https://crates.io/crates/xtce-cli) | `xtce info`, `xtce decode`, `xtce codegen`, `xtce compile`, `xtce wireshark`, `xtce pcap`, `xtce encode`, `xtce pus`, `xtce diff`, `xtce validate`, `xtce sim`, `xtce lsp`, `xtce bench` | +| `xtce-wasm` | Client-side WebAssembly (`wasm32-unknown-unknown`) XTCE 1.2, CCSDS, ECSS PUS-C & `.pcap` decoder | | `xtce-py` | Python bindings (PyO3), built by `maturin` | | `xtask` | differential test harness against the Python reference | diff --git a/crates/xtce-cli/README.md b/crates/xtce-cli/README.md index 2bb6350..8a36562 100644 --- a/crates/xtce-cli/README.md +++ b/crates/xtce-cli/README.md @@ -60,6 +60,9 @@ $ xtce compile ecss_pus.xml --target wireshark -o mission.lua $ xtce compile ecss_pus.xml --target json-schema -o mission.schema.json $ xtce compile ecss_pus.xml --target docs -o MISSION_DICTIONARY.md $ xtce compile ecss_pus.xml --target dashboard -o telemetry_studio.json + +# 11. Run the XTCE 1.2 Language Server Protocol (LSP) JSON-RPC server over stdio +$ xtce lsp ``` Part of [RustSpaceLab/xtce-rs](https://github.com/RustSpaceLab/xtce-rs). diff --git a/crates/xtce-cli/src/lsp.rs b/crates/xtce-cli/src/lsp.rs new file mode 100644 index 0000000..83420b6 --- /dev/null +++ b/crates/xtce-cli/src/lsp.rs @@ -0,0 +1,609 @@ +//! `xtce lsp` — Language Server Protocol (LSP) server for OMG XTCE 1.2 XML mission databases. +//! +//! Speaks standard JSON-RPC 2.0 over `stdin`/`stdout` with `Content-Length` framing and provides +//! real-time IDE intelligence for spacecraft engineers editing large XTCE 1.2 definitions in +//! VS Code, RustRover, Neovim, or Helix: +//! - `textDocument/didOpen`, `textDocument/didChange`, `textDocument/didSave`: parses the XML +//! buffer into an [`XtceDb`], validates container inheritance, bit-layout compilability, and +//! dangling references, and publishes `textDocument/publishDiagnostics`. +//! - `textDocument/hover`: resolves the identifier or attribute value under the cursor against +//! parameters, parameter types, sequence containers, and telecommands, rendering a Markdown +//! card with type signature, bit width, byte order, calibration, and container bit offsets. +//! - `textDocument/definition`: jumps to the line and column where the referenced +//! ``, `<*ParameterType>`, ``, or `` is defined. +//! - `textDocument/documentSymbol`: populates the IDE outline tree with all containers, +//! parameters, and telecommands. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::io::{BufRead, BufReader, Write}; + +use xtce_model::{ByteOrder, DataEncoding, TypeKind, XtceDb}; + +use crate::validate::{self, Level}; + +/// Maximum LSP message payload size accepted from `stdin` (32 MiB) to prevent unbounded allocation. +const MAX_LSP_BODY_BYTES: usize = 32 * 1024 * 1024; + +/// In-memory state of the XTCE Language Server. +#[derive(Default)] +pub struct LspServer { + documents: BTreeMap, + shutdown_requested: bool, +} + +/// Runs the `xtce lsp` JSON-RPC 2.0 loop over standard input and standard output. +/// +/// # Errors +/// +/// Returns an error if reading from standard input or writing to standard output fails. +pub fn run_stdio() -> Result<(), Box> { + let stdin = std::io::stdin(); + let stdout = std::io::stdout(); + let mut reader = BufReader::new(stdin.lock()); + let mut writer = stdout.lock(); + let mut server = LspServer::default(); + server.serve(&mut reader, &mut writer) +} + +impl LspServer { + /// Processes framed JSON-RPC messages from `reader` and writes responses/notifications to `out`. + /// + /// # Errors + /// + /// Returns an I/O error if stream reading or writing fails. + pub fn serve( + &mut self, + reader: &mut impl BufRead, + out: &mut impl Write, + ) -> Result<(), Box> { + while let Some(body) = read_lsp_frame(reader)? { + let should_exit = self.handle_message(&body, out)?; + out.flush()?; + if should_exit { + break; + } + } + Ok(()) + } + + fn handle_message(&mut self, body: &str, out: &mut impl Write) -> std::io::Result { + let Some(method) = extract_json_str(body, "method") else { + return Ok(false); + }; + let id_raw = extract_json_id(body); + + match method.as_str() { + "initialize" => { + if let Some(id) = id_raw { + let result = r#"{"capabilities":{"textDocumentSync":1,"hoverProvider":true,"definitionProvider":true,"documentSymbolProvider":true},"serverInfo":{"name":"xtce-lsp","version":"0.2.2"}}"#; + write_rpc_result(out, &id, result)?; + } + } + "initialized" => {} + "shutdown" => { + self.shutdown_requested = true; + if let Some(id) = id_raw { + write_rpc_result(out, &id, "null")?; + } + } + "exit" => return Ok(true), + "textDocument/didOpen" | "textDocument/didChange" => { + if let Some(uri) = extract_json_str(body, "uri") { + if let Some(text) = extract_json_str(body, "text") { + let diag_json = build_diagnostics_notification(&uri, &text); + self.documents.insert(uri, text); + write_lsp_frame(out, &diag_json)?; + } + } + } + "textDocument/hover" => { + if let Some(id) = id_raw { + let resp = self.handle_hover(body); + write_rpc_result(out, &id, &resp)?; + } + } + "textDocument/definition" => { + if let Some(id) = id_raw { + let resp = self.handle_definition(body); + write_rpc_result(out, &id, &resp)?; + } + } + "textDocument/documentSymbol" => { + if let Some(id) = id_raw { + let resp = self.handle_document_symbols(body); + write_rpc_result(out, &id, &resp)?; + } + } + _ => { + if let Some(id) = id_raw { + write_rpc_result(out, &id, "null")?; + } + } + } + Ok(false) + } + + fn handle_hover(&self, body: &str) -> String { + let Some(uri) = extract_json_str(body, "uri") else { + return "null".to_owned(); + }; + let Some(doc) = self.documents.get(&uri) else { + return "null".to_owned(); + }; + let line = extract_json_usize(body, "line").unwrap_or(0); + let character = extract_json_usize(body, "character").unwrap_or(0); + + let Some(token) = word_at_position(doc, line, character) else { + return "null".to_owned(); + }; + let Ok(db) = XtceDb::from_xml(doc) else { + return "null".to_owned(); + }; + let Some(markdown) = build_hover_markdown(&db, token) else { + return "null".to_owned(); + }; + + let mut escaped = String::with_capacity(markdown.len() + 32); + escape_json_into(&markdown, &mut escaped); + format!(r#"{{"contents":{{"kind":"markdown","value":"{escaped}"}}}}"#) + } + + fn handle_definition(&self, body: &str) -> String { + let Some(uri) = extract_json_str(body, "uri") else { + return "null".to_owned(); + }; + let Some(doc) = self.documents.get(&uri) else { + return "null".to_owned(); + }; + let line = extract_json_usize(body, "line").unwrap_or(0); + let character = extract_json_usize(body, "character").unwrap_or(0); + + let Some(token) = word_at_position(doc, line, character) else { + return "null".to_owned(); + }; + let Some((def_line, def_col)) = find_xml_definition_line(doc, token) else { + return "null".to_owned(); + }; + + let mut uri_esc = String::with_capacity(uri.len()); + escape_json_into(&uri, &mut uri_esc); + let end_col = def_col + token.len(); + format!( + r#"{{"uri":"{uri_esc}","range":{{"start":{{"line":{def_line},"character":{def_col}}},"end":{{"line":{def_line},"character":{end_col}}}}}}}"# + ) + } + + fn handle_document_symbols(&self, body: &str) -> String { + let Some(uri) = extract_json_str(body, "uri") else { + return "[]".to_owned(); + }; + let Some(doc) = self.documents.get(&uri) else { + return "[]".to_owned(); + }; + let Ok(db) = XtceDb::from_xml(doc) else { + return "[]".to_owned(); + }; + + let mut out = String::with_capacity(2048); + out.push('['); + let mut first = true; + + for c in db.containers() { + let name = db.name(c.name); + let (line, col) = find_xml_definition_line(doc, name).unwrap_or((0, 0)); + append_symbol_json(&mut out, &mut first, name, 23, line, col); + } + for p in db.parameters() { + let name = db.name(p.name); + let (line, col) = find_xml_definition_line(doc, name).unwrap_or((0, 0)); + append_symbol_json(&mut out, &mut first, name, 8, line, col); + } + for cmd in db.meta_commands() { + let name = db.name(cmd.name); + let (line, col) = find_xml_definition_line(doc, name).unwrap_or((0, 0)); + append_symbol_json(&mut out, &mut first, name, 12, line, col); + } + + out.push(']'); + out + } +} + +fn append_symbol_json( + out: &mut String, + first: &mut bool, + name: &str, + kind: u8, + line: usize, + col: usize, +) { + if !*first { + out.push(','); + } + *first = false; + out.push_str(r#"{"name":""#); + escape_json_into(name, out); + let end_col = col + name.len(); + let _ = write!( + out, + r#"","kind":{kind},"range":{{"start":{{"line":{line},"character":{col}}},"end":{{"line":{line},"character":{end_col}}}}},"selectionRange":{{"start":{{"line":{line},"character":{col}}},"end":{{"line":{line},"character":{end_col}}}}}}}"# + ); +} + +/// Builds markdown documentation for a parameter, parameter type, container, or telecommand. +#[must_use] +pub fn build_hover_markdown(db: &XtceDb, symbol: &str) -> Option { + let mut md = String::with_capacity(512); + + if let Some(param_id) = db.find_parameter(symbol) { + let param = db.parameter(param_id)?; + let p_name = db.name(param.name); + let q_name = db.name(param.qualified_name); + let _ = writeln!(md, "### Parameter `{p_name}`\n"); + let _ = writeln!(md, "- **Qualified Path:** `{q_name}`"); + if let Some(desc) = param.short_description { + let _ = writeln!(md, "- **Description:** {}", db.name(desc)); + } + if let Some(ty) = db.parameter_type(param.type_id) { + append_type_details(db, ty, &mut md); + } + return Some(md); + } + + if let Some(container_id) = db.find_container(symbol) { + let container = db.container(container_id)?; + let c_name = db.name(container.name); + let q_name = db.name(container.qualified_name); + let kind = if container.is_abstract { + "Abstract SequenceContainer" + } else if container.is_command { + "CommandContainer" + } else { + "Concrete SequenceContainer" + }; + let _ = writeln!(md, "### {kind} `{c_name}`\n"); + let _ = writeln!(md, "- **Qualified Path:** `{q_name}`"); + if let Some(base_id) = container.base { + if let Some(base) = db.container(base_id) { + let _ = writeln!(md, "- **Extends:** `{}`", db.name(base.name)); + } + } + let _ = writeln!(md, "- **Direct Entries:** {}", container.entries.len()); + let _ = writeln!(md, "- **Inheritors:** {}", container.inheritors.len()); + return Some(md); + } + + if let Some(type_id) = db.find_type(symbol) { + let ty = db.parameter_type(type_id)?; + let t_name = db.name(ty.name); + let _ = writeln!(md, "### ParameterType `{t_name}`\n"); + append_type_details(db, ty, &mut md); + return Some(md); + } + + if let Some(cmd_id) = db.find_meta_command(symbol) { + let cmd = db.meta_command(cmd_id)?; + let c_name = db.name(cmd.name); + let _ = writeln!(md, "### MetaCommand `{c_name}`\n"); + let _ = writeln!(md, "- **Abstract:** `{}`", cmd.is_abstract); + let _ = writeln!(md, "- **Arguments:** {}", cmd.arguments.len()); + return Some(md); + } + + None +} + +fn append_type_details(db: &XtceDb, ty: &xtce_model::ParameterType, md: &mut String) { + let _ = writeln!( + md, + "- **Type:** `{}` (`{}`)", + db.name(ty.name), + ty.kind.label() + ); + if let Some(bits) = ty.fixed_size_in_bits() { + let _ = writeln!(md, "- **Size:** `{bits}` bits"); + } else { + let _ = writeln!(md, "- **Size:** dynamic / variable"); + } + let order = match &ty.encoding { + DataEncoding::Integer(enc) => Some(enc.byte_order), + DataEncoding::Float(enc) => Some(enc.byte_order), + DataEncoding::String(enc) => Some(enc.byte_order), + DataEncoding::Binary(_) | DataEncoding::None => None, + }; + if let Some(bo) = order { + let label = match bo { + ByteOrder::MostSignificantFirst => "mostSignificantByteFirst (Big-Endian)", + ByteOrder::LeastSignificantFirst => "leastSignificantByteFirst (Little-Endian)", + }; + let _ = writeln!(md, "- **Byte Order:** `{label}`"); + } + if let TypeKind::Enumerated(enums) = &ty.kind { + let _ = writeln!(md, "- **Enumerations:** {} items", enums.entries().len()); + } +} + +fn build_diagnostics_notification(uri: &str, xml_text: &str) -> String { + let mut out = String::with_capacity(1024); + out.push_str( + r#"{"jsonrpc":"2.0","method":"textDocument/publishDiagnostics","params":{"uri":""#, + ); + escape_json_into(uri, &mut out); + out.push_str(r#"","diagnostics":["#); + + match XtceDb::from_xml(xml_text) { + Ok(db) => { + let report = validate::validate_db(&db, None); + for (idx, diag) in report.diagnostics.iter().enumerate() { + if idx > 0 { + out.push(','); + } + let severity = match diag.level { + Level::Error => 1, + Level::Warning => 2, + }; + let (line, col) = + find_xml_definition_line(xml_text, &diag.subject).unwrap_or((0, 0)); + append_diagnostic_entry( + &mut out, + line, + col, + severity, + &diag.subject, + &diag.message, + ); + } + } + Err(err) => { + let msg = err.to_string(); + append_diagnostic_entry(&mut out, 0, 0, 1, "xtce-model", &msg); + } + } + + out.push_str("]}}"); + out +} + +fn append_diagnostic_entry( + out: &mut String, + line: usize, + col: usize, + severity: u8, + subject: &str, + message: &str, +) { + let _ = write!( + out, + r#"{{"range":{{"start":{{"line":{line},"character":{col}}},"end":{{"line":{line},"character":{}}}}},"severity":{severity},"source":"xtce-lsp","message":""#, + col + subject.len().max(1) + ); + escape_json_into(subject, out); + out.push_str(": "); + escape_json_into(message, out); + out.push_str(r#""}"#); +} + +/// Finds the 0-based `(line, column)` where `name="symbol"` appears in `xml_text`. +#[must_use] +pub fn find_xml_definition_line(xml_text: &str, symbol: &str) -> Option<(usize, usize)> { + let leaf = symbol.rsplit('/').next().unwrap_or(symbol); + let needle = format!(r#"name="{leaf}""#); + for (line_idx, line_str) in xml_text.lines().enumerate() { + if let Some(pos) = line_str.find(&needle) { + return Some((line_idx, pos + 6)); + } + } + None +} + +fn word_at_position(text: &str, line: usize, character: usize) -> Option<&str> { + let target_line = text.lines().nth(line)?; + let bytes = target_line.as_bytes(); + if bytes.is_empty() { + return None; + } + let idx = character.min(bytes.len().saturating_sub(1)); + if !is_ident_byte(*bytes.get(idx)?) { + return None; + } + let mut start = idx; + while start > 0 && is_ident_byte(bytes[start - 1]) { + start -= 1; + } + let mut end = idx; + while end < bytes.len() && is_ident_byte(bytes[end]) { + end += 1; + } + target_line.get(start..end) +} + +const fn is_ident_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || b == b'.' || b == b'/' +} + +fn read_lsp_frame(reader: &mut impl BufRead) -> std::io::Result> { + let mut content_length: Option = None; + let mut line = String::new(); + + loop { + line.clear(); + let n = reader.read_line(&mut line)?; + if n == 0 { + return Ok(None); + } + let trimmed = line.trim(); + if trimmed.is_empty() { + break; + } + if let Some(rest) = trimmed.strip_prefix("Content-Length:") { + content_length = rest.trim().parse::().ok(); + } else if let Some(rest) = trimmed.strip_prefix("content-length:") { + content_length = rest.trim().parse::().ok(); + } + } + + let Some(len) = content_length else { + return Ok(None); + }; + if len > MAX_LSP_BODY_BYTES { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "LSP frame exceeds MAX_LSP_BODY_BYTES (32 MiB)", + )); + } + + let mut buf = vec![0u8; len]; + reader.read_exact(&mut buf)?; + String::from_utf8(buf) + .map(Some) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) +} + +fn write_lsp_frame(out: &mut impl Write, json_body: &str) -> std::io::Result<()> { + write!( + out, + "Content-Length: {}\r\n\r\n{json_body}", + json_body.len() + ) +} + +fn write_rpc_result(out: &mut impl Write, id_raw: &str, result_json: &str) -> std::io::Result<()> { + let body = format!(r#"{{"jsonrpc":"2.0","id":{id_raw},"result":{result_json}}}"#); + write_lsp_frame(out, &body) +} + +fn extract_json_str(json: &str, key: &str) -> Option { + let pattern = format!(r#""{key}""#); + let start = json.find(&pattern)? + pattern.len(); + let rest = json.get(start..)?.trim_start(); + let rest = rest.strip_prefix(':')?.trim_start(); + let rest = rest.strip_prefix('"')?; + + let mut out = String::new(); + let mut chars = rest.chars(); + while let Some(ch) = chars.next() { + if ch == '"' { + return Some(out); + } + if ch == '\\' { + match chars.next()? { + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + '"' => out.push('"'), + '\\' => out.push('\\'), + '/' => out.push('/'), + other => out.push(other), + } + } else { + out.push(ch); + } + } + None +} + +fn extract_json_usize(json: &str, key: &str) -> Option { + let pattern = format!(r#""{key}""#); + let start = json.find(&pattern)? + pattern.len(); + let rest = json.get(start..)?.trim_start(); + let rest = rest.strip_prefix(':')?.trim_start(); + let digits: String = rest.chars().take_while(char::is_ascii_digit).collect(); + digits.parse::().ok() +} + +fn extract_json_id(json: &str) -> Option { + let start = json.find(r#""id""#)? + 4; + let rest = json.get(start..)?.trim_start(); + let rest = rest.strip_prefix(':')?.trim_start(); + if rest.starts_with('"') { + let end = rest.get(1..)?.find('"')? + 2; + return rest.get(..end).map(str::to_owned); + } + let digits: String = rest + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '-') + .collect(); + if digits.is_empty() { + None + } else { + Some(digits) + } +} + +fn escape_json_into(input: &str, out: &mut String) { + for ch in input.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c => out.push(c), + } + } +} + +#[cfg(test)] +mod tests { + use std::io::Cursor; + + use xtce_model::XtceDb; + + use super::{LspServer, build_hover_markdown, find_xml_definition_line}; + use crate::pus::ECSS_PUS_XTCE_XML; + + fn frame(json: &str) -> String { + format!("Content-Length: {}\r\n\r\n{json}", json.len()) + } + + #[test] + fn hover_and_definition_resolve_ecss_pus_parameters_and_containers() { + let db = XtceDb::from_xml(ECSS_PUS_XTCE_XML).expect("loads ECSS PUS XTCE"); + + let hover_param = build_hover_markdown(&db, "OBC_VBUS_V").expect("hover for OBC_VBUS_V"); + assert!(hover_param.contains("### Parameter `OBC_VBUS_V`")); + assert!(hover_param.contains("`16` bits")); + + let hover_cont = build_hover_markdown(&db, "TM_3_25_ObcHousekeeping") + .expect("hover for TM_3_25_ObcHousekeeping"); + assert!(hover_cont.contains("Concrete SequenceContainer `TM_3_25_ObcHousekeeping`")); + assert!(hover_cont.contains("Extends:** `CCSDSPacket`")); + + let (line, col) = + find_xml_definition_line(ECSS_PUS_XTCE_XML, "TM_3_25_ObcHousekeeping").expect("found"); + assert!(line > 10); + assert!(col > 0); + } + + #[test] + fn lsp_server_handles_initialize_did_open_hover_and_exit() { + let xml = r#""#; + let vbus_col = xml.find("VBUS").expect("VBUS in xml"); + let mut xml_escaped = String::new(); + super::escape_json_into(xml, &mut xml_escaped); + + let mut input = String::new(); + input.push_str(&frame( + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#, + )); + input.push_str(&frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"file:///mission.xml","text":"{xml_escaped}"}}}}}}"# + ))); + input.push_str(&frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"file:///mission.xml"}},"position":{{"line":0,"character":{vbus_col}}}}}}}"# + ))); + input.push_str(&frame(r#"{"jsonrpc":"2.0","id":3,"method":"shutdown"}"#)); + input.push_str(&frame(r#"{"jsonrpc":"2.0","method":"exit"}"#)); + + let mut reader = Cursor::new(input.into_bytes()); + let mut output = Vec::new(); + let mut server = LspServer::default(); + server.serve(&mut reader, &mut output).expect("LSP session"); + + let out_str = String::from_utf8(output).expect("utf8"); + assert!(out_str.contains(r#""name":"xtce-lsp""#)); + assert!(out_str.contains(r#""method":"textDocument/publishDiagnostics""#)); + assert!(out_str.contains("Parameter `VBUS`")); + } +} diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 2d2300a..18d8b12 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -24,6 +24,7 @@ mod decode; mod diff; mod encode; mod info; +mod lsp; mod pcap; mod pus; mod sim; @@ -283,6 +284,9 @@ enum Command { #[arg(long, short)] out: Option, }, + + /// Start the XTCE 1.2 Language Server Protocol (LSP) JSON-RPC server over stdio. + Lsp, } fn main() -> ExitCode { @@ -427,6 +431,7 @@ fn run(cli: Cli) -> Result<(), Box> { pcap_format: pcap, out: out.as_deref(), }), + Command::Lsp => lsp::run_stdio(), } } diff --git a/crates/xtce-wasm/Cargo.toml b/crates/xtce-wasm/Cargo.toml new file mode 100644 index 0000000..9e1d621 --- /dev/null +++ b/crates/xtce-wasm/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "xtce-wasm" +description = "Zero-bindgen client-side WebAssembly (wasm32-unknown-unknown) XTCE 1.2 and ECSS-E-ST-70-41C (PUS-C) telemetry & PCAP decoder." +version = "0.2.1" +edition = "2024" +rust-version = "1.85" +license = "MIT OR Apache-2.0" +repository = "https://github.com/RustSpaceLab/xtce-rs" +authors = ["Maciej Myszkiewicz"] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +xtce-model = { path = "../xtce-model", version = "0.2.1" } +xtce-decode = { path = "../xtce-decode", version = "0.2.1" } +xtce-pus = { path = "../xtce-pus", version = "0.2.1" } diff --git a/crates/xtce-wasm/README.md b/crates/xtce-wasm/README.md new file mode 100644 index 0000000..4ab3be5 --- /dev/null +++ b/crates/xtce-wasm/README.md @@ -0,0 +1,20 @@ +# `xtce-wasm` + +Zero-bindgen client-side WebAssembly (`wasm32-unknown-unknown`) XTCE 1.2 and ECSS-E-ST-70-41C (PUS-C) telemetry & Wireshark `.pcap` decoder. + +## Build + +```bash +rustup target add wasm32-unknown-unknown +cargo build -p xtce-wasm --target wasm32-unknown-unknown --release +``` + +## Exported WebAssembly C-ABI Functions + +- `wasm_alloc(len: usize) -> *mut u8` +- `wasm_free(ptr: *mut u8, len: usize)` +- `wasm_result_ptr() -> *const u8` +- `wasm_result_len() -> usize` +- `wasm_inspect_xtce(xml_ptr: *const u8, xml_len: usize) -> i32` +- `wasm_decode_xtce_and_packets(xml_ptr: *const u8, xml_len: usize, pkt_ptr: *const u8, pkt_len: usize, max_packets: usize) -> i32` +- `wasm_generate_pus_stream(scenario_id: u32, packet_count: usize, seed: u64, as_pcap: u32) -> i32` diff --git a/crates/xtce-wasm/src/lib.rs b/crates/xtce-wasm/src/lib.rs new file mode 100644 index 0000000..20c6700 --- /dev/null +++ b/crates/xtce-wasm/src/lib.rs @@ -0,0 +1,865 @@ +//! Client-side WebAssembly (`wasm32-unknown-unknown`) XTCE 1.2 & ECSS-E-ST-70-41C (PUS-C) +//! telemetry, PCAP, and mission database inspector. +//! +//! This crate compiles to a pure, zero-bindgen-CLI `cdylib` targeting `wasm32-unknown-unknown` +//! with raw C-ABI exports and linear-memory helpers so any browser or WebAssembly runtime can +//! inspect XTCE 1.2 XML definitions, decode raw CCSDS / ECSS PUS-C streams or Wireshark `.pcap` +//! captures, and generate deterministic fault-injection telemetry streams entirely in the browser +//! with zero server uploads. + +#![deny(missing_docs)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#![deny(clippy::todo, clippy::unimplemented)] +#![warn(clippy::pedantic)] +#![allow( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + clippy::cast_precision_loss, + clippy::cast_sign_loss, + clippy::module_name_repetitions, + clippy::similar_names, + clippy::too_many_lines +)] +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] + +use std::alloc::{Layout, alloc, dealloc}; +use std::cell::RefCell; +use std::fmt::Write as _; + +use xtce_decode::{DecodeError, Decoder, PacketIter, SpacePacketBytes}; +use xtce_model::{TypeKind, XtceDb}; +use xtce_pus::{ + CucTimestamp, MAX_HIL_FRAME_LEN, ObcHousekeeping, PusHeader, PusPacket, TmParams, encode_tm, + verify_crc16_ccitt, +}; + +thread_local! { + static RESULT_BUF: RefCell> = const { RefCell::new(Vec::new()) }; +} + +fn store_result(bytes: Vec) { + RESULT_BUF.with(|cell| { + *cell.borrow_mut() = bytes; + }); +} + +fn store_json_error(msg: &str) -> i32 { + let mut out = String::with_capacity(msg.len() + 32); + out.push_str("{\"ok\":false,\"error\":"); + push_json_str(&mut out, msg); + out.push('}'); + store_result(out.into_bytes()); + 1 +} + +/// Allocates `len` bytes in WebAssembly linear memory and returns a pointer for the host to write to. +#[unsafe(no_mangle)] +pub extern "C" fn wasm_alloc(len: usize) -> *mut u8 { + if len == 0 { + return std::ptr::null_mut(); + } + let Ok(layout) = Layout::from_size_align(len, 1) else { + return std::ptr::null_mut(); + }; + // SAFETY: `layout` has non-zero size (`len > 0`) and alignment 1. + unsafe { alloc(layout) } +} + +/// Frees a buffer previously allocated by [`wasm_alloc`]. +/// +/// # Safety +/// +/// `ptr` must have been returned by [`wasm_alloc`] with the exact same `len`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn wasm_free(ptr: *mut u8, len: usize) { + if ptr.is_null() || len == 0 { + return; + } + if let Ok(layout) = Layout::from_size_align(len, 1) { + // SAFETY: Caller guarantees `ptr` was allocated via `wasm_alloc(len)`. + unsafe { + dealloc(ptr, layout); + } + } +} + +/// Returns a pointer to the latest result buffer (JSON UTF-8 or binary stream) in linear memory. +#[unsafe(no_mangle)] +pub extern "C" fn wasm_result_ptr() -> *const u8 { + RESULT_BUF.with(|cell| cell.borrow().as_ptr()) +} + +/// Returns the byte length of the latest result buffer in linear memory. +#[unsafe(no_mangle)] +pub extern "C" fn wasm_result_len() -> usize { + RESULT_BUF.with(|cell| cell.borrow().len()) +} + +/// Inspects an XTCE 1.2 XML document in memory and writes a JSON summary of all space systems, +/// parameters, sequence containers, telecommands, and unsupported constructs into the result buffer. +/// +/// Returns `0` on success, or `1` if the XML cannot be parsed as a valid XTCE document. +/// +/// # Safety +/// +/// `xml_ptr` must point to a valid byte slice of length `xml_len` in linear memory. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn wasm_inspect_xtce(xml_ptr: *const u8, xml_len: usize) -> i32 { + if xml_ptr.is_null() || xml_len == 0 { + return store_json_error("empty XTCE XML buffer"); + } + // SAFETY: Caller guarantees `xml_ptr..xml_ptr + xml_len` is valid initialized memory. + let xml_bytes = unsafe { std::slice::from_raw_parts(xml_ptr, xml_len) }; + let Ok(xml_str) = std::str::from_utf8(xml_bytes) else { + return store_json_error("XTCE XML is not valid UTF-8"); + }; + match inspect_xtce_to_json(xml_str) { + Ok(json) => { + store_result(json.into_bytes()); + 0 + } + Err(err) => store_json_error(&err), + } +} + +/// Decodes a raw CCSDS packet stream or Wireshark `.pcap` capture against an XTCE 1.2 XML +/// definition and ECSS-E-ST-70-41C (PUS-C) parser, writing the complete JSON result into the +/// result buffer. +/// +/// Automatically detects `.pcap` global headers (`0xA1B2C3D4`, `0xD4C3B2A1`, `0xA1B23C4D`, +/// `0x4D3CB2A1`) and strips the 24-byte global header and 16-byte record headers in memory. +/// +/// Returns `0` on success, or `1` on fatal error. +/// +/// # Safety +/// +/// `xml_ptr` and `pkt_ptr` must point to valid byte slices of lengths `xml_len` and `pkt_len`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn wasm_decode_xtce_and_packets( + xml_ptr: *const u8, + xml_len: usize, + pkt_ptr: *const u8, + pkt_len: usize, + max_packets: usize, +) -> i32 { + if xml_ptr.is_null() || xml_len == 0 { + return store_json_error("empty XTCE XML buffer"); + } + if pkt_ptr.is_null() || pkt_len == 0 { + return store_json_error("empty packet/PCAP buffer"); + } + // SAFETY: Caller guarantees both slices are valid in linear memory. + let xml_bytes = unsafe { std::slice::from_raw_parts(xml_ptr, xml_len) }; + // SAFETY: Caller guarantees both slices are valid in linear memory. + let pkt_bytes = unsafe { std::slice::from_raw_parts(pkt_ptr, pkt_len) }; + let Ok(xml_str) = std::str::from_utf8(xml_bytes) else { + return store_json_error("XTCE XML is not valid UTF-8"); + }; + + let limit = if max_packets == 0 { 500 } else { max_packets }; + match decode_xtce_and_packets_to_json(xml_str, pkt_bytes, limit) { + Ok(json) => { + store_result(json.into_bytes()); + 0 + } + Err(err) => store_json_error(&err), + } +} + +/// Generates a deterministic CCSDS / ECSS-E-ST-70-41C (PUS-C) binary stream (or `.pcap` capture +/// when `as_pcap != 0`) directly in WebAssembly memory and stores the bytes in the result buffer. +/// +/// `scenario_id`: +/// * `0` = Nominal orbital pass +/// * `1` = Eclipse voltage drop (21.4 V -> SAFE mode) +/// * `2` = OBC thermal runaway (+68.5 °C -> SAFE mode) +/// * `3` = RF downlink sequence gap +/// * `4` = Watchdog cold reboot +/// * `5` = ADCS attitude tumble +/// * `6` = ADC sensor glitch spike +#[unsafe(no_mangle)] +pub extern "C" fn wasm_generate_pus_stream( + scenario_id: u32, + packet_count: usize, + seed: u64, + as_pcap: u32, +) -> i32 { + let count = packet_count.clamp(1, 5_000); + let raw = generate_pus_stream_bytes(scenario_id, count, seed); + if as_pcap != 0 { + let pcap = wrap_in_pcap(&raw); + store_result(pcap); + } else { + store_result(raw); + } + 0 +} + +fn push_json_str(out: &mut String, s: &str) { + out.push('"'); + for ch in s.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => { + let _ = write!(out, "\\u{:04x}", c as u32); + } + c => out.push(c), + } + } + out.push('"'); +} + +fn type_kind_label(kind: &TypeKind) -> &'static str { + match kind { + TypeKind::Integer => "integer", + TypeKind::Float => "float", + TypeKind::String => "string", + TypeKind::Binary => "binary", + TypeKind::Boolean { .. } => "boolean", + TypeKind::Enumerated(_) => "enumerated", + TypeKind::AbsoluteTime { .. } => "absolute-time", + TypeKind::RelativeTime => "relative-time", + TypeKind::Aggregate { .. } => "aggregate", + TypeKind::Array { .. } => "array", + TypeKind::Unsupported { .. } => "unsupported", + } +} + +/// Parses an XTCE 1.2 XML string and returns a JSON summary of the database. +/// +/// # Errors +/// +/// Returns an error string if the XML is malformed or fails XTCE lowering. +pub fn inspect_xtce_to_json(xml_str: &str) -> Result { + let db = XtceDb::from_xml(xml_str).map_err(|e| e.to_string())?; + let stats = db.stats(); + + let root_name = db + .space_systems() + .first() + .map_or("Unknown", |ss| db.name(ss.name)); + let default_root_container = db + .default_root_container() + .and_then(|id| db.container(id)) + .map(|c| db.name(c.name)); + + let mut out = String::with_capacity(4096); + out.push_str("{\"ok\":true,\"root_space_system\":"); + push_json_str(&mut out, root_name); + out.push_str(",\"xmlns\":"); + if let Some(ns) = db.xmlns() { + push_json_str(&mut out, ns); + } else { + out.push_str("null"); + } + out.push_str(",\"default_root_container\":"); + if let Some(rc) = default_root_container { + push_json_str(&mut out, rc); + } else { + out.push_str("null"); + } + + let _ = write!( + out, + ",\"stats\":{{\"space_systems\":{},\"parameters\":{},\"parameter_types\":{},\"decodable_parameter_types\":{},\"containers\":{},\"abstract_containers\":{},\"concrete_containers\":{},\"entries\":{},\"meta_commands\":{},\"unsupported\":{}}}", + stats.space_systems, + stats.parameters, + stats.parameter_types, + stats.decodable_parameter_types, + stats.containers, + stats.abstract_containers, + stats.containers.saturating_sub(stats.abstract_containers), + stats.entries, + stats.meta_commands, + stats.unsupported + ); + + out.push_str(",\"space_systems\":["); + for (i, ss) in db.space_systems().iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str("{\"name\":"); + push_json_str(&mut out, db.name(ss.name)); + out.push_str(",\"qualified_name\":"); + push_json_str(&mut out, db.name(ss.qualified_name)); + out.push('}'); + } + out.push(']'); + + out.push_str(",\"containers\":["); + for (i, c) in db.containers().iter().take(200).enumerate() { + if i > 0 { + out.push(','); + } + out.push_str("{\"name\":"); + push_json_str(&mut out, db.name(c.name)); + out.push_str(",\"qualified_name\":"); + push_json_str(&mut out, db.name(c.qualified_name)); + let base_name = c + .base + .and_then(|bid| db.container(bid)) + .map(|b| db.name(b.name)); + out.push_str(",\"base\":"); + if let Some(bn) = base_name { + push_json_str(&mut out, bn); + } else { + out.push_str("null"); + } + let _ = write!( + out, + ",\"abstract\":{},\"is_command\":{},\"entries\":{}}}", + c.is_abstract, + c.is_command, + c.entries.len() + ); + } + out.push(']'); + + out.push_str(",\"parameters\":["); + for (i, p) in db.parameters().iter().take(250).enumerate() { + if i > 0 { + out.push(','); + } + out.push_str("{\"name\":"); + push_json_str(&mut out, db.name(p.name)); + let (kind_str, bits_opt, unit_str) = + db.parameter_type(p.type_id) + .map_or(("unknown", None, ""), |ty| { + let u = ty.units.first().map_or("", |uid| db.name(*uid)); + (type_kind_label(&ty.kind), ty.fixed_size_in_bits(), u) + }); + out.push_str(",\"kind\":"); + push_json_str(&mut out, kind_str); + out.push_str(",\"bits\":"); + if let Some(b) = bits_opt { + let _ = write!(out, "{b}"); + } else { + out.push_str("null"); + } + out.push_str(",\"unit\":"); + push_json_str(&mut out, unit_str); + out.push('}'); + } + out.push(']'); + + out.push_str(",\"telecommands\":["); + for (i, cmd) in db.meta_commands().iter().take(100).enumerate() { + if i > 0 { + out.push(','); + } + out.push_str("{\"name\":"); + push_json_str(&mut out, db.name(cmd.name)); + let _ = write!( + out, + ",\"abstract\":{},\"arguments\":{}}}", + cmd.is_abstract, + cmd.arguments.len() + ); + } + out.push(']'); + + out.push_str(",\"unsupported\":["); + for (i, u) in db.unsupported().iter().take(50).enumerate() { + if i > 0 { + out.push(','); + } + out.push_str("{\"element\":"); + push_json_str(&mut out, &u.element); + out.push_str(",\"path\":"); + push_json_str(&mut out, &u.path); + out.push_str(",\"reason\":"); + push_json_str(&mut out, u.reason); + out.push('}'); + } + out.push_str("]}"); + + Ok(out) +} + +/// Checks if `bytes` begins with a standard libpcap global header magic number and, if so, +/// extracts the concatenated raw packet payloads from all PCAP records. +#[must_use] +pub fn extract_packets_if_pcap(bytes: &[u8]) -> (bool, Vec) { + if bytes.len() < 24 { + return (false, Vec::new()); + } + let magic_le = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); + let (is_pcap, little_endian) = match magic_le { + 0xA1B2_C3D4 | 0xA1B2_3C4D => (true, true), + 0xD4C3_B2A1 | 0x4D3C_B2A1 => (true, false), + _ => (false, true), + }; + if !is_pcap { + return (false, Vec::new()); + } + + let mut out = Vec::with_capacity(bytes.len()); + let mut offset = 24usize; + while offset + 16 <= bytes.len() { + let incl_len = if little_endian { + u32::from_le_bytes([ + bytes[offset + 8], + bytes[offset + 9], + bytes[offset + 10], + bytes[offset + 11], + ]) as usize + } else { + u32::from_be_bytes([ + bytes[offset + 8], + bytes[offset + 9], + bytes[offset + 10], + bytes[offset + 11], + ]) as usize + }; + offset += 16; + if offset + incl_len > bytes.len() { + break; + } + out.extend_from_slice(&bytes[offset..offset + incl_len]); + offset += incl_len; + } + (true, out) +} + +/// Decodes a packet stream (raw CCSDS or `.pcap`) against an XTCE 1.2 XML string and returns JSON. +/// +/// # Errors +/// +/// Returns an error string if the XTCE XML cannot be parsed or has no root container. +#[allow(clippy::too_many_lines)] +pub fn decode_xtce_and_packets_to_json( + xml_str: &str, + pkt_bytes: &[u8], + max_packets: usize, +) -> Result { + let db = XtceDb::from_xml(xml_str).map_err(|e| e.to_string())?; + let stats = db.stats(); + let decoder = Decoder::new(&db).map_err(|e| e.to_string())?; + + let (is_pcap, extracted) = extract_packets_if_pcap(pkt_bytes); + let stream: &[u8] = if is_pcap { &extracted } else { pkt_bytes }; + + let root_name = db + .space_systems() + .first() + .map_or("Unknown", |ss| db.name(ss.name)); + + let mut total_packets = 0usize; + let mut decoded_packets = 0usize; + let mut unrecognized_packets = 0usize; + let mut failed_packets = 0usize; + let mut crc_valid_packets = 0usize; + let mut payload_bytes = 0usize; + let mut container_counts: Vec<(&str, usize)> = Vec::new(); + + let mut packets_json = String::with_capacity(16_384); + packets_json.push('['); + let mut first_pkt_entry = true; + + for framed_res in PacketIter::new(stream, 0) { + let Ok(framed) = framed_res else { + failed_packets += 1; + break; + }; + let raw = framed.bytes(); + total_packets += 1; + payload_bytes += raw.len(); + + let sp = SpacePacketBytes::new(raw); + let apid = sp.apid(); + let seq_count = sp.sequence_count(); + let pkt_type = sp.packet_type(); + let crc_ok = raw.len() >= 8 && verify_crc16_ccitt(raw); + if crc_ok { + crc_valid_packets += 1; + } + let crc_val = if raw.len() >= 2 { + u16::from_be_bytes([raw[raw.len() - 2], raw[raw.len() - 1]]) + } else { + 0 + }; + + let pus_info = PusPacket::parse(raw).ok().map(|p| match p.header { + PusHeader::Telemetry { + service, + subtype, + timestamp, + .. + } => ("TM", service, subtype, timestamp.coarse_seconds), + PusHeader::Telecommand { + service, subtype, .. + } => ("TC", service, subtype, 0), + }); + + match decoder.decode(raw) { + Ok(decoded) => { + decoded_packets += 1; + let cname = db + .container(decoded.container()) + .map_or("?", |c| db.name(c.name)); + if let Some(entry) = container_counts.iter_mut().find(|(n, _)| *n == cname) { + entry.1 += 1; + } else { + container_counts.push((cname, 1)); + } + + if total_packets <= max_packets { + if !first_pkt_entry { + packets_json.push(','); + } + first_pkt_entry = false; + + let _ = write!( + packets_json, + "{{\"index\":{},\"status\":\"decoded\",\"container\":", + total_packets - 1 + ); + push_json_str(&mut packets_json, cname); + let _ = write!( + packets_json, + ",\"apid\":\"0x{apid:03X}\",\"apid_num\":{apid},\"seq_count\":{seq_count},\"direction\":\"{}\",\"length\":{},\"bits_consumed\":{},\"trailing_bits\":{},\"crc_ok\":{},\"crc_hex\":\"0x{crc_val:04X}\"", + if pkt_type == 1 { "TC" } else { "TM" }, + raw.len(), + decoded.bits_consumed(), + decoded.trailing_bits(), + crc_ok + ); + + if let Some((dir, st, sub, coarse_s)) = pus_info { + let _ = write!( + packets_json, + ",\"pus_label\":\"{dir}[{st},{sub}]\",\"pus_service\":{st},\"pus_subtype\":{sub},\"cuc_coarse_s\":{coarse_s}" + ); + } else { + packets_json.push_str(",\"pus_label\":null"); + } + + packets_json.push_str(",\"hex_preview\":\""); + for (bi, b) in raw.iter().take(28).enumerate() { + if bi > 0 { + packets_json.push(' '); + } + let _ = write!(packets_json, "{b:02X}"); + } + if raw.len() > 28 { + packets_json.push_str(" ..."); + } + packets_json.push('"'); + + packets_json.push_str(",\"parameters\":["); + for (pi, (pname, pval)) in decoded.iter_named().enumerate() { + if pi > 0 { + packets_json.push(','); + } + let unit_str = db + .type_of(pval.parameter) + .and_then(|ty| ty.units.first()) + .map_or("", |uid| db.name(*uid)); + append_decoded_param_json(&mut packets_json, pname, pval, unit_str); + } + packets_json.push_str("]}"); + } + } + Err(DecodeError::UnrecognizedPacket { container, .. }) => { + unrecognized_packets += 1; + if total_packets <= max_packets { + if !first_pkt_entry { + packets_json.push(','); + } + first_pkt_entry = false; + let _ = write!( + packets_json, + "{{\"index\":{},\"status\":\"unrecognized\",\"container\":", + total_packets - 1 + ); + push_json_str(&mut packets_json, &container); + let _ = write!( + packets_json, + ",\"apid\":\"0x{apid:03X}\",\"apid_num\":{apid},\"seq_count\":{seq_count},\"direction\":\"{}\",\"length\":{},\"crc_ok\":{},\"crc_hex\":\"0x{crc_val:04X}\",\"parameters\":[]}}", + if pkt_type == 1 { "TC" } else { "TM" }, + raw.len(), + crc_ok + ); + } + } + Err(err) => { + failed_packets += 1; + if total_packets <= max_packets { + if !first_pkt_entry { + packets_json.push(','); + } + first_pkt_entry = false; + append_decode_error_json( + &mut packets_json, + total_packets - 1, + &err, + apid, + seq_count, + raw.len(), + crc_ok, + ); + } + } + } + } + packets_json.push(']'); + + let mut out = String::with_capacity(packets_json.len() + 1024); + out.push_str("{\"ok\":true,\"root_space_system\":"); + push_json_str(&mut out, root_name); + let _ = write!( + out, + ",\"is_pcap\":{is_pcap},\"input_bytes\":{},\"stream_bytes\":{payload_bytes},\"total_packets\":{total_packets},\"decoded_packets\":{decoded_packets},\"unrecognized_packets\":{unrecognized_packets},\"failed_packets\":{failed_packets},\"crc_valid_packets\":{crc_valid_packets}", + pkt_bytes.len() + ); + let _ = write!( + out, + ",\"db_stats\":{{\"space_systems\":{},\"parameters\":{},\"parameter_types\":{},\"containers\":{},\"meta_commands\":{},\"unsupported\":{}}}", + stats.space_systems, + stats.parameters, + stats.parameter_types, + stats.containers, + stats.meta_commands, + stats.unsupported + ); + + out.push_str(",\"container_distribution\":["); + for (i, (cname, ccount)) in container_counts.iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str("{\"container\":"); + push_json_str(&mut out, cname); + let _ = write!(out, ",\"count\":{ccount}}}"); + } + out.push(']'); + + out.push_str(",\"packets\":"); + out.push_str(&packets_json); + out.push('}'); + + Ok(out) +} + +fn append_decoded_param_json( + out: &mut String, + pname: &str, + pval: &xtce_decode::ParameterValue<'_, '_>, + unit_str: &str, +) { + out.push_str("{\"name\":"); + push_json_str(out, pname); + out.push_str(",\"raw\":"); + push_json_str(out, &pval.raw.to_string()); + out.push_str(",\"eng\":"); + push_json_str(out, &pval.eng.to_string()); + out.push_str(",\"unit\":"); + push_json_str(out, unit_str); + let _ = write!( + out, + ",\"bit_offset\":{},\"bit_width\":{}}}", + pval.bit_offset, pval.bit_width + ); +} + +fn append_decode_error_json( + out: &mut String, + index: usize, + err: &DecodeError, + apid: u16, + seq_count: u16, + len: usize, + crc_ok: bool, +) { + let _ = write!(out, "{{\"index\":{index},\"status\":\"error\",\"error\":"); + push_json_str(out, &err.to_string()); + let _ = write!( + out, + ",\"apid\":\"0x{apid:03X}\",\"seq_count\":{seq_count},\"length\":{len},\"crc_ok\":{crc_ok},\"parameters\":[]}}" + ); +} + +/// Deterministic `SplitMix64` PRNG for client-side WASM telemetry simulation. +struct SplitMix64 { + state: u64, +} + +impl SplitMix64 { + const fn new(seed: u64) -> Self { + Self { state: seed } + } + + const fn next_u64(&mut self) -> u64 { + self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + const fn jitter_i16(&mut self, span: u16) -> i16 { + if span == 0 { + return 0; + } + let r = (self.next_u64() % ((span as u64) * 2 + 1)) as i16; + r - (span as i16) + } +} + +/// Generates a deterministic sequence of CCSDS / ECSS PUS-C frames in memory. +#[must_use] +pub fn generate_pus_stream_bytes(scenario_id: u32, packet_count: usize, seed: u64) -> Vec { + let mut rng = SplitMix64::new(seed); + let mut stream = Vec::with_capacity(packet_count * 36); + + let apid: u16 = 0x010; + let destination_id: u16 = 0x0001; + let mut seq_count: u16 = 0; + let mut msg_counter: u16 = 0; + let mut uptime_s: u32 = 100; + let mut mode: u8 = 2; // NOMINAL + let mut frame_buf = [0u8; MAX_HIL_FRAME_LEN]; + let fault_step = (packet_count / 2).max(1); + + for step in 0..packet_count { + uptime_s = uptime_s.wrapping_add(1); + let v_jitter = rng.jitter_i16(25); + let t_jitter = rng.jitter_i16(10); + + let mut bus_voltage_mv: u16 = (28_200i32 + i32::from(v_jitter)) as u16; + let mut obc_temp_cdeg: i16 = 2_250 + t_jitter; + + match scenario_id { + 1 if step >= fault_step => { + let drop = ((step - fault_step + 1) * 900).min(6_800) as u16; + bus_voltage_mv = bus_voltage_mv.saturating_sub(drop); + if bus_voltage_mv < 24_000 { + mode = 0; + } + } + 2 if step >= fault_step => { + let rise = ((step - fault_step + 1) * 650).min(4_600) as i16; + obc_temp_cdeg = obc_temp_cdeg.saturating_add(rise); + if obc_temp_cdeg > 5_500 { + mode = 0; + } + } + 3 if step == fault_step => { + seq_count = (seq_count + 17) & 0x3FFF; + } + 4 if step == fault_step => { + uptime_s = 1; + seq_count = 0; + mode = 0; + } + 5 if step >= fault_step => { + mode = 0; + } + 6 if step == fault_step + 1 => { + bus_voltage_mv = 35_900; + obc_temp_cdeg = 8_500; + } + _ => {} + } + + let (service, subtype, payload_len, payload) = if step == fault_step && scenario_id != 0 { + let (ev_id, aux_val): (u16, u16) = match scenario_id { + 1 => (0x1201, bus_voltage_mv), + 2 => (0x1202, obc_temp_cdeg as u16), + 3 => (0x0502, 17), + 4 => (0x0503, 1), + 5 => (0x0504, 0), + 6 => (0x0505, 0xFFFF), + _ => (0x0000, 0), + }; + let id_b = ev_id.to_be_bytes(); + let aux_b = aux_val.to_be_bytes(); + let mut app = [0u8; 11]; + app[0] = id_b[0]; + app[1] = id_b[1]; + app[2] = aux_b[0]; + app[3] = aux_b[1]; + (5u8, 2u8, 4usize, app) + } else if step % 5 == 4 { + (17u8, 2u8, 0usize, [0u8; 11]) + } else { + let hk = ObcHousekeeping { + uptime_s, + bus_voltage_mv, + obc_temp_cdeg, + mode, + }; + (3u8, 25u8, 11usize, hk.to_app_data()) + }; + + let params = TmParams { + apid, + sequence_count: seq_count, + service, + subtype, + msg_counter, + destination_id, + timestamp: CucTimestamp { + coarse_seconds: uptime_s, + fine_subseconds: 0, + }, + }; + + if let Ok(written) = encode_tm(¶ms, &payload[..payload_len], &mut frame_buf) { + stream.extend_from_slice(&frame_buf[..written]); + } + + seq_count = (seq_count + 1) & 0x3FFF; + msg_counter = msg_counter.wrapping_add(1); + } + + stream +} + +/// Wraps a raw CCSDS packet stream in a libpcap (`.pcap`, `DLT_USER0 = 147`) capture buffer. +#[must_use] +pub fn wrap_in_pcap(raw_stream: &[u8]) -> Vec { + const GLOBAL_HEADER: [u8; 24] = [ + 0xD4, 0xC3, 0xB2, 0xA1, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x93, 0x00, 0x00, 0x00, + ]; + let mut out = Vec::with_capacity(24 + raw_stream.len() + 256); + out.extend_from_slice(&GLOBAL_HEADER); + + for (idx, framed_res) in PacketIter::new(raw_stream, 0).enumerate() { + let Ok(framed) = framed_res else { + break; + }; + let bytes = framed.bytes(); + let pkt_len = u32::try_from(bytes.len()).unwrap_or(u32::MAX); + let idx_u32 = u32::try_from(idx).unwrap_or(u32::MAX); + let seconds = idx_u32 / 1_000; + let micros = (idx_u32 % 1_000) * 1_000; + + out.extend_from_slice(&seconds.to_le_bytes()); + out.extend_from_slice(µs.to_le_bytes()); + out.extend_from_slice(&pkt_len.to_le_bytes()); + out.extend_from_slice(&pkt_len.to_le_bytes()); + out.extend_from_slice(bytes); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wasm_stream_and_pcap_roundtrip_decode() { + let raw = generate_pus_stream_bytes(1, 10, 42); + let pcap = wrap_in_pcap(&raw); + let (is_pcap, stripped) = extract_packets_if_pcap(&pcap); + assert!(is_pcap); + assert_eq!(stripped, raw); + } +} From d1b68ca4064c7921d33f0b61a5618319af82c7db Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Fri, 20 Nov 2026 21:09:31 +0100 Subject: [PATCH 2/2] fix(lsp,wasm): use O(1) line index and UTF-16 char resolution per Altanix CR --- crates/xtce-cli/src/lsp.rs | 85 ++++++++++++++++++++++++++++++------- crates/xtce-wasm/src/lib.rs | 19 +++++++++ 2 files changed, 89 insertions(+), 15 deletions(-) diff --git a/crates/xtce-cli/src/lsp.rs b/crates/xtce-cli/src/lsp.rs index 83420b6..43e77c1 100644 --- a/crates/xtce-cli/src/lsp.rs +++ b/crates/xtce-cli/src/lsp.rs @@ -25,10 +25,39 @@ use crate::validate::{self, Level}; /// Maximum LSP message payload size accepted from `stdin` (32 MiB) to prevent unbounded allocation. const MAX_LSP_BODY_BYTES: usize = 32 * 1024 * 1024; +/// Cached document buffer with precomputed line-start byte offsets for O(1) line lookup. +#[derive(Default)] +struct CachedDocument { + text: String, + line_starts: Vec, +} + +impl CachedDocument { + fn new(text: String) -> Self { + let mut line_starts = vec![0]; + for (idx, b) in text.bytes().enumerate() { + if b == b'\n' { + line_starts.push(idx + 1); + } + } + Self { text, line_starts } + } + + fn line_slice(&self, line: usize) -> Option<&str> { + let start = *self.line_starts.get(line)?; + let end = self + .line_starts + .get(line + 1) + .map_or(self.text.len(), |next| next.saturating_sub(1)); + let slice = self.text.get(start..end)?; + Some(slice.strip_suffix('\r').unwrap_or(slice)) + } +} + /// In-memory state of the XTCE Language Server. #[derive(Default)] pub struct LspServer { - documents: BTreeMap, + documents: BTreeMap, shutdown_requested: bool, } @@ -92,7 +121,7 @@ impl LspServer { if let Some(uri) = extract_json_str(body, "uri") { if let Some(text) = extract_json_str(body, "text") { let diag_json = build_diagnostics_notification(&uri, &text); - self.documents.insert(uri, text); + self.documents.insert(uri, CachedDocument::new(text)); write_lsp_frame(out, &diag_json)?; } } @@ -134,10 +163,13 @@ impl LspServer { let line = extract_json_usize(body, "line").unwrap_or(0); let character = extract_json_usize(body, "character").unwrap_or(0); - let Some(token) = word_at_position(doc, line, character) else { + let Some(line_str) = doc.line_slice(line) else { + return "null".to_owned(); + }; + let Some(token) = word_in_line_utf16(line_str, character) else { return "null".to_owned(); }; - let Ok(db) = XtceDb::from_xml(doc) else { + let Ok(db) = XtceDb::from_xml(&doc.text) else { return "null".to_owned(); }; let Some(markdown) = build_hover_markdown(&db, token) else { @@ -159,10 +191,13 @@ impl LspServer { let line = extract_json_usize(body, "line").unwrap_or(0); let character = extract_json_usize(body, "character").unwrap_or(0); - let Some(token) = word_at_position(doc, line, character) else { + let Some(line_str) = doc.line_slice(line) else { + return "null".to_owned(); + }; + let Some(token) = word_in_line_utf16(line_str, character) else { return "null".to_owned(); }; - let Some((def_line, def_col)) = find_xml_definition_line(doc, token) else { + let Some((def_line, def_col)) = find_xml_definition_line(&doc.text, token) else { return "null".to_owned(); }; @@ -181,7 +216,7 @@ impl LspServer { let Some(doc) = self.documents.get(&uri) else { return "[]".to_owned(); }; - let Ok(db) = XtceDb::from_xml(doc) else { + let Ok(db) = XtceDb::from_xml(&doc.text) else { return "[]".to_owned(); }; @@ -191,17 +226,17 @@ impl LspServer { for c in db.containers() { let name = db.name(c.name); - let (line, col) = find_xml_definition_line(doc, name).unwrap_or((0, 0)); + let (line, col) = find_xml_definition_line(&doc.text, name).unwrap_or((0, 0)); append_symbol_json(&mut out, &mut first, name, 23, line, col); } for p in db.parameters() { let name = db.name(p.name); - let (line, col) = find_xml_definition_line(doc, name).unwrap_or((0, 0)); + let (line, col) = find_xml_definition_line(&doc.text, name).unwrap_or((0, 0)); append_symbol_json(&mut out, &mut first, name, 8, line, col); } for cmd in db.meta_commands() { let name = db.name(cmd.name); - let (line, col) = find_xml_definition_line(doc, name).unwrap_or((0, 0)); + let (line, col) = find_xml_definition_line(&doc.text, name).unwrap_or((0, 0)); append_symbol_json(&mut out, &mut first, name, 12, line, col); } @@ -397,13 +432,22 @@ pub fn find_xml_definition_line(xml_text: &str, symbol: &str) -> Option<(usize, None } -fn word_at_position(text: &str, line: usize, character: usize) -> Option<&str> { - let target_line = text.lines().nth(line)?; - let bytes = target_line.as_bytes(); - if bytes.is_empty() { +fn word_in_line_utf16(target_line: &str, character_utf16: usize) -> Option<&str> { + if target_line.is_empty() { return None; } - let idx = character.min(bytes.len().saturating_sub(1)); + let mut utf16_col = 0usize; + let mut target_byte_idx = None; + for (byte_idx, ch) in target_line.char_indices() { + let ch_utf16_len = ch.len_utf16(); + if character_utf16 >= utf16_col && character_utf16 < utf16_col + ch_utf16_len { + target_byte_idx = Some(byte_idx); + break; + } + utf16_col += ch_utf16_len; + } + let idx = target_byte_idx?; + let bytes = target_line.as_bytes(); if !is_ident_byte(*bytes.get(idx)?) { return None; } @@ -606,4 +650,15 @@ mod tests { assert!(out_str.contains(r#""method":"textDocument/publishDiagnostics""#)); assert!(out_str.contains("Parameter `VBUS`")); } + + #[test] + fn word_in_line_utf16_handles_multibyte_and_edge_cases() { + let line = r#" "#; + // " 40 + let word = super::word_in_line_utf16(line, 43); + assert_eq!(word, Some("OBC_VBUS_V")); + assert!(super::word_in_line_utf16(line, 21).is_none()); + assert!(super::word_in_line_utf16("", 0).is_none()); + assert!(super::word_in_line_utf16(line, 999).is_none()); + } } diff --git a/crates/xtce-wasm/src/lib.rs b/crates/xtce-wasm/src/lib.rs index 20c6700..614d1e8 100644 --- a/crates/xtce-wasm/src/lib.rs +++ b/crates/xtce-wasm/src/lib.rs @@ -862,4 +862,23 @@ mod tests { assert!(is_pcap); assert_eq!(stripped, raw); } + + #[test] + fn extract_packets_if_pcap_edge_cases_and_invalid_magic() { + let empty: &[u8] = &[]; + let (is_pcap_empty, extracted_empty) = extract_packets_if_pcap(empty); + assert!(!is_pcap_empty); + assert_eq!(extracted_empty, [] as [u8; 0]); + + let short_bytes: &[u8] = &[0xD4, 0xC3, 0xB2, 0xA1, 0x02, 0x00]; + let (is_pcap_short, extracted_short) = extract_packets_if_pcap(short_bytes); + assert!(!is_pcap_short); + assert_eq!(extracted_short, [] as [u8; 0]); + + let mut invalid_header_pcap = vec![0x11, 0x22, 0x33, 0x44]; + invalid_header_pcap.resize(24, 0); + let (is_pcap_invalid, extracted_invalid) = extract_packets_if_pcap(&invalid_header_pcap); + assert!(!is_pcap_invalid); + assert_eq!(extracted_invalid, [] as [u8; 0]); + } }