fix(notes): apply only the outstanding load and own the save lock

A second load reply, from Discard clicked twice or during the first
load, replaced the editor again after it had become editable. Only the
reply to the outstanding load is applied now, and Discard does nothing
while a load is outstanding.

The save lock holds an owner token and is released only by its owner; a
stale lock is renamed away before removal, so two saves cannot both take
it over. A save removes only a staging file it created and, holding the
lock, removes staging files left by saves that ended before their
rename. A save acknowledgement arriving after the page's timeout is
still accepted, and text that cannot be encoded is refused before it is
sent. app.wasm is rebuilt and the package re-signed with the demo key.
This commit is contained in:
Marco Allegretti 2026-10-09 09:01:28 +00:00
parent 1928ffb661
commit 87436d0e08
No known key found for this signature in database
4 changed files with 78 additions and 28 deletions

View file

@ -1 +1 @@
f84d1c550b851837fd1ef7b90cd15cee29c9967facc871a117c1ea2b650a171136c1335f4ee24920a740867969a6f017e130e68e9767122d0f23e2320fcf2f0e 555f2d3d0183d28f99f66efef3f2dc8bb8aa3e6a4d038dc78b1414ccf54d23dd52a1668314d377d10603580908d7d9de7109a6ddcf0d7aa175bbf4bbd835c80c

View file

