Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

#197, #193: web recovery retries failed snapshot writes and keeps skipped snapshots dirty

Claude7fbb22370737
diff --git a/apps/filmcraft-web/src/lib.rs b/apps/filmcraft-web/src/lib.rs
index 469d2107a..754e6dd74 100644
--- a/apps/filmcraft-web/src/lib.rs
+++ b/apps/filmcraft-web/src/lib.rs
@@ -24,6 +24,7 @@ pub mod fs;
pub mod import;
pub mod opfs;
pub mod recovery;
+pub mod recovery_policy;
pub mod webcodecs;
use std::cell::RefCell;
diff --git a/apps/filmcraft-web/src/opfs.rs b/apps/filmcraft-web/src/opfs.rs
index b19071082..a246a52d2 100644
--- a/apps/filmcraft-web/src/opfs.rs
+++ b/apps/filmcraft-web/src/opfs.rs
@@ -10,8 +10,13 @@ use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use web_sys::{FileSystemDirectoryHandle, FileSystemFileHandle};
+/// Called with whether a queued write reached OPFS.
+pub type Done = Box<dyn FnOnce(bool)>;
+
thread_local! {
- static QUEUE: RefCell<(BTreeMap<String, Vec<u8>>, bool)> = const { RefCell::new((BTreeMap::new(), false)) };
+ /// Pending writes per path (bytes and the callbacks of every write coalesced into them), and
+ /// whether the writer task is running.
+ static QUEUE: RefCell<(BTreeMap<String, (Vec<u8>, Vec<Done>)>, bool)> = const { RefCell::new((BTreeMap::new(), false)) };
}
/// Whether this browser has OPFS (`navigator.storage.getDirectory`).
@@ -60,9 +65,17 @@ async fn write_now(rel: &str, data: &[u8]) -> Result<(), JsValue> {
/// Queue a write of `data` to `rel` (relative to the OPFS root).
pub fn write(rel: String, data: Vec<u8>) {
+ write_then(rel, data, None);
+}
+
+/// [`write`], then call `done` with whether it succeeded. A write replaced by a newer one to the
+/// same path reports the newer one's result.
+pub fn write_then(rel: String, data: Vec<u8>, done: Option<Done>) {
let start = QUEUE.with(|q| {
let mut q = q.borrow_mut();
- q.0.insert(rel, data);
+ let e = q.0.entry(rel).or_default();
+ e.0 = data;
+ e.1.extend(done);
!std::mem::replace(&mut q.1, true)
});
if !start {
@@ -81,10 +94,14 @@ pub fn write(rel: String, data: Vec<u8>) {
}
}
});
- let Some((rel, data)) = next else { break };
- if let Err(e) = write_now(&rel, &data).await {
+ let Some((rel, (data, done))) = next else { break };
+ let r = write_now(&rel, &data).await;
+ if let Err(e) = &r {
log::warn!("OPFS write {rel}: {e:?}");
}
+ for d in done {
+ d(r.is_ok());
+ }
}
});
}
diff --git a/apps/filmcraft-web/src/recovery.rs b/apps/filmcraft-web/src/recovery.rs
index 939559a46..6001531e8 100644
--- a/apps/filmcraft-web/src/recovery.rs
+++ b/apps/filmcraft-web/src/recovery.rs
@@ -6,24 +6,32 @@
//! - Imported media are copied to `media/<name>` (the browser streams the copy; nothing goes
//! through wasm memory), so the snapshot's `/files/<name>` references resolve after a reload.
//! - At start-up a dirty snapshot is reopened (`?norecover` skips it, `?fresh` also skips the media).
+//! A skipped snapshot stays dirty until this session writes its own ([`crate::recovery_policy`]).
+
+use std::cell::{Cell, RefCell};
+use std::rc::Rc;
use filmcraft_engine::Session;
use serde_json::{Value, json};
use crate::opfs;
+use crate::recovery_policy::{Action, Policy};
const SNAPSHOT: &str = "recovery/snapshot.fcproj";
const META: &str = "recovery/meta.json";
-/// Seconds between snapshots of a changing project.
-const INTERVAL_S: f64 = 5.0;
/// Media larger than this are not copied to OPFS.
const KEEP_MAX: f64 = 4.0 * 1024.0 * 1024.0 * 1024.0;
+/// A finished OPFS write, reported back to the next [`Autosave::tick`].
+enum Outcome {
+ Snapshot { revision: u64, ok: bool },
+ Clean { ok: bool },
+}
+
#[derive(Default)]
pub struct Autosave {
- last_revision: u64,
- last_time: f64,
- last_dirty: Option<bool>,
+ policy: Policy,
+ outcomes: Rc<RefCell<Vec<Outcome>>>,
}
impl Autosave {
@@ -33,22 +41,44 @@ impl Autosave {
return;
}
let now = ctx.input(|i| i.time);
- let dirty = s.revision != s.saved_revision;
- if dirty {
- if s.revision != self.last_revision && now - self.last_time >= INTERVAL_S {
- opfs::write(SNAPSHOT.into(), filmcraft_format::encode(&s.project, false));
+ for o in self.outcomes.borrow_mut().drain(..) {
+ match o {
+ Outcome::Snapshot { revision, ok } => self.policy.written(revision, ok, now),
+ Outcome::Clean { ok } => self.policy.cleaned(ok, now),
+ }
+ }
+ match self.policy.tick(now, s.revision, s.saved_revision) {
+ Action::Nothing => {}
+ Action::WakeAfter(secs) => ctx.request_repaint_after(std::time::Duration::from_secs_f64(secs)),
+ Action::WriteSnapshot(revision) => {
+ // Snapshot and meta both have to land; either failing retries the pair.
+ let failed = Rc::new(Cell::new(false));
+ let left = Rc::new(Cell::new(2u8));
+ let done = |out: Rc<RefCell<Vec<Outcome>>>, failed: Rc<Cell<bool>>, left: Rc<Cell<u8>>, ctx: egui::Context| -> opfs::Done {
+ Box::new(move |ok| {
+ failed.set(failed.get() || !ok);
+ left.set(left.get().saturating_sub(1));
+ if left.get() == 0 {
+ out.borrow_mut().push(Outcome::Snapshot { revision, ok: !failed.get() });
+ ctx.request_repaint();
+ }
+ })
+ };
let meta = json!({"dirty": true, "name": s.project.name, "revision": s.revision, "time": js_sys::Date::now()});
- opfs::write(META.into(), meta.to_string().into_bytes());
- self.last_revision = s.revision;
- self.last_time = now;
- } else if s.revision != self.last_revision {
- // the UI may go idle: wake up when the snapshot is due
- ctx.request_repaint_after(std::time::Duration::from_secs_f64((INTERVAL_S - (now - self.last_time)).max(0.05)));
+ let d1 = done(self.outcomes.clone(), failed.clone(), left.clone(), ctx.clone());
+ let d2 = done(self.outcomes.clone(), failed, left, ctx.clone());
+ opfs::write_then(SNAPSHOT.into(), filmcraft_format::encode(&s.project, false), Some(d1));
+ opfs::write_then(META.into(), meta.to_string().into_bytes(), Some(d2));
+ }
+ Action::WriteClean => {
+ let (out, ctx) = (self.outcomes.clone(), ctx.clone());
+ let done: opfs::Done = Box::new(move |ok| {
+ out.borrow_mut().push(Outcome::Clean { ok });
+ ctx.request_repaint();
+ });
+ opfs::write_then(META.into(), json!({"dirty": false}).to_string().into_bytes(), Some(done));
}
- } else if self.last_dirty != Some(false) {
- opfs::write(META.into(), json!({"dirty": false}).to_string().into_bytes());
}
- self.last_dirty = Some(dirty);
}
}
diff --git a/apps/filmcraft-web/src/recovery_policy.rs b/apps/filmcraft-web/src/recovery_policy.rs
new file mode 100644
index 000000000..8426d3c39
--- /dev/null
+++ b/apps/filmcraft-web/src/recovery_policy.rs
@@ -0,0 +1,88 @@
+//! When the web recovery snapshot is written or marked clean (pure, so it is tested natively in
+//! `tests/recovery_policy.rs`; the OPFS side lives in [`crate::recovery`]).
+//!
+//! - A dirty project is snapshotted at most every [`INTERVAL_S`] seconds, once per revision. A write
+//! that fails is retried after the interval, without waiting for another edit (#197).
+//! - The meta is marked clean only to retire a snapshot this session wrote. A snapshot left by an
+//! earlier session that was not reopened (`?norecover`, `?fresh`) stays dirty (#193).
+
+/// Seconds between snapshots of a changing project.
+pub const INTERVAL_S: f64 = 5.0;
+
+/// What the caller should do this frame.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Action {
+ Nothing,
+ /// Write the snapshot and a dirty meta for this revision, then report with [`Policy::written`].
+ WriteSnapshot(u64),
+ /// Write a clean meta, then report with [`Policy::cleaned`].
+ WriteClean,
+ /// Nothing now; wake up after this many seconds.
+ WakeAfter(f64),
+}
+
+#[derive(Debug, Default)]
+pub struct Policy {
+ /// Revision whose snapshot was last written or is being written.
+ last_revision: Option<u64>,
+ last_time: Option<f64>,
+ /// This session wrote a dirty meta that is not yet retired.
+ owns_dirty_meta: bool,
+ /// A clean-meta write is in flight.
+ cleaning: bool,
+ /// Snapshot writes started so far, and how many had started when the clean write did (a
+ /// snapshot started after it makes the meta dirty again).
+ snapshots: u64,
+ snapshots_at_clean: u64,
+}
+
+impl Policy {
+ /// Called every frame with the session's revisions and the time in seconds.
+ pub fn tick(&mut self, now: f64, revision: u64, saved_revision: u64) -> Action {
+ if revision != saved_revision {
+ if self.last_revision == Some(revision) {
+ return Action::Nothing;
+ }
+ let since = self.last_time.map_or(f64::INFINITY, |t| now - t);
+ if since >= INTERVAL_S {
+ self.last_revision = Some(revision);
+ self.last_time = Some(now);
+ self.owns_dirty_meta = true;
+ self.snapshots += 1;
+ return Action::WriteSnapshot(revision);
+ }
+ return Action::WakeAfter((INTERVAL_S - since).max(0.05));
+ }
+ if self.owns_dirty_meta && !self.cleaning {
+ let since = self.last_time.map_or(f64::INFINITY, |t| now - t);
+ if self.last_revision.is_some() || since >= INTERVAL_S {
+ self.cleaning = true;
+ self.snapshots_at_clean = self.snapshots;
+ return Action::WriteClean;
+ }
+ return Action::WakeAfter((INTERVAL_S - since).max(0.05));
+ }
+ Action::Nothing
+ }
+
+ /// The snapshot write for `revision` finished.
+ pub fn written(&mut self, revision: u64, ok: bool, now: f64) {
+ if !ok && self.last_revision == Some(revision) {
+ // retry after the interval, even if nothing else changes
+ self.last_revision = None;
+ self.last_time = Some(now);
+ }
+ }
+
+ /// The clean-meta write finished.
+ pub fn cleaned(&mut self, ok: bool, now: f64) {
+ self.cleaning = false;
+ if ok {
+ self.owns_dirty_meta = self.snapshots != self.snapshots_at_clean;
+ } else {
+ // retry after the interval
+ self.last_revision = None;
+ self.last_time = Some(now);
+ }
+ }
+}
diff --git a/apps/filmcraft-web/tests/recovery_policy.rs b/apps/filmcraft-web/tests/recovery_policy.rs
new file mode 100644
index 000000000..c60b34d5b
--- /dev/null
+++ b/apps/filmcraft-web/tests/recovery_policy.rs
@@ -0,0 +1,77 @@
+//! The web recovery snapshot policy. It is pure, so it runs natively even though the rest of the
+//! crate is wasm32-only.
+
+#[path = "../src/recovery_policy.rs"]
+mod recovery_policy;
+
+use recovery_policy::{Action, INTERVAL_S, Policy};
+
+/// #197: a snapshot write that fails is retried after the interval without another edit.
+#[test]
+fn failed_snapshot_write_is_retried_without_another_edit() {
+ let mut p = Policy::default();
+ assert_eq!(p.tick(0.0, 3, 0), Action::WriteSnapshot(3));
+ p.written(3, false, 0.1);
+ // not immediately (no spinning on a failing disk)…
+ assert!(matches!(p.tick(1.0, 3, 0), Action::WakeAfter(_)));
+ // …but once the interval has passed, with the revision unchanged
+ assert_eq!(p.tick(0.1 + INTERVAL_S, 3, 0), Action::WriteSnapshot(3));
+ p.written(3, true, 5.2);
+ assert_eq!(p.tick(20.0, 3, 0), Action::Nothing);
+}
+
+/// A failure reported for an older revision doesn't make the newer one be written again.
+#[test]
+fn stale_failure_is_ignored() {
+ let mut p = Policy::default();
+ assert_eq!(p.tick(0.0, 1, 0), Action::WriteSnapshot(1));
+ assert_eq!(p.tick(INTERVAL_S, 2, 0), Action::WriteSnapshot(2));
+ p.written(1, false, INTERVAL_S);
+ assert_eq!(p.tick(3.0 * INTERVAL_S, 2, 0), Action::Nothing);
+}
+
+/// #193: a clean session (started with `?norecover` / `?fresh`, so the snapshot left by an
+/// earlier session was not reopened) never marks that snapshot clean.
+#[test]
+fn clean_start_leaves_an_unconsumed_snapshot_dirty() {
+ let mut p = Policy::default();
+ for t in 0..100 {
+ assert_eq!(p.tick(t as f64, 0, 0), Action::Nothing);
+ }
+}
+
+/// The snapshot this session wrote is retired once the project is saved.
+#[test]
+fn saving_marks_own_snapshot_clean() {
+ let mut p = Policy::default();
+ assert_eq!(p.tick(0.0, 1, 0), Action::WriteSnapshot(1));
+ p.written(1, true, 0.1);
+ assert_eq!(p.tick(1.0, 1, 1), Action::WriteClean);
+ assert_eq!(p.tick(1.1, 1, 1), Action::Nothing);
+ p.cleaned(true, 1.2);
+ assert_eq!(p.tick(30.0, 1, 1), Action::Nothing);
+}
+
+/// A failed clean write is retried after the interval.
+#[test]
+fn failed_clean_write_is_retried() {
+ let mut p = Policy::default();
+ assert_eq!(p.tick(0.0, 1, 0), Action::WriteSnapshot(1));
+ p.written(1, true, 0.1);
+ assert_eq!(p.tick(1.0, 1, 1), Action::WriteClean);
+ p.cleaned(false, 1.1);
+ assert!(matches!(p.tick(2.0, 1, 1), Action::WakeAfter(_)));
+ assert_eq!(p.tick(1.1 + INTERVAL_S, 1, 1), Action::WriteClean);
+}
+
+/// An edit made while the clean write is in flight keeps the meta dirty after it lands.
+#[test]
+fn edit_during_clean_write_keeps_meta_owned() {
+ let mut p = Policy::default();
+ assert_eq!(p.tick(0.0, 1, 0), Action::WriteSnapshot(1));
+ assert_eq!(p.tick(10.0, 1, 1), Action::WriteClean);
+ assert_eq!(p.tick(20.0, 2, 1), Action::WriteSnapshot(2));
+ p.cleaned(true, 20.1);
+ // saved again: the newer snapshot must be retired too
+ assert_eq!(p.tick(30.0, 2, 2), Action::WriteClean);
+}