Files
alkane-os/third-party/flare-ui/dash-editor/rust/wdash_format.rs
T
x ad31cfbafa Vendor flare-ui v0.2.9 and prove the schema-driven UI in an image
Spike, not the final UI: it answers whether flare-ui can drive Alkane OS's
on-box pages, and what it costs.

What works:

- schema/alkane-bb.json authors the sidebar as data (3 sections, 14 tabs);
- src/bin/ui-spike.rs renders it through flare_ui::nav + flare_ui::shell, so
  the unified sidebar, ordering and surface filtering come from the schema
  rather than from hand-written HTML;
- the render uses the shared bf- design tokens, the same ones the rest of the
  suite uses.

Size, measured rather than assumed (armv7, release, stripped):

  ui-baseline   323 KiB   (maud + serde_json, no flare-ui)
  ui-spike      771 KiB   (flare-ui + wschema + sha2)
  marginal      448 KiB

Vendoring: third-party/flare-ui is the full v0.2.9 tree pinned in
flare-ui/flare-ui.lock (a partial archive does not compile, since the crate
include_str!s assets from dash-editor/). vendor/ is re-generated as a cargo
directory source with the new registry dependencies (maud, sha2, typenum,
digest, generic-array, block-buffer, crypto-common, cfg-if, etc.) so the build
still works offline. third-party/README.md records how to re-pin.
2026-11-04 14:06:25 -06:00

415 lines
16 KiB
Rust