@ -50,22 +50,49 @@ fn load() -> Value {
} }
} }
/// Exclusive access to the notes file for one save. /// A value unique to this process and moment, for lock ownership and
struct SaveLock; /// staging file names.
fn unique() -> String {
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or_default();
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
format!("{nanos}-{n}")
}
/// Exclusive access to the notes file for one save. The lock file holds an
/// owner token, so a save only ever removes its own lock.
struct SaveLock {
token: String,
}
impl SaveLock { impl SaveLock {
fn acquire() -> Result<Self, String> { fn acquire() -> Result<Self, String> {
use std::io::Write;
let token = unique();
for _ in 0..50 { for _ in 0..50 {
match std::fs::OpenOptions::new().write(true).create_new(true).open(LOCK_PATH) { match std::fs::OpenOptions::new()
Ok(_) => return Ok(SaveLock), .write(true)
.create_new(true)
.open(LOCK_PATH)
{
Ok(mut file) => {
let _ = file.write_all(token.as_bytes());
return Ok(SaveLock { token });
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
// A lock older than STALE_LOCK (or of unknown age) was left
// by an ended session. Renaming it away is atomic, so only
// one save can take it over.
let stale = std::fs::metadata(LOCK_PATH) let stale = std::fs::metadata(LOCK_PATH)
.and_then(|m| m.modified()) .and_then(|m| m.modified())
.ok() .map(|t| t.elapsed().is_ok_and(|age| age > STALE_LOCK))
.and_then(|t| t.elapsed().ok()) .unwrap_or(true);
.is_some_and(|age| age > STALE_LOCK); let taken = format!("/data/.notes.lock.{token}.stale");
if stale { if stale && std::fs::rename(LOCK_PATH, &taken).is_ok() {
let _ = std::fs::remove_file(LOCK_PATH); let _ = std::fs::remove_file(&taken);
} else { } else {
std::thread::sleep(std::time::Duration::from_millis(20)); std::thread::sleep(std::time::Duration::from_millis(20));
} }
@ -79,8 +106,25 @@ impl SaveLock {
impl Drop for SaveLock { impl Drop for SaveLock {
fn drop(&mut self) { fn drop(&mut self) {
if std::fs::read_to_string(LOCK_PATH).is_ok_and(|t| t == self.token) {
let _ = std::fs::remove_file(LOCK_PATH); let _ = std::fs::remove_file(LOCK_PATH);
} }
}
}
/// Removes staging files left by saves that ended before their rename. Only
/// called with the lock held, when no other save is in progress.
fn remove_abandoned_staging() {
let Ok(entries) = std::fs::read_dir("/data") else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if name.starts_with(".notes.txt.") && name.ends_with(".saving") {
let _ = std::fs::remove_file(entry.path());
}
}
} }
/// Writes `text` to a staging file unique to this save, syncs it and renames /// Writes `text` to a staging file unique to this save, syncs it and renames
@ -88,19 +132,14 @@ impl Drop for SaveLock {
/// the new text in full. /// the new text in full.
fn replace_notes(text: &str) -> std::io::Result<()> { fn replace_notes(text: &str) -> std::io::Result<()> {
use std::io::Write; use std::io::Write;
let nanos = std::time::SystemTime::now() let staging = format!("/data/.notes.txt.{}.saving", unique());
.duration_since(std::time::UNIX_EPOCH) let mut file = std::fs::OpenOptions::new()
.map(|d| d.as_nanos())
.unwrap_or_default();
let staging = format!("/data/.notes.txt.{nanos}.saving");
let written = std::fs::OpenOptions::new()
.write(true) .write(true)
.create_new(true) .create_new(true)
.open(&staging) .open(&staging)?;
.and_then(|mut file| { let written = file
file.write_all(text.as_bytes())?; .write_all(text.as_bytes())
file.sync_all() .and_then(|()| file.sync_all())
})
.and_then(|()| std::fs::rename(&staging, NOTES_PATH)); .and_then(|()| std::fs::rename(&staging, NOTES_PATH));
if written.is_err() { if written.is_err() {
let _ = std::fs::remove_file(&staging); let _ = std::fs::remove_file(&staging);
@ -109,9 +148,7 @@ fn replace_notes(text: &str) -> std::io::Result<()> {
} }
fn save(seq: &Value, base: &str, text: &str) -> Value { fn save(seq: &Value, base: &str, text: &str) -> Value {
let error = |conflict: bool, message: String| { let error = |conflict: bool, message: String| json!({ "op": "error", "seq": seq, "conflict": conflict, "message": message });
json!({ "op": "error", "seq": seq, "conflict": conflict, "message": message })
};
if text.len() > MAX_NOTES { if text.len() > MAX_NOTES {
return error(false, format!("notes are limited to {MAX_NOTES} bytes")); return error(false, format!("notes are limited to {MAX_NOTES} bytes"));
} }
@ -119,6 +156,7 @@ fn save(seq: &Value, base: &str, text: &str) -> Value {
Ok(lock) => lock, Ok(lock) => lock,
Err(message) => return error(false, message), Err(message) => return error(false, message),
}; };
remove_abandoned_staging();
let current = match stored() { let current = match stored() {
Ok(bytes) => revision(&bytes), Ok(bytes) => revision(&bytes),
Err(message) => return error(false, message), Err(message) => return error(false, message),

View file

@ -118,6 +118,7 @@
var rev = null; var rev = null;
var seq = 0; var seq = 0;
var pending = null; var pending = null;
var lastSent = null;
var encoder = new TextEncoder(); var encoder = new TextEncoder();
function setStatus(msg) { statusEl.textContent = msg; } function setStatus(msg) { statusEl.textContent = msg; }
@ -143,11 +144,18 @@
return; return;
} }
var request = { op: 'save', seq: seq + 1, base: rev, text: editor.value }; var request = { op: 'save', seq: seq + 1, base: rev, text: editor.value };
try {
encodeURIComponent(request.text);
} catch (_) {
setStatus('not saved: the text contains characters that cannot be stored');
return;
}
if (encoder.encode(JSON.stringify(request)).length > MAX_MESSAGE) { if (encoder.encode(JSON.stringify(request)).length > MAX_MESSAGE) {
setStatus('not saved: the notes are too long'); setStatus('not saved: the notes are too long');
return; return;
} }
seq += 1; seq += 1;
lastSent = { seq: seq, text: request.text };
pending = { pending = {
seq: seq, seq: seq,
text: request.text, text: request.text,
@ -163,7 +171,7 @@
// Discard reloads the stored notes, replacing unsaved edits. // Discard reloads the stored notes, replacing unsaved edits.
document.getElementById('discard').addEventListener('click', function () { document.getElementById('discard').addEventListener('click', function () {
if (!window.weftIpc || pending) return; if (!window.weftIpc || pending || rev === null) return;
editor.value = saved; editor.value = saved;
countChars(); countChars();
rev = null; rev = null;
@ -183,14 +191,18 @@
var msg; var msg;
try { msg = JSON.parse(raw); } catch (_) { return; } try { msg = JSON.parse(raw); } catch (_) { return; }
if (msg.op === 'loaded') { if (msg.op === 'loaded') {
// Only the reply to the outstanding load applies; the editor is
// read-only until it arrives, so it never replaces newer text.
if (rev !== null) return;
editor.value = msg.text; editor.value = msg.text;
countChars(); countChars();
saved = msg.text; saved = msg.text;
rev = msg.rev; rev = msg.rev;
setLoaded(true); setLoaded(true);
setStatus(''); setStatus('');
} else if (msg.op === 'saved' && pending && msg.seq === pending.seq) { } else if (msg.op === 'saved' && lastSent && msg.seq === lastSent.seq) {
saved = pending.text; // Also accepts an acknowledgement that arrives after the timeout.
saved = lastSent.text;
rev = msg.rev; rev = msg.rev;
finishSave(); finishSave();
setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet'); setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet');