diff --git a/examples/web-chat/Cargo.toml b/examples/web-chat/Cargo.toml index 00ce2e3..efe274b 100644 --- a/examples/web-chat/Cargo.toml +++ b/examples/web-chat/Cargo.toml @@ -11,13 +11,20 @@ publish = false crate-type = ["cdylib"] [dependencies] -ed-agent = { path = "../../crates/ed-agent" } -# Used only for web_store::download_model; ed-agent does not re-export it. The -# browser engine and web_store arrived in onde 1.5.0. -onde = "1.5.0" +# The inference engine: GGUF loading, the Qwen2 forward pass and sampling. +vectoron = "0.2" +tokenizers = { version = "0.22", default-features = false, features = ["unstable_wasm"] } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" +web-sys = { version = "0.3", features = [ + "Cache", + "CacheStorage", + "Headers", + "ReadableStream", + "ReadableStreamDefaultReader", + "Response", +] } serde = { version = "1", features = ["derive"] } serde-wasm-bindgen = "0.6" console_error_panic_hook = "0.1" diff --git a/examples/web-chat/README.md b/examples/web-chat/README.md index 89ad943..c8a3c81 100644 --- a/examples/web-chat/README.md +++ b/examples/web-chat/README.md @@ -1,8 +1,9 @@ # web-chat Ed running a model entirely in the browser. The page talks to a Web Worker -that owns one `Ed` instance compiled to `wasm32-unknown-unknown`. Nothing you -type is sent to a server. +that owns one model, compiled to `wasm32-unknown-unknown`. Nothing you type is +sent to a server. Inference runs on [vectoron](https://github.com/setoelkahfi/vectoron): +it loads the GGUF file, runs the Qwen2 forward pass and samples tokens. ## Build and run @@ -16,12 +17,9 @@ python3 -m http.server -d www 8080 Open . No bundler, npm or special headers are needed. Cache Storage needs a secure context, which `localhost` counts as. -The browser engine comes from `onde` 1.5.0 on crates.io. To try a local `onde` -checkout instead, pass a patch through to cargo: - -```bash -./build.sh --config 'patch.crates-io.onde.path="../../../onde"' -``` +`vectoron` comes from its `feature/v1` branch as a git dependency (see +`Cargo.toml`). To build against a local checkout instead, change that line to +`vectoron = { path = "../../../onde-vectoron" }`. ## Deploy @@ -49,23 +47,29 @@ from disk without downloading again. **Remove model** in the footer deletes it. ## Phones and tablets -Loading the model peaks at about three times the file in memory (the cached -bytes, the copy handed to the engine, and the tensors built from it), so a bit -over 1 GB. Mobile browsers kill the tab before that. On phones and tablets the -page shows a warning instead of starting, with a link to Siti AI in the App -Store or Google Play (Onde in a native app) and a **Try anyway** button. The -same warning appears on any device whose previous visit was killed while the -model was loading. Lowering the peak is work for onde's `web_store`. +Loading copies the cached file into wasm memory once, and vectoron computes +with the quantized weights in place. The peak is therefore about twice the file +(the JS buffer plus the wasm copy) until the browser frees the JS buffer, so +roughly 800 MB. That figure comes from the code; it has not been profiled. The +earlier engine peaked at over 1 GB, and mobile browsers still kill the tab +around these sizes. On phones and tablets the page shows a warning instead of +starting, with a link to Siti AI in the App Store or Google Play (Onde in a +native app) and a **Try anyway** button. The same warning appears on any device +whose previous visit was killed while the model was loading. ## Speed -Inference is CPU only, single threaded, using WebAssembly SIMD. Expect one to three -tokens per second on a laptop (measured 1.2 to 2.5 on an Apple Silicon Mac). Stop ends the worker and starts a new one, so it -also resets the conversation. +Inference is CPU only, single threaded, using WebAssembly SIMD. On an Apple +Silicon Mac a reply ran at 3.9 to 5.1 tokens per second, counting the prompt. +A follow-up only runs the new part of the prompt, because the conversation's +earlier tokens stay in the model's cache. Stop ends the worker and starts a new +one, so it also resets the conversation. ## Layout -- `src/lib.rs`: the wasm-bindgen API (`WebChat`) around `Ed`. +- `src/lib.rs`: the wasm-bindgen API (`WebChat`). +- `src/chat.rs`: the conversation, its ChatML prompt and streaming generation. +- `src/store.rs`: downloads and caches the model and tokenizer in Cache Storage. - `www/worker.js`: owns the wasm module and the `WebChat`. - `www/main.js`, `index.html`, `style.css`: the UI. diff --git a/examples/web-chat/build.sh b/examples/web-chat/build.sh index 1efb82f..0882976 100755 --- a/examples/web-chat/build.sh +++ b/examples/web-chat/build.sh @@ -1,8 +1,7 @@ #!/usr/bin/env bash # Build the wasm package into www/pkg. Serve www/ with any static server: # python3 -m http.server -d www 8080 -# Extra arguments go to `cargo`, e.g. a local onde checkout: -# ./build.sh --config 'patch.crates-io.onde.path="../../../onde"' +# Extra arguments go to `cargo`, e.g. `./build.sh --offline`. set -euo pipefail cd "$(dirname "$0")" diff --git a/examples/web-chat/src/chat.rs b/examples/web-chat/src/chat.rs new file mode 100644 index 0000000..394695b --- /dev/null +++ b/examples/web-chat/src/chat.rs @@ -0,0 +1,200 @@ +//! A chat session over one vectoron model: the conversation, its ChatML +//! prompt, and streaming generation. + +use tokenizers::Tokenizer; +use vectoron::{Qwen2Model, Sampler, SamplerConfig}; +use wasm_bindgen::{JsCast, JsValue}; +use wasm_bindgen_futures::JsFuture; + +/// Prompt tokens run per forward pass. Between chunks the worker yields, so +/// a long prompt does not hold its event loop for seconds. +const PREFILL_CHUNK: usize = 64; +const MAX_TOKENS: usize = 512; + +#[derive(Clone, Copy)] +enum Role { + User, + Assistant, +} + +pub struct Chat { + model: Qwen2Model, + tokenizer: Tokenizer, + eos: Vec, + system: Option, + history: Vec<(Role, String)>, + /// The tokens whose keys and values are in the model's cache, so the + /// next turn only runs what changed. + cached: Vec, +} + +impl Chat { + pub fn new( + model: Qwen2Model, + tokenizer: Tokenizer, + system: Option, + ) -> Result { + let eos: Vec = ["<|im_end|>", "<|endoftext|>"] + .iter() + .filter_map(|t| tokenizer.token_to_id(t)) + .collect(); + if eos.is_empty() { + return Err("the tokenizer has no end-of-turn token".into()); + } + Ok(Self { + model, + tokenizer, + eos, + system, + history: Vec::new(), + cached: Vec::new(), + }) + } + + pub fn history_len(&self) -> usize { + self.history.len() + } + + /// Forgets the conversation. Returns how many messages were dropped. + pub fn reset(&mut self) -> usize { + let dropped = self.history.len(); + self.history.clear(); + self.cached.clear(); + self.model.clear_kv_cache(); + dropped + } + + /// The conversation as a ChatML prompt ending in an open assistant turn. + fn prompt(&self) -> String { + let mut out = String::new(); + let mut turn = |role: &str, content: &str| { + out.push_str("<|im_start|>"); + out.push_str(role); + out.push('\n'); + out.push_str(content); + out.push_str("<|im_end|>\n"); + }; + if let Some(system) = &self.system { + turn("system", system); + } + for (role, content) in &self.history { + let role = match role { + Role::User => "user", + Role::Assistant => "assistant", + }; + turn(role, content); + } + out.push_str("<|im_start|>assistant\n"); + out + } + + /// Answers `message`, calling `on_piece` with each new piece of text. + /// Returns the whole reply, which is added to the conversation. + pub async fn send( + &mut self, + message: String, + on_piece: impl FnMut(&str), + ) -> Result { + self.history.push((Role::User, message)); + match self.generate(on_piece).await { + Ok(reply) => { + self.history.push((Role::Assistant, reply.clone())); + Ok(reply) + } + Err(e) => { + self.history.pop(); + Err(e) + } + } + } + + async fn generate(&mut self, mut on_piece: impl FnMut(&str)) -> Result { + let ids = self + .tokenizer + .encode(self.prompt(), false) + .map_err(|e| e.to_string())? + .get_ids() + .to_vec(); + + // Reuse the cached positions the new prompt shares with the last one. + let mut start = self + .cached + .iter() + .zip(&ids) + .take_while(|(a, b)| a == b) + .count(); + if start == ids.len() { + start -= 1; + } + // `cached` mirrors the model's cache, which forward() truncates to + // `start` before running a chunk. + self.cached.truncate(start); + let mut logits = Vec::new(); + for chunk in ids[start..].chunks(PREFILL_CHUNK) { + logits = self + .model + .forward(chunk, start) + .map_err(|e| e.to_string())?; + self.cached.extend_from_slice(chunk); + start += chunk.len(); + yield_to_event_loop().await; + } + + let mut sampler = Sampler::new(SamplerConfig { + seed: seed(), + ..SamplerConfig::default() + }); + let mut generated: Vec = Vec::new(); + let mut shown = 0; + let mut reply = String::new(); + for _ in 0..MAX_TOKENS { + let next = sampler.sample(&mut logits, &generated); + if self.eos.contains(&next) { + break; + } + generated.push(next); + let text = self + .tokenizer + .decode(&generated, true) + .map_err(|e| e.to_string())?; + // Hold back a piece that ends inside a multi-byte character. + if !text.ends_with('\u{fffd}') && text.len() > shown { + on_piece(&text[shown..]); + shown = text.len(); + reply = text; + } + if self.model.cache_len() + 1 >= self.model.config().context_length { + break; + } + logits = self + .model + .forward(&[next], self.model.cache_len()) + .map_err(|e| e.to_string())?; + self.cached.push(next); + yield_to_event_loop().await; + } + Ok(reply) + } +} + +/// A seed that differs between replies. +fn seed() -> u64 { + let now = js_sys::Date::now() as u64; + let random = (js_sys::Math::random() * u32::MAX as f64) as u64; + now ^ (random << 20) +} + +/// Lets the worker's event loop run (a `setTimeout(0)` macrotask). +async fn yield_to_event_loop() { + let promise = js_sys::Promise::new(&mut |resolve, _reject| { + let global = js_sys::global(); + if let Ok(set_timeout) = js_sys::Reflect::get(&global, &"setTimeout".into()) { + if let Ok(set_timeout) = set_timeout.dyn_into::() { + let _ = set_timeout.call2(&global, &resolve, &JsValue::from(0)); + return; + } + } + let _ = resolve.call0(&JsValue::UNDEFINED); + }); + let _ = JsFuture::from(promise).await; +} diff --git a/examples/web-chat/src/lib.rs b/examples/web-chat/src/lib.rs index 1f36faf..b879781 100644 --- a/examples/web-chat/src/lib.rs +++ b/examples/web-chat/src/lib.rs @@ -1,26 +1,43 @@ -//! Ed in the browser. +//! Ed in the browser, on the vectoron engine. //! -//! [`WebChat`] wraps one [`Ed`] and is meant to live in a Web Worker: loading +//! [`WebChat`] owns one model and is meant to live in a Web Worker: loading //! the model and every token's forward pass block the thread they run on. The //! page talks to it through `www/worker.js`. //! -//! Each method returns a `Promise` and holds its own `Rc`, because -//! wasm-bindgen would otherwise borrow `&self` across the whole await and a -//! second call (a `reset` while a reply streams) would panic. +//! Each method returns a `Promise` and holds its own `Rc` of the session, +//! because wasm-bindgen would otherwise borrow `&self` across the whole await. +//! While a reply streams, the chat is taken out of the session and the session +//! reads [`State::Busy`], so a call that arrives meanwhile (a `reset` during a +//! reply) is refused with an error. +mod chat; +mod store; + +use std::cell::RefCell; use std::rc::Rc; -use ed_agent::{Ed, GgufModelConfig}; +use chat::Chat; use js_sys::{Function, Promise}; +use serde::Serialize; +use store::{ModelFiles, QWEN25_0_5B}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::future_to_promise; -/// The model this example runs: the catalogue's smallest (about 380 MB). The -/// preset comes from onde, so no model name is written here. -fn model() -> GgufModelConfig { - GgufModelConfig::qwen25_0_5b() +/// The model this example runs: Qwen 2.5 0.5B, about 380 MB. +const MODEL: ModelFiles = QWEN25_0_5B; + +const BUSY: &str = "Ed is busy with another request"; +const NOT_LOADED: &str = "No model loaded, call `load` first"; + +enum State { + Unloaded, + Ready(Box), + /// A reply or a load is running. + Busy, } +type Session = Rc>; + fn to_js_error(e: impl std::fmt::Display) -> JsValue { JsValue::from_str(&e.to_string()) } @@ -29,9 +46,30 @@ fn number(n: u64) -> JsValue { JsValue::from_f64(n as f64) } +/// Takes the chat out of the session, leaving it busy. +fn take_chat(session: &Session) -> Result, JsValue> { + let mut state = session.borrow_mut(); + match std::mem::replace(&mut *state, State::Busy) { + State::Ready(chat) => Ok(chat), + State::Unloaded => { + *state = State::Unloaded; + Err(to_js_error(NOT_LOADED)) + } + State::Busy => Err(to_js_error(BUSY)), + } +} + +#[derive(Serialize)] +struct Info { + status: &'static str, + model_name: Option<&'static str>, + approx_memory: Option<&'static str>, + history_length: u64, +} + #[wasm_bindgen] pub struct WebChat { - ed: Rc, + session: Session, } impl Default for WebChat { @@ -46,30 +84,25 @@ impl WebChat { pub fn new() -> WebChat { console_error_panic_hook::set_once(); WebChat { - ed: Rc::new(Ed::new()), + session: Rc::new(RefCell::new(State::Unloaded)), } } /// Display name and size of the model, for the first-run card. pub fn model_label(&self) -> String { - let config = model(); - format!("{}, {}", config.display_name, config.approx_memory) + format!("{}, {}", MODEL.display_name, MODEL.approx_size) } /// Resolves to whether the model is already in the browser cache. pub fn is_cached(&self) -> Promise { - future_to_promise(async move { - Ok(JsValue::from_bool( - onde::web_store::is_cached(&model()).await, - )) - }) + future_to_promise(async move { Ok(JsValue::from_bool(store::is_cached(&MODEL).await)) }) } /// Download the model into the browser cache. `on_progress(received, total)` /// gets byte counts; `total` is `null` when the server hides the length. pub fn download(&self, on_progress: Function) -> Promise { future_to_promise(async move { - onde::web_store::download_model(&model(), |received, total| { + store::download(&MODEL, |received, total| { let total = total.map_or(JsValue::NULL, number); let _ = on_progress.call2(&JsValue::NULL, &number(received), &total); }) @@ -82,9 +115,7 @@ impl WebChat { /// Remove the downloaded model from the browser cache. pub fn delete_cached(&self) -> Promise { future_to_promise(async move { - let removed = onde::web_store::delete_model(&model()) - .await - .map_err(to_js_error)?; + let removed = store::delete(&MODEL).await.map_err(to_js_error)?; Ok(JsValue::from_bool(removed)) }) } @@ -92,43 +123,93 @@ impl WebChat { /// Load the model into memory (downloading it first if it isn't cached). /// Resolves to the load time in seconds. pub fn load(&self, system_prompt: Option) -> Promise { - let ed = self.ed.clone(); + let session = self.session.clone(); future_to_promise(async move { - let took = ed - .load(model(), system_prompt, None) - .await - .map_err(to_js_error)?; - Ok(JsValue::from_f64(took.as_secs_f64())) + let previous = std::mem::replace(&mut *session.borrow_mut(), State::Busy); + if matches!(previous, State::Busy) { + return Err(to_js_error(BUSY)); + } + // Free the old model before reading the new one. + drop(previous); + let started = js_sys::Date::now(); + match load_chat(system_prompt).await { + Ok(chat) => { + *session.borrow_mut() = State::Ready(Box::new(chat)); + Ok(JsValue::from_f64((js_sys::Date::now() - started) / 1000.0)) + } + Err(e) => { + *session.borrow_mut() = State::Unloaded; + Err(e) + } + } }) } /// Send one message. `on_delta(text)` is called for each piece as it is /// generated; the promise resolves with the whole reply. pub fn send(&self, message: String, on_delta: Function) -> Promise { - let ed = self.ed.clone(); + let session = self.session.clone(); future_to_promise(async move { - let mut stream = ed.stream(message).await.map_err(to_js_error)?; - let mut reply = String::new(); - while let Some(piece) = stream.next().await { - let piece = piece.map_err(to_js_error)?; - reply.push_str(&piece); - let _ = on_delta.call1(&JsValue::NULL, &JsValue::from_str(&piece)); - } - Ok(JsValue::from_str(&reply)) + let mut chat = take_chat(&session)?; + let reply = chat + .send(message, |piece| { + let _ = on_delta.call1(&JsValue::NULL, &JsValue::from_str(piece)); + }) + .await; + *session.borrow_mut() = State::Ready(chat); + Ok(JsValue::from_str(&reply.map_err(to_js_error)?)) }) } /// Forget the conversation. Resolves to how many messages were dropped. pub fn reset(&self) -> Promise { - let ed = self.ed.clone(); - future_to_promise(async move { Ok(number(ed.clear_history().await as u64)) }) + let session = self.session.clone(); + future_to_promise(async move { + let dropped = match &mut *session.borrow_mut() { + State::Ready(chat) => chat.reset(), + State::Unloaded => 0, + State::Busy => return Err(to_js_error(BUSY)), + }; + Ok(number(dropped as u64)) + }) } /// Engine status, model name and history length. pub fn info(&self) -> Promise { - let ed = self.ed.clone(); + let session = self.session.clone(); future_to_promise(async move { - serde_wasm_bindgen::to_value(&ed.info().await).map_err(to_js_error) + let info = match &*session.borrow() { + State::Unloaded => Info { + status: "unloaded", + model_name: None, + approx_memory: None, + history_length: 0, + }, + State::Busy => Info { + status: "busy", + model_name: Some(MODEL.display_name), + approx_memory: Some(MODEL.approx_size), + history_length: 0, + }, + State::Ready(chat) => Info { + status: "ready", + model_name: Some(MODEL.display_name), + approx_memory: Some(MODEL.approx_size), + history_length: chat.history_len() as u64, + }, + }; + serde_wasm_bindgen::to_value(&info).map_err(to_js_error) }) } } + +/// Reads the tokenizer and the model from the cache and starts a chat. +async fn load_chat(system_prompt: Option) -> Result { + let tokenizer = store::load(&MODEL.tokenizer_url()) + .await + .map_err(to_js_error)?; + let tokenizer = tokenizers::Tokenizer::from_bytes(tokenizer).map_err(to_js_error)?; + let gguf = store::load(&MODEL.model_url()).await.map_err(to_js_error)?; + let model = vectoron::Qwen2Model::load(gguf).map_err(to_js_error)?; + Chat::new(model, tokenizer, system_prompt).map_err(to_js_error) +} diff --git a/examples/web-chat/src/store.rs b/examples/web-chat/src/store.rs new file mode 100644 index 0000000..9fabc60 --- /dev/null +++ b/examples/web-chat/src/store.rs @@ -0,0 +1,232 @@ +//! The browser model store. +//! +//! Model files come from `https://huggingface.co//resolve/main/` +//! (Hugging Face serves CORS) and are kept in the Cache Storage API under +//! [`CACHE_NAME`]. Cache Storage works from a window and from a worker and +//! survives reloads, so a model is downloaded once per browser profile. +//! +//! The cache name and URLs match the ones onde's `web_store` used, so a model +//! cached by an earlier build of this page is found without downloading again. + +use js_sys::{Function, Promise, Reflect, Uint8Array}; +use wasm_bindgen::{JsCast, JsValue}; +use wasm_bindgen_futures::JsFuture; +use web_sys::{Cache, CacheStorage, ReadableStreamDefaultReader, Response}; + +/// Name of the Cache Storage bucket that holds downloaded model files. +pub const CACHE_NAME: &str = "onde-models-v1"; + +const HF_BASE: &str = "https://huggingface.co"; + +/// A model and its tokenizer, both hosted on Hugging Face. +pub struct ModelFiles { + pub display_name: &'static str, + pub approx_size: &'static str, + pub repo: &'static str, + pub file: &'static str, + pub tokenizer_repo: &'static str, +} + +/// Qwen 2.5 0.5B Instruct, Q4_K_M. +pub const QWEN25_0_5B: ModelFiles = ModelFiles { + display_name: "Qwen 2.5 0.5B", + approx_size: "~380 MB (GGUF Q4_K_M)", + repo: "bartowski/Qwen2.5-0.5B-Instruct-GGUF", + file: "Qwen2.5-0.5B-Instruct-Q4_K_M.gguf", + tokenizer_repo: "Qwen/Qwen2.5-0.5B-Instruct", +}; + +const TOKENIZER_FILE: &str = "tokenizer.json"; + +impl ModelFiles { + pub fn model_url(&self) -> String { + url(self.repo, self.file) + } + + pub fn tokenizer_url(&self) -> String { + url(self.tokenizer_repo, TOKENIZER_FILE) + } + + fn urls(&self) -> [String; 2] { + [self.tokenizer_url(), self.model_url()] + } +} + +fn url(repo: &str, file: &str) -> String { + format!("{HF_BASE}/{repo}/resolve/main/{file}") +} + +/// Downloads the tokenizer, then the model, into the cache. +/// `on_progress(received, total)` reports the model file's bytes; `total` is +/// `None` when the server hides the length. Cached files are skipped. +pub async fn download( + files: &ModelFiles, + mut on_progress: impl FnMut(u64, Option), +) -> Result<(), String> { + ensure_cached(&files.tokenizer_url(), &mut |_, _| {}).await?; + ensure_cached(&files.model_url(), &mut on_progress).await +} + +/// Whether the model and its tokenizer are both cached. +pub async fn is_cached(files: &ModelFiles) -> bool { + let Ok(cache) = open_cache().await else { + return false; + }; + for url in files.urls() { + if !matches!(cache_match(&cache, &url).await, Ok(Some(_))) { + return false; + } + } + true +} + +/// Removes the model and its tokenizer. Returns whether anything was removed. +pub async fn delete(files: &ModelFiles) -> Result { + let cache = open_cache().await?; + let mut removed = false; + for url in files.urls() { + let deleted = JsFuture::from(cache.delete_with_str(&url)) + .await + .map_err(|e| js_message(&e))?; + removed |= deleted.as_bool().unwrap_or(false); + } + Ok(removed) +} + +/// Reads a cached file into wasm memory, downloading it first if missing. +/// +/// The bytes cross from a JS `ArrayBuffer` into one `Vec`; the engine then +/// works on that `Vec` in place, so the peak is about twice the file size +/// until the browser collects the `ArrayBuffer`. +pub async fn load(url: &str) -> Result, String> { + ensure_cached(url, &mut |_, _| {}).await?; + let cache = open_cache().await?; + let response = cache_match(&cache, url) + .await? + .ok_or_else(|| format!("{url} vanished from the cache"))?; + let buffer = JsFuture::from(response.array_buffer().map_err(|e| js_message(&e))?) + .await + .map_err(|e| js_message(&e))?; + Ok(Uint8Array::new(&buffer).to_vec()) +} + +pub fn js_message(value: &JsValue) -> String { + if let Some(s) = value.as_string() { + return s; + } + if let Ok(message) = Reflect::get(value, &"message".into()) { + if let Some(s) = message.as_string() { + return s; + } + } + format!("{value:?}") +} + +async fn open_cache() -> Result { + let global = js_sys::global(); + let caches = Reflect::get(&global, &"caches".into()).map_err(|e| js_message(&e))?; + if caches.is_undefined() || caches.is_null() { + return Err("Cache Storage is not available (it needs a secure context)".into()); + } + let storage: CacheStorage = caches + .dyn_into() + .map_err(|_| "`caches` is not a CacheStorage".to_string())?; + JsFuture::from(storage.open(CACHE_NAME)) + .await + .map_err(|e| js_message(&e))? + .dyn_into::() + .map_err(|_| "Cache Storage returned something that is not a Cache".to_string()) +} + +async fn cache_match(cache: &Cache, url: &str) -> Result, String> { + let found = JsFuture::from(cache.match_with_str(url)) + .await + .map_err(|e| js_message(&e))?; + if found.is_undefined() || found.is_null() { + return Ok(None); + } + found + .dyn_into::() + .map(Some) + .map_err(|_| "cache hit is not a Response".to_string()) +} + +fn content_length(response: &Response) -> Option { + response + .headers() + .get("content-length") + .ok() + .flatten() + .and_then(|v| v.parse().ok()) +} + +async fn fetch(url: &str) -> Result { + let global = js_sys::global(); + let fetch: Function = Reflect::get(&global, &"fetch".into()) + .map_err(|e| js_message(&e))? + .dyn_into() + .map_err(|_| "`fetch` is not available".to_string())?; + let promise: Promise = fetch + .call1(&global, &JsValue::from_str(url)) + .map_err(|e| js_message(&e))? + .dyn_into() + .map_err(|_| "`fetch` did not return a promise".to_string())?; + let response: Response = JsFuture::from(promise) + .await + .map_err(|e| format!("could not fetch {url}: {}", js_message(&e)))? + .dyn_into() + .map_err(|_| "`fetch` did not resolve to a Response".to_string())?; + if !response.ok() { + return Err(format!("HTTP {} for {url}", response.status())); + } + Ok(response) +} + +/// Makes sure `url` is in the cache. One clone of the response goes to +/// `Cache.put`, which writes it to disk as it arrives; the other is read only +/// to count bytes, so the file is never held in memory here. +async fn ensure_cached( + url: &str, + on_progress: &mut dyn FnMut(u64, Option), +) -> Result<(), String> { + let cache = open_cache().await?; + if let Some(hit) = cache_match(&cache, url).await? { + let size = content_length(&hit).unwrap_or(0); + on_progress(size, Some(size)); + return Ok(()); + } + + let response = fetch(url).await?; + let total = content_length(&response); + let for_cache = response.clone().map_err(|e| js_message(&e))?; + let put = cache.put_with_str(url, &for_cache); + + let body = response + .body() + .ok_or_else(|| format!("{url} has no response body"))?; + let reader: ReadableStreamDefaultReader = body + .get_reader() + .dyn_into() + .map_err(|_| "response body has no default reader".to_string())?; + let mut received = 0u64; + loop { + let step = JsFuture::from(reader.read()) + .await + .map_err(|e| js_message(&e))?; + if Reflect::get(&step, &"done".into()) + .map(|d| d.as_bool().unwrap_or(false)) + .unwrap_or(true) + { + break; + } + if let Ok(chunk) = Reflect::get(&step, &"value".into()) { + received += chunk.unchecked_into::().length() as u64; + on_progress(received, total); + } + } + JsFuture::from(put) + .await + .map_err(|e| format!("could not cache {url}: {}", js_message(&e)))?; + on_progress(received, total.or(Some(received))); + Ok(()) +}