Skip to content

Commit beb3a91

Browse files
committed
refactor(json): adopt kernel project and DWARF smoke documents
1 parent 73c2a33 commit beb3a91

6 files changed

Lines changed: 146 additions & 44 deletions

File tree

‎Cargo.lock‎

Lines changed: 11 additions & 9 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ homepage = "https://github.com/zackees/fastled-wasm"
1414

1515
[workspace.dependencies]
1616
clap = { version = "4", features = ["derive"] }
17-
kernal-api = { version = "=0.1.0", features = ["fs", "fs-watch", "hash-sha256", "archive", "http-client", "http-server", "event-stream", "secure-random", "text-similarity", "terminal-input", "terminal-style", "command-arguments", "config-toml", "source-cpp"] }
17+
kernal-api = { version = "=0.1.0", features = ["fs", "fs-watch", "hash-sha256", "archive", "http-client", "http-server", "event-stream", "secure-random", "text-similarity", "terminal-input", "terminal-style", "command-arguments", "config-toml", "source-cpp", "json"] }
1818
serde = { version = "1", features = ["derive"] }
1919
serde_json = "1"
2020
anyhow = "1"
@@ -26,7 +26,7 @@ strip = "none"
2626

2727
# Temporary migration override; replace with the verified published release.
2828
[patch.crates-io]
29-
kernal-api = { path = "../fastled-wasm-extern/kernal-api-source-cpp" }
29+
kernal-api = { path = "../fastled-wasm-extern/kernal-api-json" }
3030

3131
[profile.dev.package.kernal-api]
3232
codegen-units = 1

‎crates/fastled-cli/src/dwarf_smoke.rs‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::path::Path;
33
use std::sync::{Arc, RwLock};
44

55
use anyhow::Context;
6+
use kernal_api::json::{self, Layout, Value};
67

