diff --git a/.gitignore b/.gitignore index c642375..c407450 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ Thumbs.db /tests/components/*/target/ +/examples/*/target/ diff --git a/docs/building.md b/docs/building.md index ef03486..27b96c0 100644 --- a/docs/building.md +++ b/docs/building.md @@ -86,8 +86,12 @@ rustup target add wasm32-wasip2 cd examples/org.weft.demo.counter cargo build --release # output: target/wasm32-wasip2/release/app.wasm +cp target/wasm32-wasip2/release/app.wasm app.wasm +rm -rf target ``` +The signature covers every file in the package directory, so remove the crate's `target` directory before signing it again (see *Signing packages*). The demo keys in `examples/keys` are test fixtures, not a signing authority. + ## weft-runtime with Wasmtime ```sh diff --git a/examples/org.weft.demo.notes/app.wasm b/examples/org.weft.demo.notes/app.wasm index bd523ab..760286d 100644 Binary files a/examples/org.weft.demo.notes/app.wasm and b/examples/org.weft.demo.notes/app.wasm differ diff --git a/examples/org.weft.demo.notes/signature.sig b/examples/org.weft.demo.notes/signature.sig index feb4212..b996332 100644 --- a/examples/org.weft.demo.notes/signature.sig +++ b/examples/org.weft.demo.notes/signature.sig @@ -1 +1 @@ -e781544104eee4538e17f953ea3223903e2b2a46a78705cd1ffa8d6946a62d0385c76eab2cc1c2533eecbeff7600e76a4205abc66915be8851fe2e71316ebc0d \ No newline at end of file +619aae11afd3f9cd6c6c094dff51e22922f185b8b49b15f77d136fcc74ea3354e6d908e576eae55c124c9d937725cd947593264e4c8e84409a927154522f120f \ No newline at end of file diff --git a/examples/org.weft.demo.notes/src/main.rs b/examples/org.weft.demo.notes/src/main.rs index 485544e..5c31516 100644 --- a/examples/org.weft.demo.notes/src/main.rs +++ b/examples/org.weft.demo.notes/src/main.rs @@ -7,31 +7,82 @@ wit_bindgen::generate!({ }, }); +use serde_json::{Value, json}; use weft::app::{ipc, notify}; const NOTES_PATH: &str = "/data/notes.txt"; +const STAGING_PATH: &str = "/data/.notes.txt.saving"; +/// Largest note accepted, in bytes; app messages are limited to 64 KiB. +const MAX_NOTES: usize = 60 * 1024; -fn load_notes() -> String { - std::fs::read_to_string(NOTES_PATH).unwrap_or_default() +/// A revision names the exact stored bytes. A save must name the revision +/// it was edited from, so a save based on stale content is refused instead +/// of silently replacing changes made in another window. +fn revision(bytes: &[u8]) -> String { + // FNV-1a, 64-bit. + let hash = bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| { + (h ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3) + }); + format!("{hash:016x}") } -fn save_notes(text: &str) -> Result<(), String> { - std::fs::write(NOTES_PATH, text).map_err(|e| e.to_string()) +fn stored() -> Result, String> { + match std::fs::read(NOTES_PATH) { + Ok(bytes) => Ok(bytes), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(e) => Err(format!("cannot read notes: {e}")), + } } -fn json_text(text: &str) -> String { - let escaped = text - .replace('\\', "\\\\") - .replace('"', "\\\"") - .replace('\n', "\\n") - .replace('\r', "\\r") - .replace('\t', "\\t"); - format!("{{\"text\":\"{escaped}\"}}") +fn load() -> Value { + let bytes = match stored() { + Ok(bytes) => bytes, + Err(message) => return json!({ "op": "error", "message": message }), + }; + match String::from_utf8(bytes) { + Ok(text) => json!({ "op": "loaded", "rev": revision(text.as_bytes()), "text": text }), + Err(_) => json!({ "op": "error", "message": "stored notes are not valid UTF-8" }), + } } -fn json_error(msg: &str) -> String { - let escaped = msg.replace('"', "\\\""); - format!("{{\"error\":\"{escaped}\"}}") +fn save(seq: &Value, base: &str, text: &str) -> Value { + let error = |conflict: bool, message: String| { + json!({ "op": "error", "seq": seq, "conflict": conflict, "message": message }) + }; + if text.len() > MAX_NOTES { + return error(false, format!("notes are limited to {MAX_NOTES} bytes")); + } + let current = match stored() { + Ok(bytes) => revision(&bytes), + Err(message) => return error(false, message), + }; + if current != base { + return error(true, "the notes were changed elsewhere".to_owned()); + } + // Written beside the file and renamed over it, so the stored notes are + // always either the previous or the new text in full. + let written = std::fs::write(STAGING_PATH, text.as_bytes()) + .and_then(|()| std::fs::rename(STAGING_PATH, NOTES_PATH)); + match written { + Ok(()) => json!({ "op": "saved", "seq": seq, "rev": revision(text.as_bytes()) }), + Err(e) => { + let _ = std::fs::remove_file(STAGING_PATH); + error(false, format!("cannot save notes: {e}")) + } + } +} + +fn handle(raw: &str) -> Option { + let request: Value = serde_json::from_str(raw).ok()?; + match request.get("op")?.as_str()? { + "load" => Some(load()), + "save" => { + let base = request.get("base")?.as_str()?; + let text = request.get("text")?.as_str()?; + Some(save(request.get("seq").unwrap_or(&Value::Null), base, text)) + } + _ => None, + } } fn main() { @@ -39,19 +90,9 @@ fn main() { loop { if let Some(raw) = ipc::recv() { - let raw = raw.trim().to_owned(); - let reply = if raw == "load" { - json_text(&load_notes()) - } else if let Some(rest) = raw.strip_prefix("save:") { - let text = rest.replace("\\n", "\n"); - match save_notes(&text) { - Ok(()) => json_text(&text), - Err(e) => json_error(&e), - } - } else { - continue; - }; - let _ = ipc::send(&reply); + if let Some(reply) = handle(&raw) { + let _ = ipc::send(&reply.to_string()); + } } else { std::thread::sleep(std::time::Duration::from_millis(10)); } diff --git a/examples/org.weft.demo.notes/ui/index.html b/examples/org.weft.demo.notes/ui/index.html index e0592e5..94f0099 100644 --- a/examples/org.weft.demo.notes/ui/index.html +++ b/examples/org.weft.demo.notes/ui/index.html @@ -103,58 +103,84 @@