M13.24: web app depth (WEB-1) — GPU effects in frame workers, OPFS disk cache, storage manager
- GPU in the browser: each frame worker opens its own WebGPU device (Gpu::request_deferred) and renders the GPU compositor and GPU effects with deferred readbacks (effectcraft-gpu deferred): readbacks keyed by content start with map_async and miss, the pass returns placeholders, the layer cache's gate drops inserts, and FrameServer::resume renders again once the device delivered. Backend Auto times whole frames per comp in the workers. Frames with effects go to GPU workers instead of the page. CPU fallback without WebGPU in workers (?nogpuworkers). - Fix: a WGSL constant (3.40282347e38) that Chrome rejects invalidated every GPU kernel in Chrome (the page's compositor too); a test checks every float literal fits f32. - Disk cache in the Origin Private File System: workers write sealed frame entries with sync access handles (temp file + move), the page keeps the DiskIndex (LRU under the settings' limit, at most half the quota) and reads hits instead of rendering; survives reloads; blue cache bar. - Storage manager: Settings ▸ Disk ▸ Browser Storage (usage/quota, persistent storage, Clear buttons, automation ids) and storage.info / storage.persist / storage.clear (StorageHost). - Docs: web.md (GPU workers, deferred passes, disk cache, storage manager, threading design: one engine instance per worker), architecture, preferences, parity (WEB-1), roadmap. - Tests: deferred passes vs CPU on a real device, placeholder gating, frame server passes and Auto, GPU worker routing + disk cache across a reload, storage commands and widgets, store usage by kind; smoke test: GPU effect frames in workers with pixel parity, disk hits after a reload, storage manager. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
081ce79de3
commit
1b726349ab
@@ -6,7 +6,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use effectcraft_engine::Session;
|
||||
|
||||
use crate::{api, audio, browse, files, frames, persist, worker};
|
||||
use crate::{api, audio, browse, diskcache, files, frames, persist, storage, worker};
|
||||
use effectcraft_ui_egui::EffectcraftApp;
|
||||
use serde_json::json;
|
||||
use wasm_bindgen::prelude::*;
|
||||
@@ -104,6 +104,10 @@ impl eframe::App for WebApp {
|
||||
}
|
||||
api::set_info("gpu", json!({"compositor": self.app.gpu_adapter(), "viewerOnGpu": self.app.viewer_on_gpu()}));
|
||||
api::set_info("frameWorkers", frames::stats());
|
||||
// Settings ▸ Disk ▸ Disk Cache (frames in the Origin Private File System).
|
||||
let d = &self.app.session.prefs.disk;
|
||||
diskcache::configure(d.disk_cache_enabled, d.disk_cache_max_gb, storage::quota());
|
||||
api::set_info("diskCache", diskcache::stats());
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
@@ -139,6 +143,7 @@ pub fn session() -> Session {
|
||||
config: Some(Arc::new(persist::config())),
|
||||
offload: (!query_flag("noworkers")).then(|| Arc::new(worker::WorkerOffload) as Arc<dyn effectcraft_engine::offload::Offload>),
|
||||
browser: Some(Arc::new(browse::WebBrowser)),
|
||||
storage: Some(Arc::new(storage::WebStorage)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -186,6 +191,8 @@ pub async fn start(canvas_id: String) -> Result<(), JsValue> {
|
||||
api::set_info("storage", json!({"backend": persist::backend(), "entries": stored, "loadMs": js_sys::Date::now() - t0}));
|
||||
audio::install_unlock();
|
||||
browse::restore();
|
||||
diskcache::init();
|
||||
storage::refresh();
|
||||
let runner = eframe::WebRunner::new();
|
||||
runner
|
||||
.start(
|
||||
@@ -210,10 +217,11 @@ pub async fn start(canvas_id: String) -> Result<(), JsValue> {
|
||||
}
|
||||
install_hooks(&mut app);
|
||||
// Viewer frames render in frame workers (`?frameworkers=N`, 0 or `?noworkers`:
|
||||
// on the page's thread).
|
||||
// on the page's thread), each on its own WebGPU device where the browser has
|
||||
// WebGPU in workers (`?nogpuworkers`: their CPU).
|
||||
let n = if query_flag("noworkers") { 0 } else { query_value("frameworkers").and_then(|v| v.parse().ok()).unwrap_or(2usize).min(8) };
|
||||
if n > 0 {
|
||||
app.frames.set_remote(Some(Arc::new(frames::WebFrames::start(n))));
|
||||
app.frames.set_remote(Some(Arc::new(frames::WebFrames::start(n, !query_flag("nogpuworkers")))));
|
||||
}
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
api::set_sender(tx);
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
//! The disk cache (Settings ▸ Disk ▸ Disk Cache) in the browser: viewer frames kept in the
|
||||
//! Origin Private File System between visits, with the size limit from the settings and
|
||||
//! least-recently-used eviction.
|
||||
//!
|
||||
//! - **Writes** happen in the frame workers: a render request carries the frame's disk-cache key
|
||||
//! (`effectcraft_engine::remote::FrameMsg::Render`), the worker posts the frame, then writes
|
||||
//! the sealed entry (`disk_cache::frame_entry`: LZ4, checksum) with a synchronous access
|
||||
//! handle into a temporary file moved into place (`js/host.js` `cacheWrite`), and reports
|
||||
//! `FrameReply::Stored`.
|
||||
//! - **The index** lives here, on the page ([`DiskIndex`], shared with the desktop's cache):
|
||||
//! rebuilt at startup from the folder listing (oldest files first), updated by the workers'
|
||||
//! `Stored` replies and by reads; eviction deletes the least recently used files.
|
||||
//! - **Reads** are asynchronous: a frame whose key is indexed is read and decoded here instead
|
||||
//! of rendering it (`crate::frames`); a damaged or missing file is a miss and is forgotten.
|
||||
//!
|
||||
//! Only frames are cached on disk in the browser (the desktop also keeps slow layer buffers):
|
||||
//! a layer lookup happens in the middle of a synchronous render, where the browser's file
|
||||
//! system can't be read.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use effectcraft_engine::render::disk_cache::{self, DiskIndex, Kind};
|
||||
use serde_json::{Value, json};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
#[wasm_bindgen(module = "/js/host.js")]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_name = cacheList)]
|
||||
fn cache_list() -> js_sys::Promise;
|
||||
#[wasm_bindgen(js_name = cacheRead)]
|
||||
fn cache_read(name: &str) -> js_sys::Promise;
|
||||
#[wasm_bindgen(js_name = cacheWrite)]
|
||||
pub(crate) fn cache_write(name: &str, bytes: js_sys::Uint8Array) -> js_sys::Promise;
|
||||
#[wasm_bindgen(js_name = cacheDelete)]
|
||||
fn cache_delete(names: js_sys::Array) -> js_sys::Promise;
|
||||
#[wasm_bindgen(js_name = cacheClear)]
|
||||
fn cache_clear() -> js_sys::Promise;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
index: DiskIndex,
|
||||
/// The folder was listed (lookups before then miss).
|
||||
loaded: bool,
|
||||
/// The Origin Private File System works here.
|
||||
available: bool,
|
||||
/// Settings ▸ Disk ▸ Enable Disk Cache.
|
||||
enabled: bool,
|
||||
max_bytes: u64,
|
||||
hits: u64,
|
||||
misses: u64,
|
||||
writes: u64,
|
||||
evictions: u64,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ST: RefCell<State> = RefCell::new(State { enabled: true, max_bytes: 1 << 30, ..Default::default() });
|
||||
}
|
||||
|
||||
fn js_err(e: JsValue) -> String {
|
||||
e.as_string().or_else(|| js_sys::Reflect::get(&e, &"message".into()).ok().and_then(|m| m.as_string())).unwrap_or_else(|| format!("{e:?}"))
|
||||
}
|
||||
|
||||
/// List the cache folder and build the index (in the background).
|
||||
pub fn init() {
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
match JsFuture::from(cache_list()).await {
|
||||
Ok(list) => {
|
||||
let mut entries: Vec<(f64, u128, u64)> = js_sys::Array::from(&list)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let get = |k: &str| js_sys::Reflect::get(&e, &k.into()).ok();
|
||||
let key = disk_cache::parse_entry_name(&get("name")?.as_string()?)?;
|
||||
Some((get("modified")?.as_f64().unwrap_or(0.0), key, get("size")?.as_f64().unwrap_or(0.0) as u64))
|
||||
})
|
||||
.collect();
|
||||
entries.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
for (_, key, bytes) in entries {
|
||||
s.index.insert(Kind::Frame, key, bytes);
|
||||
}
|
||||
s.loaded = true;
|
||||
s.available = true;
|
||||
});
|
||||
evict();
|
||||
}
|
||||
Err(e) => {
|
||||
let e = js_err(e);
|
||||
log::info!("disk cache unavailable: {e}");
|
||||
ST.with(|s| s.borrow_mut().error = Some(e));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply the settings: on/off and the limit (`max_gb`, at most half the origin's quota when it
|
||||
/// is known).
|
||||
pub fn configure(enabled: bool, max_gb: u32, quota: Option<u64>) {
|
||||
let mut max = (max_gb.max(1) as u64) << 30;
|
||||
if let Some(q) = quota.filter(|q| *q > 0) {
|
||||
max = max.min(q / 2);
|
||||
}
|
||||
let changed = ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
let changed = s.enabled != enabled || s.max_bytes != max;
|
||||
s.enabled = enabled;
|
||||
s.max_bytes = max;
|
||||
changed
|
||||
});
|
||||
if changed {
|
||||
evict();
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache is usable: listed, available and enabled.
|
||||
pub fn active() -> bool {
|
||||
ST.with(|s| {
|
||||
let s = s.borrow();
|
||||
s.loaded && s.available && s.enabled
|
||||
})
|
||||
}
|
||||
|
||||
/// The frame of `key` is cached.
|
||||
pub fn contains(key: u128) -> bool {
|
||||
active() && ST.with(|s| s.borrow().index.contains(Kind::Frame, key))
|
||||
}
|
||||
|
||||
/// A lookup missed (counted for the statistics).
|
||||
pub fn note_miss() {
|
||||
ST.with(|s| s.borrow_mut().misses += 1);
|
||||
}
|
||||
|
||||
/// Read and decode a cached frame; `None` (forgotten and deleted) when the file is missing or
|
||||
/// damaged.
|
||||
pub async fn read(key: u128) -> Option<disk_cache::Frame8> {
|
||||
let name = disk_cache::entry_name(key);
|
||||
let bytes = JsFuture::from(cache_read(&name)).await.ok().and_then(|b| b.dyn_into::<js_sys::Uint8Array>().ok()).map(|b| b.to_vec());
|
||||
let frame = bytes.as_deref().and_then(disk_cache::read_frame_entry);
|
||||
ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
if frame.is_some() {
|
||||
s.hits += 1;
|
||||
s.index.touch(Kind::Frame, key);
|
||||
} else {
|
||||
s.misses += 1;
|
||||
s.index.remove(Kind::Frame, key);
|
||||
}
|
||||
});
|
||||
if frame.is_none() && bytes.is_some() {
|
||||
delete(vec![name]);
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
/// A worker stored the frame of `key` (`bytes` on disk).
|
||||
pub fn stored(key: u128, bytes: u64) {
|
||||
ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
s.index.insert(Kind::Frame, key, bytes);
|
||||
s.writes += 1;
|
||||
});
|
||||
evict();
|
||||
}
|
||||
|
||||
fn evict() {
|
||||
let victims = ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
let max = if s.enabled { s.max_bytes } else { u64::MAX };
|
||||
let v = s.index.evict(max);
|
||||
s.evictions += v.len() as u64;
|
||||
v
|
||||
});
|
||||
if !victims.is_empty() {
|
||||
delete(victims.into_iter().map(|(_, k)| disk_cache::entry_name(k)).collect());
|
||||
}
|
||||
}
|
||||
|
||||
fn delete(names: Vec<String>) {
|
||||
let arr = js_sys::Array::new();
|
||||
for n in names {
|
||||
arr.push(&JsValue::from_str(&n));
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let _ = JsFuture::from(cache_delete(arr)).await;
|
||||
});
|
||||
}
|
||||
|
||||
/// Delete every cached frame; returns (entries, bytes) removed.
|
||||
pub fn clear() -> (u64, u64) {
|
||||
let r = ST.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
let r = (s.index.len() as u64, s.index.total());
|
||||
s.index.clear();
|
||||
r
|
||||
});
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
if let Err(e) = JsFuture::from(cache_clear()).await {
|
||||
log::warn!("disk cache: clearing failed: {}", js_err(e));
|
||||
}
|
||||
});
|
||||
r
|
||||
}
|
||||
|
||||
/// `cache.diskStats` / `storage.info().diskCache`.
|
||||
pub fn stats() -> Value {
|
||||
ST.with(|s| {
|
||||
let s = s.borrow();
|
||||
json!({
|
||||
"enabled": s.enabled && s.available,
|
||||
"available": s.available,
|
||||
"loaded": s.loaded,
|
||||
"folder": "Origin Private File System: effectcraft-cache/v1/frames",
|
||||
"entries": s.index.len(),
|
||||
"frames": s.index.len(),
|
||||
"layers": 0,
|
||||
"bytes": s.index.total(),
|
||||
"maxBytes": s.max_bytes,
|
||||
"hits": s.hits,
|
||||
"misses": s.misses,
|
||||
"writes": s.writes,
|
||||
"evictions": s.evictions,
|
||||
"error": s.error,
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -6,27 +6,39 @@
|
||||
//! time, then diffs: [`Mirror`]); the frame comes back as premultiplied RGBA8 in a transferred
|
||||
//! buffer. One frame per worker at a time, so the page always decides what renders next (the
|
||||
//! viewer's frame before prefetch). A worker that fails is dropped; with none left, frames render
|
||||
//! on the page's thread again (`Frames::pump`).
|
||||
//! on the page's thread again (`Frames::pump`). With the disk cache on, a frame whose key is
|
||||
//! cached is read from the Origin Private File System instead ([`crate::diskcache`]); the
|
||||
//! others are stored there by the worker that renders them.
|
||||
//!
|
||||
//! **Worker side** — [`worker_frame`]: the worker's [`FrameServer`] (footage from the worker's
|
||||
//! media pool, expressions) handles each message and posts its replies.
|
||||
//! **Worker side** — [`worker_frame_init`] / [`worker_frame`]: the worker's [`FrameServer`]
|
||||
//! (footage from the worker's media pool, expressions) handles each message and posts its
|
||||
//! replies. Where the browser has WebGPU in workers, the worker opens its own device
|
||||
//! ([`Gpu::request_deferred`]) and renders GPU effects and the GPU compositor on it: a frame
|
||||
//! takes several passes, awaiting the device's readbacks in between (they can't be waited for
|
||||
//! synchronously, even in a worker), and Backend Auto picks CPU or GPU per comp from measured
|
||||
//! frame times. Without WebGPU, frames render on the worker's CPU.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_engine::offload::footage_files;
|
||||
use effectcraft_engine::remote::{FrameMsg, FrameReply, FrameServer, Mirror};
|
||||
use effectcraft_gpu::Gpu;
|
||||
use effectcraft_ui_egui::frames::{RemoteDone, RemoteFrame, RemoteFrames, RemoteJob};
|
||||
use serde_json::{Value, json};
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
#[wasm_bindgen(module = "/js/host.js")]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_name = frameWorkerStart)]
|
||||
fn frame_worker_start(base: &str, on_message: &js_sys::Function) -> u32;
|
||||
fn frame_worker_start(base: &str, on_message: &js_sys::Function, gpu: bool) -> u32;
|
||||
#[wasm_bindgen(js_name = frameWorkerPost)]
|
||||
fn frame_worker_post(index: u32, msg: &JsValue, transfer: &js_sys::Array);
|
||||
#[wasm_bindgen(js_name = hasWebGpu)]
|
||||
fn has_web_gpu() -> bool;
|
||||
}
|
||||
|
||||
/// One frame worker as the page sees it.
|
||||
@@ -36,6 +48,8 @@ struct Fw {
|
||||
files: HashSet<String>,
|
||||
busy: Option<(u64, RemoteDone)>,
|
||||
alive: bool,
|
||||
/// Its GPU adapter (after it reported), or why it has none.
|
||||
gpu: Option<Result<String, String>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -48,6 +62,11 @@ struct State {
|
||||
/// Bytes of project sync messages sent (diffs keep this small).
|
||||
sync_bytes: u64,
|
||||
syncs: u64,
|
||||
/// Frames rendered through a worker's GPU, and the passes of the last one.
|
||||
gpu_frames: u64,
|
||||
last_passes: u32,
|
||||
/// Frames served from the disk cache.
|
||||
disk_hits: u64,
|
||||
}
|
||||
|
||||
type OnMessage = Closure<dyn FnMut(u32, JsValue, JsValue, JsValue)>;
|
||||
@@ -57,6 +76,8 @@ thread_local! {
|
||||
static HANDLER: RefCell<Option<OnMessage>> = const { RefCell::new(None) };
|
||||
/// The worker's frame server (worker side).
|
||||
static SERVER: RefCell<Option<FrameServer>> = const { RefCell::new(None) };
|
||||
/// The worker's GPU device (worker side).
|
||||
static GPU: RefCell<Option<Gpu>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
fn obj(pairs: &[(&str, JsValue)]) -> JsValue {
|
||||
@@ -71,31 +92,22 @@ fn obj(pairs: &[(&str, JsValue)]) -> JsValue {
|
||||
pub struct WebFrames;
|
||||
|
||||
impl WebFrames {
|
||||
/// Start `n` frame workers.
|
||||
pub fn start(n: usize) -> WebFrames {
|
||||
/// Start `n` frame workers; `gpu`: each opens its own WebGPU device where it can.
|
||||
pub fn start(n: usize, gpu: bool) -> WebFrames {
|
||||
let on: OnMessage = Closure::new(|index: u32, json: JsValue, bytes: JsValue, error: JsValue| on_message(index, json, bytes, error));
|
||||
STATE.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
for _ in 0..n {
|
||||
let index = frame_worker_start(&crate::page_url(""), on.as_ref().unchecked_ref());
|
||||
s.workers.push(Fw { index, mirror: Mirror::default(), files: HashSet::new(), busy: None, alive: true });
|
||||
let index = frame_worker_start(&crate::page_url(""), on.as_ref().unchecked_ref(), gpu);
|
||||
s.workers.push(Fw { index, mirror: Mirror::default(), files: HashSet::new(), busy: None, alive: true, gpu: None });
|
||||
}
|
||||
});
|
||||
HANDLER.with(|h| *h.borrow_mut() = Some(on));
|
||||
WebFrames
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteFrames for WebFrames {
|
||||
fn slots(&self) -> usize {
|
||||
STATE.with(|s| s.borrow().workers.iter().filter(|w| w.alive).count())
|
||||
}
|
||||
|
||||
fn purge(&self) {
|
||||
purge();
|
||||
}
|
||||
|
||||
fn start(&self, job: RemoteJob, done: RemoteDone) {
|
||||
/// Send `job` to an idle worker.
|
||||
fn render(&self, job: RemoteJob, done: RemoteDone) {
|
||||
let r = STATE.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
s.next_id += 1;
|
||||
@@ -121,7 +133,8 @@ impl RemoteFrames for WebFrames {
|
||||
sent = t.len() as u64;
|
||||
frame_worker_post(index, &obj(&[("type", "frame".into()), ("json", t.into())]), &js_sys::Array::new());
|
||||
}
|
||||
let req = FrameMsg::Render { id, revision: job.revision, comp: job.comp, time: job.t, opts: Box::new(job.opts) };
|
||||
let disk = job.disk_key.map(|k| format!("{k:032x}"));
|
||||
let req = FrameMsg::Render { id, revision: job.revision, comp: job.comp, time: job.t, opts: Box::new(job.opts), disk };
|
||||
frame_worker_post(
|
||||
index,
|
||||
&obj(&[("type", "frame".into()), ("json", serde_json::to_string(&req).unwrap_or_default().into())]),
|
||||
@@ -140,6 +153,49 @@ impl RemoteFrames for WebFrames {
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteFrames for WebFrames {
|
||||
fn slots(&self) -> usize {
|
||||
STATE.with(|s| s.borrow().workers.iter().filter(|w| w.alive).count())
|
||||
}
|
||||
|
||||
fn purge(&self) {
|
||||
purge();
|
||||
}
|
||||
|
||||
fn gpu(&self) -> bool {
|
||||
STATE.with(|s| s.borrow().workers.iter().any(|w| w.alive && matches!(w.gpu, Some(Ok(_)))))
|
||||
}
|
||||
|
||||
fn disk(&self) -> bool {
|
||||
crate::diskcache::active()
|
||||
}
|
||||
|
||||
fn disk_contains(&self, key: u128) -> bool {
|
||||
crate::diskcache::contains(key)
|
||||
}
|
||||
|
||||
fn start(&self, job: RemoteJob, done: RemoteDone) {
|
||||
// A frame in the disk cache is read, not rendered (a failed read renders it).
|
||||
if let Some(k) = job.disk_key {
|
||||
if crate::diskcache::contains(k) {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match crate::diskcache::read(k).await {
|
||||
Some(f) => {
|
||||
STATE.with(|s| s.borrow_mut().disk_hits += 1);
|
||||
done(Ok(RemoteFrame { width: f.width, height: f.height, rgba: f.rgba, ms: 0.0 }));
|
||||
}
|
||||
None => WebFrames.render(job, done),
|
||||
}
|
||||
crate::repaint();
|
||||
});
|
||||
return;
|
||||
}
|
||||
crate::diskcache::note_miss();
|
||||
}
|
||||
self.render(job, done);
|
||||
}
|
||||
}
|
||||
|
||||
/// A message from frame worker `index`: a JSON [`FrameReply`] (with the pixels in `bytes`), or
|
||||
/// `error` when the worker died.
|
||||
fn on_message(index: u32, json: JsValue, bytes: JsValue, error: JsValue) {
|
||||
@@ -154,11 +210,15 @@ fn on_message(index: u32, json: JsValue, bytes: JsValue, error: JsValue) {
|
||||
}
|
||||
let reply: FrameReply = serde_json::from_str(&json.as_string()?).ok()?;
|
||||
match reply {
|
||||
FrameReply::Frame { id, width, height, ms } => {
|
||||
FrameReply::Frame { id, width, height, ms, passes, gpu } => {
|
||||
let (_, d) = w.busy.take_if(|b| b.0 == id)?;
|
||||
let rgba = bytes.dyn_into::<js_sys::Uint8Array>().map(|b| b.to_vec()).unwrap_or_default();
|
||||
st.rendered += 1;
|
||||
st.last_ms = ms;
|
||||
if gpu {
|
||||
st.gpu_frames += 1;
|
||||
st.last_passes = passes;
|
||||
}
|
||||
Some((d, Ok(RemoteFrame { width, height, rgba, ms })))
|
||||
}
|
||||
FrameReply::Failed { id, error, .. } => {
|
||||
@@ -171,6 +231,20 @@ fn on_message(index: u32, json: JsValue, bytes: JsValue, error: JsValue) {
|
||||
w.mirror.reset();
|
||||
None
|
||||
}
|
||||
FrameReply::Stored { key, bytes } => {
|
||||
if let Ok(k) = u128::from_str_radix(&key, 16) {
|
||||
crate::diskcache::stored(k, bytes);
|
||||
}
|
||||
None
|
||||
}
|
||||
FrameReply::Info { gpu, error } => {
|
||||
match (&gpu, &error) {
|
||||
(Some(g), _) => log::info!("frame worker {index}: GPU {g}"),
|
||||
(None, e) => log::info!("frame worker {index}: CPU only ({})", e.as_deref().unwrap_or("no GPU")),
|
||||
}
|
||||
w.gpu = Some(gpu.ok_or_else(|| error.unwrap_or_default()));
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some((d, r)) = done {
|
||||
@@ -207,6 +281,15 @@ pub fn purge() {
|
||||
pub fn stats() -> Value {
|
||||
STATE.with(|s| {
|
||||
let s = s.borrow();
|
||||
let gpu: Vec<Value> = s
|
||||
.workers
|
||||
.iter()
|
||||
.map(|w| match &w.gpu {
|
||||
Some(Ok(name)) => json!(name),
|
||||
Some(Err(e)) => json!({"cpu": e}),
|
||||
None => Value::Null,
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"workers": s.workers.len(),
|
||||
"alive": s.workers.iter().filter(|w| w.alive).count(),
|
||||
@@ -216,16 +299,150 @@ pub fn stats() -> Value {
|
||||
"lastMs": s.last_ms,
|
||||
"syncs": s.syncs,
|
||||
"syncBytes": s.sync_bytes,
|
||||
"gpu": gpu,
|
||||
"gpuFrames": s.gpu_frames,
|
||||
"lastPasses": s.last_passes,
|
||||
"diskHits": s.disk_hits,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// `workerFrameCheck` promises waiting for their frame: id → (resolve, reject, local frame).
|
||||
#[allow(clippy::type_complexity)]
|
||||
static CHECKS: RefCell<std::collections::HashMap<u64, (js_sys::Function, js_sys::Function, (u32, u32, Vec<u8>), f64)>> = RefCell::new(Default::default());
|
||||
}
|
||||
|
||||
/// `effectcraft.workerFrameCheck({time?, scale?, backend?})`: render the active comp's frame in
|
||||
/// a frame worker (backend `gpu` by default: the worker's WebGPU device) and on the page's CPU
|
||||
/// with the same render options, and compare them. Resolves with `{width, height, maxDiff,
|
||||
/// meanDiff, over4, workerMs, gpuFrames}` (differences in 8-bit levels; `over4`: the fraction
|
||||
/// of channels more than 4 levels apart). Rejects when no worker is idle (try again).
|
||||
#[wasm_bindgen(js_name = workerFrameCheck)]
|
||||
pub fn worker_frame_check(params: JsValue) -> js_sys::Promise {
|
||||
let get = |k: &str| js_sys::Reflect::get(¶ms, &k.into()).ok().filter(|v| !v.is_undefined());
|
||||
let time = get("time").and_then(|v| v.as_f64());
|
||||
let scale = get("scale").and_then(|v| v.as_f64()).unwrap_or(0.5);
|
||||
let backend = get("backend").and_then(|v| v.as_string()).unwrap_or_else(|| "gpu".into());
|
||||
js_sys::Promise::new(&mut |resolve, reject| {
|
||||
let backend = backend.clone();
|
||||
crate::post(move |app| {
|
||||
let s = &app.session;
|
||||
let Some(comp) = s.active_comp_id() else {
|
||||
let _ = reject.call1(&JsValue::NULL, &"no active composition".into());
|
||||
return;
|
||||
};
|
||||
let t = time.map(effectcraft_engine::time::Tick::from_seconds_f64).unwrap_or_else(|| s.time());
|
||||
let mut opts = app.frame_opts(comp, scale);
|
||||
opts.backend = match backend.as_str() {
|
||||
"cpu" => effectcraft_engine::render::Backend::Cpu,
|
||||
"auto" => effectcraft_engine::render::Backend::Auto,
|
||||
_ => effectcraft_engine::render::Backend::Gpu,
|
||||
};
|
||||
let local = {
|
||||
let mut r = effectcraft_engine::render::Renderer::new(
|
||||
&s.project,
|
||||
s.footage.as_ref(),
|
||||
effectcraft_engine::render::RenderOpts { backend: effectcraft_engine::render::Backend::Cpu, ..opts },
|
||||
);
|
||||
r.expr = s.expr.as_deref();
|
||||
let img = r.comp_frame(comp, t);
|
||||
(img.width, img.height, effectcraft_engine::remote::rgba8_premultiplied(&img))
|
||||
};
|
||||
let id = STATE.with(|st| {
|
||||
let mut st = st.borrow_mut();
|
||||
st.next_id += 1;
|
||||
st.next_id
|
||||
});
|
||||
CHECKS.with(|c| c.borrow_mut().insert(id, (resolve.clone(), reject.clone(), local, js_sys::Date::now())));
|
||||
let job = RemoteJob { project: s.project.clone(), revision: s.revision, comp, t, opts, disk_key: None };
|
||||
WebFrames.render(
|
||||
job,
|
||||
Box::new(move |r: Result<RemoteFrame, String>| {
|
||||
let Some((resolve, reject, (w, h, want), t0)) = CHECKS.with(|c| c.borrow_mut().remove(&id)) else { return };
|
||||
match r {
|
||||
Ok(f) if (f.width, f.height) == (w, h) && f.rgba.len() == want.len() => {
|
||||
let (mut max, mut sum, mut over) = (0u32, 0u64, 0u64);
|
||||
for (a, b) in f.rgba.iter().zip(&want) {
|
||||
let d = (*a as i32 - *b as i32).unsigned_abs();
|
||||
max = max.max(d);
|
||||
sum += d as u64;
|
||||
over += (d > 4) as u64;
|
||||
}
|
||||
let n = want.len().max(1) as f64;
|
||||
let c = ((h / 2 * w + w / 2) * 4) as usize;
|
||||
let v = json!({"width": w, "height": h, "maxDiff": max, "meanDiff": sum as f64 / n, "over4": over as f64 / n,
|
||||
"workerMs": f.ms, "wallMs": js_sys::Date::now() - t0, "gpuFrames": stats()["gpuFrames"],
|
||||
"center": [&f.rgba[c..c + 4], &want[c..c + 4]]});
|
||||
let _ = resolve.call1(&JsValue::NULL, &JsValue::from_str(&v.to_string()));
|
||||
}
|
||||
Ok(f) => {
|
||||
let _ = reject.call1(&JsValue::NULL, &format!("size {}x{} vs {w}x{h}", f.width, f.height).into());
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reject.call1(&JsValue::NULL, &e.into());
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- worker side
|
||||
|
||||
/// Handle one frame message (a JSON [`FrameMsg`]) in a frame worker; replies are posted with
|
||||
/// their pixels transferred.
|
||||
fn post_reply(r: &FrameReply, px: Option<&[u8]>) {
|
||||
let scope: web_sys::DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let t = serde_json::to_string(r).unwrap_or_default();
|
||||
let res = match px {
|
||||
Some(px) => {
|
||||
let buf = js_sys::Uint8Array::from(px).buffer();
|
||||
scope.post_message_with_transfer(
|
||||
&obj(&[("type", "frameReply".into()), ("json", t.into()), ("bytes", buf.clone().into())]),
|
||||
&js_sys::Array::of1(&buf),
|
||||
)
|
||||
}
|
||||
None => scope.post_message(&obj(&[("type", "frameReply".into()), ("json", t.into())])),
|
||||
};
|
||||
if let Err(e) = res {
|
||||
log::warn!("frame worker: postMessage: {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn new_server() -> FrameServer {
|
||||
FrameServer::new(crate::worker::pool(), Some(Arc::new(effectcraft_expr::Expressions)))
|
||||
}
|
||||
|
||||
/// Set up a frame worker (called once by `web/worker.js` after `workerInit`): its frame
|
||||
/// server and, with `gpu` and WebGPU in workers, its own GPU device. Reports
|
||||
/// [`FrameReply::Info`].
|
||||
#[wasm_bindgen(js_name = workerFrameInit)]
|
||||
pub async fn worker_frame_init(gpu: bool) {
|
||||
let mut server = new_server();
|
||||
let info = if !gpu {
|
||||
FrameReply::Info { gpu: None, error: Some("GPU frame workers are off (?nogpuworkers)".into()) }
|
||||
} else if !has_web_gpu() {
|
||||
FrameReply::Info { gpu: None, error: Some("no WebGPU in workers".into()) }
|
||||
} else {
|
||||
match Gpu::request_deferred().await {
|
||||
Ok(g) => {
|
||||
let name = effectcraft_engine::render::Accelerator::name(&g);
|
||||
server.set_accel(Some(Arc::new(g.clone())));
|
||||
GPU.with(|c| *c.borrow_mut() = Some(g));
|
||||
FrameReply::Info { gpu: Some(name), error: None }
|
||||
}
|
||||
Err(e) => FrameReply::Info { gpu: None, error: Some(e) },
|
||||
}
|
||||
};
|
||||
SERVER.with(|c| *c.borrow_mut() = Some(server));
|
||||
post_reply(&info, None);
|
||||
}
|
||||
|
||||
/// Handle one frame message (a JSON [`FrameMsg`]) in a frame worker: replies are posted with
|
||||
/// their pixels transferred. A frame rendering in passes awaits the GPU between them; a frame
|
||||
/// with a disk-cache key is then stored ([`FrameReply::Stored`]).
|
||||
#[wasm_bindgen(js_name = workerFrame)]
|
||||
pub fn worker_frame(json: String) {
|
||||
pub async fn worker_frame(json: String) {
|
||||
let msg: FrameMsg = match serde_json::from_str(&json) {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
@@ -233,29 +450,25 @@ pub fn worker_frame(json: String) {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let replies = SERVER.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
let server = c.get_or_insert_with(|| {
|
||||
let pool = crate::worker::pool();
|
||||
FrameServer::new(pool, Some(std::sync::Arc::new(effectcraft_expr::Expressions)))
|
||||
});
|
||||
server.handle(msg)
|
||||
});
|
||||
let scope: web_sys::DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let disk = match &msg {
|
||||
FrameMsg::Render { disk, .. } => disk.clone(),
|
||||
_ => None,
|
||||
};
|
||||
let mut replies = SERVER.with(|c| c.borrow_mut().get_or_insert_with(new_server).handle(msg));
|
||||
while SERVER.with(|c| c.borrow().as_ref().is_some_and(|s| s.waiting())) {
|
||||
let Some(g) = GPU.with(|c| c.borrow().clone()) else { break };
|
||||
g.settled().await;
|
||||
replies = SERVER.with(|c| c.borrow_mut().as_mut().map(|s| s.resume()).unwrap_or_default());
|
||||
}
|
||||
for (r, px) in replies {
|
||||
let t = serde_json::to_string(&r).unwrap_or_default();
|
||||
let res = match px {
|
||||
Some(px) => {
|
||||
let buf = js_sys::Uint8Array::from(&px[..]).buffer();
|
||||
scope.post_message_with_transfer(
|
||||
&obj(&[("type", "frameReply".into()), ("json", t.into()), ("bytes", buf.clone().into())]),
|
||||
&js_sys::Array::of1(&buf),
|
||||
)
|
||||
post_reply(&r, px.as_deref());
|
||||
if let (FrameReply::Frame { width, height, .. }, Some(px), Some(key)) = (&r, &px, &disk) {
|
||||
let entry = effectcraft_engine::render::disk_cache::frame_entry(*width, *height, px);
|
||||
let name = format!("{key}.ecc");
|
||||
match JsFuture::from(crate::diskcache::cache_write(&name, js_sys::Uint8Array::from(&entry[..]))).await {
|
||||
Ok(n) => post_reply(&FrameReply::Stored { key: key.clone(), bytes: n.as_f64().unwrap_or(entry.len() as f64) as u64 }, None),
|
||||
Err(e) => log::warn!("frame worker: disk cache write failed: {e:?}"),
|
||||
}
|
||||
None => scope.post_message(&obj(&[("type", "frameReply".into()), ("json", t.into())])),
|
||||
};
|
||||
if let Err(e) = res {
|
||||
log::warn!("frame worker: postMessage: {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
//! | rfd file dialogs | `<input type=file>` pickers; drop files on the page |
|
||||
//! | Media Browser on the file system | browser storage and folders opened with the File System Access API ([`browse`]) |
|
||||
//! | written files (Save, Render Queue) | browser downloads (several render files as one `.zip`) |
|
||||
//! | frame render threads | frame workers, each with a project replica fed by diffs ([`frames`]); `Frames::pump` on the UI thread without workers |
|
||||
//! | frame render threads | frame workers, each with a project replica fed by diffs and its own WebGPU device ([`frames`]); `Frames::pump` on the UI thread without workers |
|
||||
//! | disk cache folder | frames in the Origin Private File System, written by the frame workers ([`diskcache`]) |
|
||||
//! | (none) | the storage manager: usage, quota, persistence, clearing ([`storage`]) |
|
||||
//! | Render Queue / analysis threads | Web Workers running their own engine instance ([`worker`]) |
|
||||
//! | cpal audio output | Web Audio: an AudioWorklet fed from the preview mixdown ([`audio`]) |
|
||||
//! | TCP control channel / MCP | `window.effectcraft` JavaScript API ([`api`]) |
|
||||
@@ -29,12 +31,16 @@ pub mod audio;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod browse;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod diskcache;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod files;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod frames;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod persist;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod storage;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod worker;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The storage manager ([`StorageHost`], `storage.*` commands, Settings ▸ Disk ▸ Browser
|
||||
//! Storage): the origin's usage and quota (`navigator.storage.estimate()`), persistent storage
|
||||
//! (`navigator.storage.persist()`), what the store holds by kind ([`crate::store::FileKind`])
|
||||
//! and the disk cache ([`crate::diskcache`]); clearing each.
|
||||
//!
|
||||
//! The browser answers asynchronously: [`StorageHost::info`] returns the latest estimate and
|
||||
//! asks for a new one at most once a second.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use effectcraft_engine::storage::StorageHost;
|
||||
use serde_json::{Value, json};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use crate::store::FileKind;
|
||||
|
||||
#[wasm_bindgen(module = "/js/host.js")]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_name = storePersist)]
|
||||
fn store_persist() -> js_sys::Promise;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Estimate {
|
||||
usage: u64,
|
||||
quota: u64,
|
||||
persisted: bool,
|
||||
/// When the last refresh started (ms).
|
||||
asked: f64,
|
||||
busy: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static EST: RefCell<Estimate> = RefCell::new(Estimate::default());
|
||||
}
|
||||
|
||||
/// Refresh the estimate in the background (at most once a second).
|
||||
pub fn refresh() {
|
||||
let now = js_sys::Date::now();
|
||||
let go = EST.with(|e| {
|
||||
let mut e = e.borrow_mut();
|
||||
if e.busy || now - e.asked < 1000.0 {
|
||||
return false;
|
||||
}
|
||||
e.busy = true;
|
||||
e.asked = now;
|
||||
true
|
||||
});
|
||||
if !go {
|
||||
return;
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
let v = JsFuture::from(crate::persist::store_estimate()).await.ok();
|
||||
EST.with(|e| {
|
||||
let mut e = e.borrow_mut();
|
||||
e.busy = false;
|
||||
if let Some(v) = v {
|
||||
let get = |k: &str| js_sys::Reflect::get(&v, &k.into()).ok();
|
||||
e.usage = get("usage").and_then(|x| x.as_f64()).unwrap_or(0.0) as u64;
|
||||
e.quota = get("quota").and_then(|x| x.as_f64()).unwrap_or(0.0) as u64;
|
||||
e.persisted = get("persisted").and_then(|x| x.as_bool()).unwrap_or(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The origin's quota in bytes, when known.
|
||||
pub fn quota() -> Option<u64> {
|
||||
EST.with(|e| Some(e.borrow().quota).filter(|q| *q > 0))
|
||||
}
|
||||
|
||||
/// The web app's [`StorageHost`].
|
||||
pub struct WebStorage;
|
||||
|
||||
impl StorageHost for WebStorage {
|
||||
fn info(&self) -> Value {
|
||||
refresh();
|
||||
let (usage, quota, persisted) = EST.with(|e| {
|
||||
let e = e.borrow();
|
||||
(e.usage, e.quota, e.persisted)
|
||||
});
|
||||
json!({
|
||||
"backend": crate::persist::backend(),
|
||||
"usage": usage,
|
||||
"quota": quota,
|
||||
"persisted": persisted,
|
||||
"files": crate::files::STORE.usage(),
|
||||
"diskCache": crate::diskcache::stats(),
|
||||
"error": crate::persist::last_error(),
|
||||
})
|
||||
}
|
||||
|
||||
fn request_persist(&self) -> Value {
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
let granted = JsFuture::from(store_persist()).await.ok().and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
EST.with(|e| e.borrow_mut().persisted = granted);
|
||||
crate::repaint();
|
||||
});
|
||||
json!({"requested": true, "persisted": EST.with(|e| e.borrow().persisted)})
|
||||
}
|
||||
|
||||
fn clear(&self, what: &str) -> Result<Value, String> {
|
||||
let kinds: Vec<FileKind> = match what {
|
||||
"diskCache" => vec![],
|
||||
"all" => vec![FileKind::Media, FileKind::Project, FileKind::AutoSave],
|
||||
k => vec![FileKind::from_name(k).ok_or_else(|| format!("unknown storage kind {k}"))?],
|
||||
};
|
||||
let (mut entries, mut bytes) = (0u64, 0u64);
|
||||
if matches!(what, "diskCache" | "all") {
|
||||
let (n, b) = crate::diskcache::clear();
|
||||
entries += n;
|
||||
bytes += b;
|
||||
}
|
||||
for k in kinds {
|
||||
let (n, b) = crate::files::STORE.clear_kind(k);
|
||||
entries += n;
|
||||
bytes += b;
|
||||
}
|
||||
// The estimate catches up on the next refresh.
|
||||
EST.with(|e| e.borrow_mut().asked = 0.0);
|
||||
Ok(json!({"cleared": what, "entries": entries, "bytes": bytes}))
|
||||
}
|
||||
}
|
||||
@@ -182,6 +182,74 @@ impl Store {
|
||||
pub fn files(&self) -> Vec<(String, usize, f64, bool)> {
|
||||
self.lock().list(FILES).into_iter().filter_map(|(k, n, m, p)| Some((key_path(&k)?.to_string(), n, m, p))).collect()
|
||||
}
|
||||
|
||||
/// Stored (persisted) files by kind: `{projects, media, autoSaves}`, each `{count, bytes}`
|
||||
/// (the storage manager, `storage.info`).
|
||||
pub fn usage(&self) -> serde_json::Value {
|
||||
let mut out = serde_json::Map::new();
|
||||
for k in [FileKind::Project, FileKind::Media, FileKind::AutoSave] {
|
||||
let (mut count, mut bytes) = (0u64, 0u64);
|
||||
for (path, n, _, persisted) in self.files() {
|
||||
if persisted && FileKind::of(&path) == k {
|
||||
count += 1;
|
||||
bytes += n as u64;
|
||||
}
|
||||
}
|
||||
out.insert(k.name().into(), serde_json::json!({"count": count, "bytes": bytes}));
|
||||
}
|
||||
out.into()
|
||||
}
|
||||
|
||||
/// Delete every stored file of a kind; returns (files, bytes) removed.
|
||||
pub fn clear_kind(&self, kind: FileKind) -> (u64, u64) {
|
||||
let (mut count, mut bytes) = (0u64, 0u64);
|
||||
for (path, n, _, persisted) in self.files() {
|
||||
if persisted && FileKind::of(&path) == kind {
|
||||
self.lock().remove(&file_key(&path));
|
||||
count += 1;
|
||||
bytes += n as u64;
|
||||
}
|
||||
}
|
||||
if count > 0 {
|
||||
self.changed();
|
||||
}
|
||||
(count, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a stored file is (Settings ▸ Disk ▸ Browser Storage).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FileKind {
|
||||
/// A saved project (`.ecproj` outside the auto-save folder).
|
||||
Project,
|
||||
/// Imported footage and everything else.
|
||||
Media,
|
||||
/// Auto-saves (`/EffectCraft Auto-Save/…`, or `… auto-save N.ecproj`).
|
||||
AutoSave,
|
||||
}
|
||||
|
||||
impl FileKind {
|
||||
pub fn of(path: &str) -> FileKind {
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if !lower.ends_with(".ecproj") {
|
||||
return FileKind::Media;
|
||||
}
|
||||
let name = lower.rsplit('/').next().unwrap_or(&lower);
|
||||
if lower.contains("/effectcraft auto-save/") || name.contains(" auto-save ") { FileKind::AutoSave } else { FileKind::Project }
|
||||
}
|
||||
|
||||
/// `storage.clear` / `storage.info` name.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
FileKind::Project => "projects",
|
||||
FileKind::Media => "media",
|
||||
FileKind::AutoSave => "autoSaves",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_name(n: &str) -> Option<FileKind> {
|
||||
[FileKind::Project, FileKind::Media, FileKind::AutoSave].into_iter().find(|k| k.name() == n)
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings and friends ([`ConfigStore`]) in the store; auto-saves ([`FileOps`]) in its file
|
||||
@@ -289,6 +357,28 @@ mod tests {
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_by_kind_and_clearing() {
|
||||
let s = store();
|
||||
s.put_file("/a.ecproj", Arc::from(&b"proj"[..]), true);
|
||||
s.put_file("/clip.mp4", Arc::from(&b"0123456789"[..]), true);
|
||||
s.put_file("/still.png", Arc::from(&b"px"[..]), true);
|
||||
s.put_file("/EffectCraft Auto-Save/a auto-save 1.ecproj", Arc::from(&b"auto"[..]), true);
|
||||
s.put_file("/render.gif", Arc::from(&b"out"[..]), false);
|
||||
let u = s.usage();
|
||||
assert_eq!(u["projects"], serde_json::json!({"count": 1, "bytes": 4}));
|
||||
assert_eq!(u["media"], serde_json::json!({"count": 2, "bytes": 12}), "render outputs are not stored");
|
||||
assert_eq!(u["autoSaves"], serde_json::json!({"count": 1, "bytes": 4}));
|
||||
assert_eq!(FileKind::from_name("autoSaves"), Some(FileKind::AutoSave));
|
||||
assert_eq!(FileKind::of("/x/My auto-save 3.ecproj"), FileKind::AutoSave);
|
||||
s.lock().take_pending();
|
||||
assert_eq!(s.clear_kind(FileKind::Media), (2, 12));
|
||||
assert!(s.file("/clip.mp4").is_none() && s.file("/a.ecproj").is_some() && s.file("/render.gif").is_some());
|
||||
let deleted: Vec<String> = s.lock().take_pending().into_iter().filter(|p| p.data.is_none()).map(|p| p.key).collect();
|
||||
assert_eq!(deleted.len(), 2, "the deletions are flushed to browser storage");
|
||||
assert_eq!(s.usage()["media"]["count"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_coalesce_per_key_in_order() {
|
||||
let mut m = Mirror::default();
|
||||
|
||||
Reference in New Issue
Block a user