78
use crate::debug_symbols;
89
use crate::server;
@@ -37,7 +38,10 @@ pub(crate) fn run_dwarf_source_smoke(output_dir: &Path) -> anyhow::Result<usize>
3738
let client = kernal_api::http::Client::new(kernal_api::http::Limits::default())?;
3839
for path in &paths {
3940
let url = format!("http://{addr}/dwarfsource");
40-
let body = serde_json::to_vec(&serde_json::json!({ "path": path }))?;
41+
let body = json::encode(
42+
&Value::Object([("path".into(), Value::String(path.clone()))].into()),
43+
Layout::Compact,
44+
)?;
4145
let resp = client
4246
.execute(kernal_api::http::Request {
4347
method: kernal_api::http::Method::Post,
@@ -73,7 +77,17 @@ fn source_smoke_uses_manifest_paths_and_reports_missing_source() {
7377
let source_path = format!("{}/demo.ino", config.prefixes.sketch_prefix);
7478
std::fs::write(
7579
output.join("fastled.wasm.map"),
76-
serde_json::json!({"sources": [source_path]}).to_string(),
80+
json::encode(
81+
&Value::Object(
82+
[(
83+
"sources".into(),
84+
Value::Array(vec![Value::String(source_path)]),
85+
)]
86+
.into(),
87+
),
88+
Layout::Compact,
89+
)
90+
.unwrap(),
7791
)
7892
.unwrap();
7993
assert_eq!(run_dwarf_source_smoke(&output).unwrap(), 1);
@@ -102,11 +116,15 @@ pub(crate) fn collect_debug_source_paths(
102116
if source_map_path.is_file() {
103117
let json = std::fs::read_to_string(&source_map_path)
104118
.with_context(|| format!("read {}", source_map_path.display()))?;
105-
let parsed: serde_json::Value = serde_json::from_str(&json)
119+
let parsed = json::parse(json.as_bytes())
106120
.with_context(|| format!("parse {}", source_map_path.display()))?;
107-
if let Some(sources) = parsed.get("sources").and_then(serde_json::Value::as_array) {
108-
for source in sources.iter().filter_map(serde_json::Value::as_str) {
109-
insert_debug_source_candidate(&mut paths, &prefixes, source);
121+
if let Value::Object(parsed) = parsed {
122+
if let Some(Value::Array(sources)) = parsed.get("sources") {
123+
for source in sources {
124+
if let Value::String(source) = source {
125+
insert_debug_source_candidate(&mut paths, &prefixes, source);
126+
}
127+
}
110128
}
111129
}
112130
}

‎crates/fastled-cli/src/project.rs‎

Lines changed: 70 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use std::fs;
1414
use std::path::{Path, PathBuf};
1515

1616
use anyhow::{bail, Context, Result};
17+
use kernal_api::json::{self, Layout, Value};
1718

1819
// ---------------------------------------------------------------------------
1920
// Sketch detection
@@ -242,8 +243,8 @@ pub fn is_fastled_repo(path: &Path) -> bool {
242243
let lib_json = path.join("library.json");
243244
if lib_json.is_file() {
244245
if let Ok(txt) = fs::read_to_string(&lib_json) {
245-
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
246-
if val.get("name").and_then(|v| v.as_str()) == Some("FastLED") {
246+
if let Ok(Value::Object(val)) = json::parse(txt.as_bytes()) {
247+
if matches!(val.get("name"), Some(Value::String(name)) if name == "FastLED") {
247248
return true;
248249
}
249250
}
@@ -321,8 +322,13 @@ pub fn collect_examples(examples_dir: &Path) -> Vec<String> {
321322
pub fn read_fastled_json_ref(directory: &Path) -> Option<String> {
322323
let fpath = directory.join("fastled.json");
323324
let txt = fs::read_to_string(fpath).ok()?;
324-
let value: serde_json::Value = serde_json::from_str(&txt).ok()?;
325-
value.get("ref")?.as_str().map(str::to_owned)
325+
let Value::Object(value) = json::parse(txt.as_bytes()).ok()? else {
326+
return None;
327+
};
328+
match value.get("ref")? {
329+
Value::String(value) => Some(value.clone()),
330+
_ => None,
331+
}
326332
}
327333

328334
/// Derive the resolved FastLED ref name from a cached repo directory.
@@ -344,25 +350,22 @@ pub fn cached_repo_ref_name(repo_root: &Path) -> String {
344350
/// keys when the file already contains valid JSON.
345351
pub fn write_fastled_json_ref(directory: &Path, ref_name: &str) -> Result<()> {
346352
let fpath = directory.join("fastled.json");
347-
let mut data = if fpath.is_file() {
348-
fs::read_to_string(&fpath)
349-
.ok()
350-
.and_then(|txt| {
351-
serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&txt).ok()
352-
})
353-
.unwrap_or_default()
354-
} else {
355-
serde_json::Map::new()
353+
let mut data = match fs::read_to_string(&fpath).ok() {
354+
Some(txt) => match json::parse(txt.as_bytes()) {
355+
Ok(Value::Object(value)) => value,
356+
Ok(_) | Err(json::Error::InvalidSyntax) => std::collections::BTreeMap::new(),
357+
// Do not erase valid user settings merely because the bounded
358+
// parser cannot retain their complete contents.
359+
Err(error) => return Err(error).context("read existing fastled.json"),
360+
},
361+
None => std::collections::BTreeMap::new(),
356362
};
357363

358-
data.insert(
359-
"ref".to_owned(),
360-
serde_json::Value::String(ref_name.to_owned()),
361-
);
364+
data.insert("ref".to_owned(), Value::String(ref_name.to_owned()));
362365

363-
let mut json = serde_json::to_string_pretty(&serde_json::Value::Object(data))
364-
.context("serialize fastled.json")?;
365-
json.push('\n');
366+
let mut json =
367+
json::encode(&Value::Object(data), Layout::Pretty).context("serialize fastled.json")?;
368+
json.push(b'\n');
366369
fs::write(&fpath, json).with_context(|| format!("write {}", fpath.display()))?;
367370
Ok(())
368371
}
@@ -424,10 +427,13 @@ fn fetch_latest_release_tag() -> Option<String> {
424427
}
425428

426429
let body = resp.into_bytes().ok()?;
427-
let json: serde_json::Value = serde_json::from_slice(&body).ok()?;
428-
json.get("tag_name")
429-
.and_then(|v: &serde_json::Value| v.as_str())
430-
.map(|s: &str| s.to_owned())
430+
let Value::Object(json) = json::parse(&body).ok()? else {
431+
return None;
432+
};
433+
match json.get("tag_name")? {
434+
Value::String(value) => Some(value.clone()),
435+
_ => None,
436+
}
431437
}
432438

433439
/// Return `true` when `ref_str` looks like a git commit SHA (7–40 hex chars).
@@ -1020,6 +1026,41 @@ mod tests {
10201026
assert_eq!(read_fastled_json_ref(dir.path()).as_deref(), Some("master"));
10211027
}
10221028

1029+
#[test]
1030+
fn project_json_preserves_nested_unknown_fields_and_layout() {
1031+
let dir = temp_dir();
1032+
let path = dir.path().join("fastled.json");
1033+
fs::write(&path, r#"{"extra":[null,true,18446744073709551615,{"日本":"line\ntext"}],"ref":"old","ref":"last"}"#).unwrap();
1034+
assert_eq!(read_fastled_json_ref(dir.path()).as_deref(), Some("last"));
1035+
write_fastled_json_ref(dir.path(), "new").unwrap();
1036+
assert_eq!(fs::read_to_string(&path).unwrap(), "{\n \"extra\": [\n null,\n true,\n 18446744073709551615,\n {\n \"日本\": \"line\\ntext\"\n }\n ],\n \"ref\": \"new\"\n}\n");
1037+
}
1038+
1039+
#[test]
1040+
fn project_json_keeps_invalid_and_nonobject_fallback_policy() {
1041+
let dir = temp_dir();
1042+
let path = dir.path().join("fastled.json");
1043+
for input in ["broken", "[]", "null", "42", r#"{"ref":false}"#] {
1044+
fs::write(&path, input).unwrap();
1045+
assert_eq!(read_fastled_json_ref(dir.path()), None);
1046+
write_fastled_json_ref(dir.path(), "master").unwrap();
1047+
assert_eq!(
1048+
fs::read_to_string(&path).unwrap(),
1049+
"{\n \"ref\": \"master\"\n}\n"
1050+
);
1051+
}
1052+
}
1053+
1054+
#[test]
1055+
fn project_json_resource_limit_does_not_replace_existing_settings() {
1056+
let dir = temp_dir();
1057+
let path = dir.path().join("fastled.json");
1058+
let original = format!("{{\"extra\":\"{}\"}}", "x".repeat(json::MAX_INPUT_BYTES));
1059+
fs::write(&path, &original).unwrap();
1060+
assert!(write_fastled_json_ref(dir.path(), "new").is_err());
1061+
assert_eq!(fs::read_to_string(path).unwrap(), original);
1062+
}
1063+
10231064
#[test]
10241065
fn test_cached_repo_ref_name_strips_fastled_prefix() {
10251066
let path = Path::new("/tmp/fastled-3.9.12");
@@ -1044,9 +1085,11 @@ mod tests {
10441085
write_fastled_json_ref(dir.path(), "3.9.12").unwrap();
10451086

10461087
let txt = fs::read_to_string(dir.path().join("fastled.json")).unwrap();
1047-
let value: serde_json::Value = serde_json::from_str(&txt).unwrap();
1048-
assert_eq!(value.get("name").and_then(|v| v.as_str()), Some("demo"));
1049-
assert_eq!(value.get("ref").and_then(|v| v.as_str()), Some("3.9.12"));
1088+
let Value::Object(value) = json::parse(txt.as_bytes()).unwrap() else {
1089+
panic!("project settings must be an object");
1090+
};
1091+
assert_eq!(value.get("name"), Some(&Value::String("demo".into())));
1092+
assert_eq!(value.get("ref"), Some(&Value::String("3.9.12".into())));
10501093
}
10511094

10521095
#[test]

‎docs/kernal-api-migration.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,31 @@ This change does not upgrade Emscripten or claim a measured build
955955
speedup. Remaining direct Rust dependencies are Clap, Serde, Serde JSON, Anyhow,
956956
and kernal-api; their migration remains required.
957957

958+
### JSON adoption in progress
959+
960+
Upstream issue zackees/kernal-api#211 and draft PR #212 provide bounded owned
961+
JSON values and parsing/encoding without public Serde contracts. The app's
962+
migration-only patch now points to `kernal-api-json` at upstream `b3896d2` and
963+
enables `json`. The lockfile aligns Serde/Serde Core/Serde Derive to 1.0.229 and
964+
Serde JSON to 1.0.151 to satisfy the kernel's exact private pins.
965+
966+
Project discovery, ref settings, release-tag extraction, and the DWARF smoke
967+
client/source-map reader now use this API. Their field selection, non-string
968+
filtering, HTTP status policy, unknown-setting preservation and trailing newline
969+
remain local. Project updates propagate resource-limit failures before writing;
970+
they must not discard an oversized valid settings file. Malformed/non-object
971+
project settings retain the existing reset behavior. Kernel object encoding is
972+
key-sorted, and its documented source/node/depth/output limits now apply.
973+
974+
Both module-specific dependency bans observed RED then GREEN. All 268 library,
975+
3 binary, 1 integration and 1 doc tests pass, including the DWARF HTTP smoke
976+
test. All 34 Python tests pass (1 skipped); formatting, Ruff, strict all-target
977+
Clippy and single-reviewer review pass. Final native/runtime verification remains
978+
pending. Direct Serde
979+
dependencies remain for the other eight JSON modules; this is not complete JSON
980+
adoption or a release-ready dependency graph. Published adoption, browser/Safari
981+
acceptance and measured build performance remain outstanding.
982+
958983
### Final migration audit
959984

960985
The Axum baseline now has a raw-wire parity test for missing-file 404,

‎tests/unit/test_kernal_boundary.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,20 @@ def test_toml_configuration_uses_kernel():
7575
assert "toml::" not in source.read_text(), source
7676

7777

78+
def test_project_json_uses_kernel():
79+
root = Path(__file__).resolve().parents[2]
80+
source = (root / "crates/fastled-cli/src/project.rs").read_text()
81+
assert "serde_json::" not in source
82+
assert "kernal_api::json" in source
83+
84+
85+
def test_dwarf_smoke_json_uses_kernel():
86+
root = Path(__file__).resolve().parents[2]
87+
source = (root / "crates/fastled-cli/src/dwarf_smoke.rs").read_text()
88+
assert "serde_json::" not in source
89+
assert "kernal_api::json" in source
90+
91+
7892
def test_cpp_source_analysis_uses_kernel():
7993
root = Path(__file__).resolve().parents[2]
8094
for path in (root / "Cargo.toml", root / "crates/fastled-cli/Cargo.toml"):

0 commit comments

Comments
 (0)