//! The `.wdash` file header: reading it, writing it, and its checksum.
//!
//! One file, vendored byte for byte into every Rust reader of the format
//! (dash-editor.lock), so the readers cannot drift apart. It covers what
//! docs/wdash.md says about the header and nothing about the document inside
//! it: each reader holds the document to its own save rules after `header`
//! has passed it. It needs only std, serde_json and sha2, keeps no state and
//! touches no storage.
//!
//! The checksum is SHA-256 over the RFC 8785 canonical form of the document.
//! Canonicalizing is what lets a re-indented file still verify, and it is the
//! part of the format where implementations drift, so the vectors are run
//! against it in each consumer.
//!
//! Errors are plain sentences that name the field or rule, which is what the
//! vectors' `reason` matches; a consumer wraps them in its own error type.
use std::fmt::Write as _;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
/// The format version this file reads and writes.
pub const FORMAT: u64 = 1;
/// The largest file a reader accepts, in bytes.
pub const FILE_MAX: usize = 192 * 1024;
/// The longest `name` or `author` a file carries, in characters.
pub const NAME_MAX: usize = 120;
/// The six header fields, in the order a file is written.
pub const FIELDS: [&str; 6] = ["wdash", "name", "author", "exported_at", "checksum", "document"];
/// A header that passed every rule. `document` is only known to be a JSON
/// object whose checksum matches; its own rules are the caller's.
#[derive(Debug, Clone, PartialEq)]
pub struct Header {
pub name: String,
pub author: String,
pub exported_at: String,
pub checksum: String,
pub document: Value,
}
impl Header {
/// A header for `document`, with display text fitted to the rules:
/// control characters dropped and the length capped, and an empty name
/// replaced by `fallback`, so any name a host accepted always writes.
pub fn new(name: &str, fallback: &str, author: &str, exported_at: String, document: Value) -> Header {
Header {
name: clipped(name, fallback),
author: clipped(author, ""),
exported_at,
checksum: checksum(&document),
document,
}
}
/// The file as a JSON value.
pub fn to_value(&self) -> Value {
json!({
"wdash": FORMAT,
"name": self.name,
"author": self.author,
"exported_at": self.exported_at,
"checksum": self.checksum,
"document": self.document,
})
}
/// The bytes a download carries, with a final newline: indented when the
/// indented file fits in `FILE_MAX`, compact otherwise. Indentation grows
/// with nesting, so a deep document inside the document cap can indent
/// past the file cap; compact, it always fits (flare-dash-editor#2).
pub fn to_text(&self) -> String {
let value = self.to_value();
let mut text = serde_json::to_string_pretty(&value).unwrap_or_default();
if text.len() >= FILE_MAX {
text = value.to_string();
}
text.push('\n');
text
}
}
/// Read a file's bytes: the size, the JSON, then `header`. `reader` names the
/// host in the newer-format refusal ("portal", "panel").
pub fn read(raw: &str, reader: &str) -> Result<Header, String> {
if raw.len() > FILE_MAX {
return Err(format!("A .wdash file is limited to {} KB", FILE_MAX / 1024));
}
let value: Value = serde_json::from_str(raw).map_err(|e| format!("The file is not JSON: {e}"))?;
header(&value, reader)
}
/// Read a file already parsed: every header rule, then the checksum.
pub fn header(value: &Value, reader: &str) -> Result<Header, String> {
let Value::Object(fields) = value else {
return Err("A .wdash file is one JSON object".into());
};
// The version first, so a newer file is refused by number rather than by
// whichever field this build happens to miss first.
match fields.get("wdash").and_then(Value::as_u64) {
Some(FORMAT) => {}
Some(other) => {
return Err(format!(
"This file is .wdash format {other}, written by a newer build; this {reader} reads format {FORMAT}"
))
}
None => return Err("wdash must be an integer format version".into()),
}
if let Some(extra) = fields.keys().find(|k| !FIELDS.contains(&k.as_str())) {
return Err(format!("unknown field `{extra}` in the file header"));
}
if let Some(missing) = FIELDS.iter().find(|k| !fields.contains_key(**k)) {
return Err(format!("missing field `{missing}` in the file header"));
}
let name = display_text("name", &fields["name"], 1)?;
let author = display_text("author", &fields["author"], 0)?;
let exported_at = match &fields["exported_at"] {
Value::String(at) if is_stamp(at) => at.clone(),
_ => return Err("exported_at must be UTC as YYYY-MM-DDTHH:MM:SSZ".into()),
};
let sum = match &fields["checksum"] {
Value::String(sum) if is_checksum(sum) => sum.clone(),
_ => return Err("checksum must be sha256: and 64 lowercase hex digits".into()),
};
let document = &fields["document"];
if !document.is_object() {
return Err("document must be a JSON object".into());
}
if checksum(document) != sum {
return Err(
"The checksum does not match the document, so the file was changed or damaged after it was exported"
.into(),
);
}
Ok(Header {
name,
author,
exported_at,
checksum: sum,
document: document.clone(),
})
}
fn display_text(field: &str, value: &Value, min: usize) -> Result<String, String> {
let Value::String(text) = value else {
return Err(format!("{field} must be a string"));
};
let length = text.chars().count();
if length < min || length > NAME_MAX {
return Err(format!("{field} must be {min} to {NAME_MAX} characters"));
}
if text.chars().any(|c| c.is_ascii_control()) {
return Err(format!("{field} holds a control character"));
}
Ok(text.clone())
}
/// Display text fitted to the header's rules (see `Header::new`).
pub fn clipped(text: &str, fallback: &str) -> String {
let kept: String = text.chars().filter(|c| !c.is_ascii_control()).take(NAME_MAX).collect();
if kept.trim().is_empty() && !fallback.is_empty() {
fallback.to_string()
} else {
kept
}
}
/// `YYYY-MM-DDTHH:MM:SSZ`, checked by shape and field range. Dates are not
/// checked against the calendar: the field is display text, and refusing
/// 31 February would be a rule with nothing to protect.
pub fn is_stamp(text: &str) -> bool {
let b = text.as_bytes();
if b.len() != 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':'
|| b[16] != b':' || b[19] != b'Z'
{
return false;
}
let field = |from: usize, to: usize| -> Option<u32> {
b[from..to].iter().all(u8::is_ascii_digit).then(|| text[from..to].parse().ok())?
};
matches!(
(field(0, 4), field(5, 7), field(8, 10), field(11, 13), field(14, 16), field(17, 19)),
(Some(_), Some(1..=12), Some(1..=31), Some(0..=23), Some(0..=59), Some(0..=59))
)
}
fn is_checksum(text: &str) -> bool {
text.strip_prefix("sha256:").is_some_and(|hex| {
hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
})
}
// ------------------------------------------------------------------ checksum
/// `sha256:` and the hex digest of the canonical document.
pub fn checksum(document: &Value) -> String {
let digest = Sha256::digest(canonical(document).as_bytes());
let mut out = String::with_capacity(7 + 64);
out.push_str("sha256:");
for byte in digest {
let _ = write!(out, "{byte:02x}");
}
out
}
/// RFC 8785: members sorted by UTF-16 code units, no whitespace, strings as
/// ECMAScript writes them (serde_json writes them the same way), and numbers
/// as ECMAScript's `Number.prototype.toString` writes them.
pub fn canonical(value: &Value) -> String {
let mut out = String::new();
write_canonical(value, &mut out);
out
}
fn write_canonical(value: &Value, out: &mut String) {
match value {
Value::Null => out.push_str("null"),
Value::Bool(flag) => out.push_str(if *flag { "true" } else { "false" }),
// Every number serde_json parses has an f64 reading, and JSON has no
// non-finite one.
Value::Number(number) => out.push_str(&es_number(number.as_f64().unwrap_or(0.0))),
Value::String(text) => quoted(text, out),
Value::Array(items) => {
out.push('[');
for (at, item) in items.iter().enumerate() {
if at > 0 {
out.push(',');
}
write_canonical(item, out);
}
out.push(']');
}
Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
out.push('{');
for (at, key) in keys.into_iter().enumerate() {
if at > 0 {
out.push(',');
}
quoted(key, out);
out.push(':');
write_canonical(&map[key], out);
}
out.push('}');
}
}
}
fn quoted(text: &str, out: &mut String) {
out.push_str(&serde_json::to_string(text).unwrap_or_default());
}
/// ECMAScript's Number::toString for a finite double; a non-finite one, which
/// JSON cannot hold, writes as 0.
///
/// Rust's `{:e}` writes the shortest digit string that reads back as the same
/// double, which is the digit string the ECMAScript algorithm starts from; the
/// rest is where the decimal point goes. `n` is the position of the point
/// relative to the digits, so the value is 0.d1d2... times ten to the `n`.
pub fn es_number(x: f64) -> String {
if x == 0.0 || !x.is_finite() {
return "0".into();
}
if x < 0.0 {
return format!("-{}", es_number(-x));
}
let exp = format!("{x:e}");
let Some((mantissa, power)) = exp.split_once('e') else {
return exp;
};
let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
let k = digits.len() as i32;
let n = power.parse::<i32>().unwrap_or(0) + 1;
if k <= n && n <= 21 {
format!("{digits}{}", "0".repeat((n - k) as usize))
} else if 0 < n && n <= 21 {
format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
} else if -6 < n && n <= 0 {
format!("0.{}{digits}", "0".repeat((-n) as usize))
} else {
let sign = if n > 0 { '+' } else { '-' };
let lead = if k == 1 {
digits.clone()
} else {
format!("{}.{}", &digits[..1], &digits[1..])
};
format!("{lead}e{sign}{}", (n - 1).abs())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn numbers_are_written_the_way_ecmascript_writes_them() {
for (value, text) in [
(1.0, "1"),
(1e21, "1e+21"),
(1e20, "100000000000000000000"),
(1e-7, "1e-7"),
(1e-6, "0.000001"),
(0.1, "0.1"),
(-40.5, "-40.5"),
(-0.0, "0"),
(123.456, "123.456"),
(1.5e-9, "1.5e-9"),
(12345678901234567890.0, "12345678901234567000"),
(0.3333333333333333, "0.3333333333333333"),
(5e-324, "5e-324"),
(1.7976931348623157e308, "1.7976931348623157e+308"),
(f64::NAN, "0"),
] {
assert_eq!(es_number(value), text, "{value:e}");
}
}
/// U+FFFF sorts after U+1F600 by code point but before it by UTF-16 code
/// unit (0xFFFF against the high surrogate 0xD83D), which is the order
/// RFC 8785 asks for.
#[test]
fn members_sort_by_utf16_code_units() {
let value: Value =
serde_json::from_str(r#"{"\uffff":1,"\ud83d\ude00":2,"b":[1.0,true,null],"a":"x\ty"}"#).unwrap();
assert_eq!(canonical(&value), "{\"a\":\"x\\ty\",\"b\":[1,true,null],\"\u{1F600}\":2,\"\u{FFFF}\":1}");
}
#[test]
fn a_stamp_is_checked_by_shape_and_range() {
assert!(is_stamp("2026-10-02T14:05:09Z"));
for bad in [
"2026-10-02 14:05:09Z",
"2026-13-02T14:05:09Z",
"2026-10-02T24:00:00Z",
"2026-10-02T14:05:09",
"2026-1a-02T14:05:09Z",
] {
assert!(!is_stamp(bad), "{bad}");
}
}
#[test]
fn a_written_header_reads_back() {
let document = json!({"version": 3, "blocks": []});
let written = Header::new("\u{7}", "Dashboard", "op", "2026-10-02T14:05:09Z".into(), document);
assert_eq!(written.name, "Dashboard");
assert_eq!(read(&written.to_text(), "test").unwrap(), written);
let long = Header::new(&"x".repeat(NAME_MAX + 5), "", "", "2026-10-02T14:05:09Z".into(), json!({}));
assert_eq!(long.name.chars().count(), NAME_MAX);
}
/// A deep document under the 128 KiB document cap indents to more than
/// the file cap. It must still write a file a reader accepts.
#[test]
fn a_large_document_writes_a_file_that_reads() {
let cell = |g: usize, c: usize| {
json!({
"label": format!("Discharge pressure, stage {c:02}, train {g:02}"),
"value": {"source": format!(
"telemetry.compressor_train_{g:02}.discharge_pressure_stage_{c:02}_{}",
"x".repeat(40)
)}
})
};
let grid = |g: usize| {
json!({"id": format!("grid-{g}"), "title": "Train", "body": {
"kind": "status_grid", "cells": (0..20).map(|c| cell(g, c)).collect::<Vec<_>>()
}})
};
let group = |g: usize| {
json!({"id": format!("group-{g}"), "title": "Group", "body": {
"kind": "group", "flow": "stack", "children": [grid(2 * g), grid(2 * g + 1)]
}})
};
let document = json!({"version": 3, "blocks": (0..16).map(group).collect::<Vec<_>>()});
let compact = document.to_string().len();
assert!((100 * 1024..128 * 1024).contains(&compact), "{compact}");
let written = Header::new("Station", "", "op", "2026-10-02T14:05:09Z".into(), document);
assert!(serde_json::to_string_pretty(&written.to_value()).unwrap().len() > FILE_MAX);
let text = written.to_text();
assert!(text.ends_with('\n'));
assert_eq!(read(&text, "test").unwrap(), written);
// A small file is still indented.
let small = Header::new("n", "", "", "2026-10-02T14:05:09Z".into(), json!({"version": 3}));
assert!(small.to_text().contains("\n \"wdash\": 1"));
}
#[test]
fn the_header_is_refused_field_by_field() {
let good = Header::new("n", "", "a", "2026-10-02T14:05:09Z".into(), json!({"version": 3})).to_value();
let refused = |change: &dyn Fn(&mut Value)| {
let mut file = good.clone();
change(&mut file);
header(&file, "test").unwrap_err()
};
assert!(refused(&|f| f["wdash"] = json!(2)).contains("this test reads format 1"));
assert!(refused(&|f| f["signed_by"] = json!("x")).contains("signed_by"));
assert!(refused(&|f| {
f.as_object_mut().unwrap().remove("author");
})
.contains("author"));
assert!(refused(&|f| f["name"] = json!("")).contains("name"));
assert!(refused(&|f| f["exported_at"] = json!("today")).contains("exported_at"));
assert!(refused(&|f| f["checksum"] = json!("sha256:XY")).contains("checksum"));
assert!(refused(&|f| f["document"]["version"] = json!(4)).contains("checksum does not match"));
assert!(refused(&|f| f["document"] = json!([])).contains("document"));
assert!(read(&" ".repeat(FILE_MAX + 1), "test").unwrap_err().contains("limited"));
}
}