From 1a9fd929e7e01b95f4f25ef10564bf13d06848b9 Mon Sep 17 00:00:00 2001 From: cuishuang Date: Tue, 8 Sep 2026 21:10:51 +0800 Subject: [PATCH] fix(yew-link): surface initial internal fetch errors --- .github/workflows/main-checks.yml | 4 + Cargo.lock | 4 + packages/yew-link/Cargo.toml | 7 + packages/yew-link/src/lib.rs | 277 +++++++++++++----------- packages/yew-link/tests/linked_state.rs | 197 +++++++++++++++++ 5 files changed, 364 insertions(+), 125 deletions(-) create mode 100644 packages/yew-link/tests/linked_state.rs diff --git a/.github/workflows/main-checks.yml b/.github/workflows/main-checks.yml index d608767dde2..3f7e8365367 100644 --- a/.github/workflows/main-checks.yml +++ b/.github/workflows/main-checks.yml @@ -114,6 +114,10 @@ jobs: CHROMEDRIVER="$(which chromedriver)" cargo test --target wasm32-unknown-unknown GECKODRIVER="$(which geckodriver)" cargo test --target wasm32-unknown-unknown + - name: Run tests - yew-link + run: | + CHROMEDRIVER="$(which chromedriver)" cargo test -p yew-link --features hydration --target wasm32-unknown-unknown + unit_tests: name: Unit Tests on ${{ matrix.toolchain }} runs-on: ubuntu-latest diff --git a/Cargo.lock b/Cargo.lock index 61fdaceef1f..29e7d2f9565 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5174,11 +5174,15 @@ version = "0.1.0" dependencies = [ "actix-web", "axum", + "gloo", "gloo-net", "lru", "serde", "serde_json", + "wasm-bindgen", "wasm-bindgen-futures", + "wasm-bindgen-test", + "web-sys", "yew", "yew-link-macro", ] diff --git a/packages/yew-link/Cargo.toml b/packages/yew-link/Cargo.toml index 14c0a3e420b..cb4c85a5488 100644 --- a/packages/yew-link/Cargo.toml +++ b/packages/yew-link/Cargo.toml @@ -22,6 +22,13 @@ wasm-bindgen-futures = { workspace = true } axum = { workspace = true, optional = true } actix-web = { workspace = true, optional = true } +[target.'cfg(target_arch = "wasm32")'.dev-dependencies] +gloo.workspace = true +wasm-bindgen.workspace = true +wasm-bindgen-test.workspace = true +web-sys.workspace = true +yew = { path = "../yew", features = ["csr"] } + [features] default = [] ssr = ["yew/ssr"] diff --git a/packages/yew-link/src/lib.rs b/packages/yew-link/src/lib.rs index 2938d577826..317d460446e 100644 --- a/packages/yew-link/src/lib.rs +++ b/packages/yew-link/src/lib.rs @@ -1,8 +1,8 @@ use std::any::{Any, TypeId}; +#[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] +use std::cell::OnceCell; use std::cell::RefCell; use std::collections::HashMap; -#[cfg(target_arch = "wasm32")] -use std::collections::HashSet; use std::fmt; use std::hash::Hash; #[cfg(target_arch = "wasm32")] @@ -16,7 +16,7 @@ use lru::LruCache; use serde::Serialize; use serde::de::DeserializeOwned; use yew::prelude::*; -#[cfg(target_arch = "wasm32")] +#[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] use yew::suspense::Suspension; use yew::suspense::SuspensionResult; pub use yew_link_macro::linked_state; @@ -306,23 +306,34 @@ fn cache_key(input: &T::Input) -> CacheKey { } #[cfg(target_arch = "wasm32")] -type Cache = Rc>>; +type Cache = Rc>>>; #[cfg(not(target_arch = "wasm32"))] type Cache = Rc>>; -#[cfg(target_arch = "wasm32")] -type InFlight = Rc>>; +#[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] +type InFlight = Rc>>>; -#[cfg(target_arch = "wasm32")] -type Refreshing = Rc>>; +#[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] +type LinkedResult = Result, LinkError<::Error>>; + +#[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] +struct Request { + suspension: Suspension, + result: OnceCell>, +} + +#[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] +struct Query { + key: CacheKey, + result: Option>, + request: Option>>, +} #[derive(Clone)] struct LinkContextInner { cache: Cache, - #[cfg(target_arch = "wasm32")] + #[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] in_flight: InFlight, - #[cfg(target_arch = "wasm32")] - refreshing: Refreshing, endpoint: AttrValue, #[cfg(feature = "ssr")] resolver: Option>, @@ -331,12 +342,11 @@ struct LinkContextInner { impl PartialEq for LinkContextInner { fn eq(&self, other: &Self) -> bool { Rc::ptr_eq(&self.cache, &other.cache) && self.endpoint == other.endpoint && { - #[cfg(target_arch = "wasm32")] + #[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] { Rc::ptr_eq(&self.in_flight, &other.in_flight) - && Rc::ptr_eq(&self.refreshing, &other.refreshing) } - #[cfg(not(target_arch = "wasm32"))] + #[cfg(any(feature = "ssr", not(target_arch = "wasm32")))] { true } @@ -345,6 +355,53 @@ impl PartialEq for LinkContextInner { } impl LinkContextInner { + #[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] + fn request(&self, key: &CacheKey, input: T::Input) -> Rc> { + if let Some(request) = self.in_flight.borrow().get(key) { + return request + .clone() + .downcast::>() + .expect("request type must match its cache key"); + } + + let (suspension, handle) = Suspension::new(); + let request = Rc::new(Request { + suspension, + result: OnceCell::new(), + }); + self.in_flight + .borrow_mut() + .insert(key.clone(), request.clone()); + + let ctx = self.clone(); + let key = key.clone(); + let pending = request.clone(); + wasm_bindgen_futures::spawn_local(async move { + let result = ctx.fetch_remote::(&input).await.map(Rc::new); + match &result { + Ok(value) => { + ctx.cache.borrow_mut().put(key.clone(), value.clone()); + } + Err(LinkError::Resolve(_)) => { + ctx.cache.borrow_mut().pop(&key); + } + Err(LinkError::Internal(_)) => {} + } + + // The hooks that joined this request own its result after it leaves the map. + assert!(pending.result.set(result).is_ok(), "request completes once"); + { + let mut in_flight = ctx.in_flight.borrow_mut(); + in_flight.remove(&key); + if in_flight.capacity() > in_flight.len().saturating_mul(4) { + in_flight.shrink_to_fit(); + } + } + handle.resume(); + }); + request + } + #[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] async fn fetch_remote( &self, @@ -460,17 +517,13 @@ pub fn LinkProvider(props: &LinkProviderProps) -> Html { }; #[cfg(not(target_arch = "wasm32"))] let cache: Cache = (*use_ref(|| Rc::new(RefCell::new(HashMap::new())))).clone(); - #[cfg(target_arch = "wasm32")] + #[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] let in_flight: InFlight = (*use_ref(|| Rc::new(RefCell::new(HashMap::new())))).clone(); - #[cfg(target_arch = "wasm32")] - let refreshing: Refreshing = (*use_ref(|| Rc::new(RefCell::new(HashSet::new())))).clone(); let ctx = LinkContextInner { cache, - #[cfg(target_arch = "wasm32")] + #[cfg(all(not(feature = "ssr"), target_arch = "wasm32"))] in_flight, - #[cfg(target_arch = "wasm32")] - refreshing, endpoint: props.endpoint.clone(), #[cfg(feature = "ssr")] resolver: props.resolver.as_ref().map(|r| Arc::clone(&r.0)), @@ -500,7 +553,10 @@ pub fn LinkProvider(props: &LinkProviderProps) -> Html { /// the fresh data arrives. /// /// Multiple components requesting the same `(T, Input)` concurrently share a -/// single in-flight request. +/// single in-flight request. Each hook remembers the result for its current +/// input, so a failed request is only retried explicitly via +/// [`refresh`](LinkedStateHandle::refresh). A background refresh updates the +/// hooks that requested it. /// /// # Panics /// @@ -556,124 +612,95 @@ pub fn use_linked_state(input: T::Input) -> SuspensionResult, T::Input>(input.clone())?; - let key = cache_key::(&input); + // Keep one query per hook. A change of input drops the previous query, + // even when a request for that input is still in flight. + let query = use_memo(input.clone(), |input| { + let key = cache_key::(input); + let result = match prepared { + Some(prepared) => { + let result = prepared.as_ref().clone().map(Rc::new); + if let Ok(value) = &result { + let mut cache = link_ctx.cache.borrow_mut(); + if cache.peek(&key).is_none() { + cache.put(key.clone(), value.clone()); + } + } + Some(result) + } + None => link_ctx.cache.borrow_mut().get(&key).map(|value| { + Ok(value + .clone() + .downcast::() + .expect("value type must match its cache key")) + }), + }; + RefCell::new(Query { + key, + result, + request: None, + }) + }); + let force_update = use_force_update(); - if let Some(ref result) = prepared { - if let Ok(json_val) = serde_json::to_value(result.as_ref()) { - let mut cache = link_ctx.cache.borrow_mut(); - if cache.peek(&key).is_none() { - cache.put(key.clone(), json_val); + let (result, refreshing) = { + let mut query = query.borrow_mut(); + let Query { + key, + result, + request, + } = &mut *query; + if let Some(fetched) = request.as_ref().and_then(|request| request.result.get()) { + // A transient refresh failure keeps the previous result visible. + if result.is_none() || !matches!(fetched, Err(LinkError::Internal(_))) { + *result = Some(fetched.clone()); } + *request = None; } - } - let force_update = use_force_update(); - let has_refreshed = use_ref(|| std::cell::Cell::new(false)); + match result { + Some(result) => (result.clone(), request.is_some()), + None => { + return Err(request + .get_or_insert_with(|| link_ctx.request::(key, input.clone())) + .suspension + .clone()); + } + } + }; let refresh = { - let cache = link_ctx.cache.clone(); - let refreshing = link_ctx.refreshing.clone(); - let key = key.clone(); - let link_ctx = link_ctx.clone(); - let input = input.clone(); - let force_update = force_update.clone(); - let has_refreshed = has_refreshed.clone(); + let query = Rc::downgrade(&query); Callback::from(move |()| { - refreshing.borrow_mut().insert(key.clone()); - has_refreshed.set(true); - - let link_ctx = link_ctx.clone(); - let key = key.clone(); - let cache = cache.clone(); - let refreshing = refreshing.clone(); - let inner_force_update = force_update.clone(); - let input = input.clone(); + let Some(current) = query.upgrade() else { + return; + }; + let mut current = current.borrow_mut(); + if current.request.is_some() { + return; + } + + let request = link_ctx.request::(¤t.key, input.clone()); + let suspension = request.suspension.clone(); + current.request = Some(request); + drop(current); + + let query = query.clone(); + let on_complete = force_update.clone(); wasm_bindgen_futures::spawn_local(async move { - let result: Result> = - link_ctx.fetch_remote::(&input).await; - - refreshing.borrow_mut().remove(&key); - - let should_cache = match &result { - Ok(_) | Err(LinkError::Resolve(_)) => true, - Err(LinkError::Internal(_)) => false, - }; - if should_cache { - if let Ok(json_val) = serde_json::to_value(&result) { - cache.borrow_mut().put(key, json_val); - } + suspension.await; + if query.upgrade().is_some() { + on_complete.force_update(); } - - inner_force_update.force_update(); }); - force_update.force_update(); }) }; - if !has_refreshed.get() { - if let Some(result) = prepared { - return Ok(LinkedStateHandle { - result: match result.as_ref() { - Ok(val) => Ok(Rc::new(val.clone())), - Err(e) => Err(e.clone()), - }, - refresh, - refreshing: false, - }); - } - } - - let is_refreshing = link_ctx.refreshing.borrow().contains(&key); - - if let Some(cached_val) = link_ctx.cache.borrow_mut().get(&key).cloned() { - if let Ok(result) = serde_json::from_value::>(cached_val) { - return Ok(LinkedStateHandle { - result: result.map(Rc::new), - refresh, - refreshing: is_refreshing, - }); - } - } - - if let Some(sus) = link_ctx.in_flight.borrow().get(&key).cloned() { - if !sus.resumed() { - return Err(sus); - } - if let Some(cached_val) = link_ctx.cache.borrow_mut().get(&key).cloned() { - if let Ok(result) = serde_json::from_value::>(cached_val) { - return Ok(LinkedStateHandle { - result: result.map(Rc::new), - refresh, - refreshing: false, - }); - } - } - } - - let sus = Suspension::from_future({ - let link_ctx = link_ctx.clone(); - let key = key.clone(); - async move { - let result: Result> = - link_ctx.fetch_remote::(&input).await; - - link_ctx.in_flight.borrow_mut().remove(&key); - - let should_cache = match &result { - Ok(_) | Err(LinkError::Resolve(_)) => true, - Err(LinkError::Internal(_)) => false, - }; - if should_cache { - if let Ok(json_val) = serde_json::to_value(&result) { - link_ctx.cache.borrow_mut().put(key, json_val); - } - } - } - }); - - link_ctx.in_flight.borrow_mut().insert(key, sus.clone()); - Err(sus) + Ok(LinkedStateHandle { + result, + refresh, + refreshing, + }) } } diff --git a/packages/yew-link/tests/linked_state.rs b/packages/yew-link/tests/linked_state.rs new file mode 100644 index 00000000000..4ecbccd800f --- /dev/null +++ b/packages/yew-link/tests/linked_state.rs @@ -0,0 +1,197 @@ +#![cfg(all(target_arch = "wasm32", target_os = "unknown", not(feature = "ssr")))] + +use std::time::Duration; + +use gloo::utils::document; +use serde::{Deserialize, Serialize}; +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure}; +use yew::platform::time::sleep; +use yew::prelude::*; +use yew_link::{LinkProvider, LinkedState, Never, use_linked_state}; + +wasm_bindgen_test_configure!(run_in_browser); + +#[wasm_bindgen(inline_js = " +const requests = []; +const fetch = window.fetch; +export function mock_fetch() { + window.fetch = (request, ...args) => { + if (!request.url?.endsWith('/linked-state-test')) { + return fetch.call(window, request, ...args); + } + return new Promise(resolve => requests.push(resolve)); + }; +} +export function request_count() { + return requests.length; +} +export function respond(index, body) { + requests[index](new Response(body)); +} +export function restore_fetch() { + window.fetch = fetch; +} +")] +extern "C" { + fn mock_fetch(); + fn request_count() -> usize; + fn respond(index: usize, body: &str); + fn restore_fetch(); +} + +#[derive(Clone, Deserialize, Serialize)] +struct Value(u32); + +impl LinkedState for Value { + type Error = Never; + type Input = u32; + + const TYPE_KEY: &'static str = "Value"; +} + +#[derive(Clone, PartialEq, Properties)] +struct WatchProps { + id: &'static str, + input: u32, + revision: u32, +} + +#[component] +fn Watch(props: &WatchProps) -> HtmlResult { + let value = use_linked_state::(props.input)?; + let text = match value.as_result() { + Ok(value) => value.0.to_string(), + Err(_) => "error".into(), + }; + let refreshing = if value.is_refreshing() { + " refreshing" + } else { + "" + }; + let onclick = Callback::from(move |_| value.refresh()); + Ok(html! { }) +} + +#[derive(Clone, PartialEq, Properties)] +struct AppProps { + second: u32, + revision: u32, +} + +#[component] +fn App(props: &AppProps) -> Html { + html! { + + + + + + + + + } +} + +async fn wait_for(mut condition: impl FnMut() -> bool) { + for _ in 0..100 { + if condition() { + return; + } + sleep(Duration::from_millis(10)).await; + } + panic!("timed out waiting for linked state"); +} + +fn text(id: &str) -> Option { + document().get_element_by_id(id)?.text_content() +} + +fn click(id: &str) { + document() + .get_element_by_id(id) + .unwrap() + .unchecked_into::() + .click(); +} + +#[wasm_bindgen_test] +async fn coalesces_requests_and_keeps_results_for_each_query() { + mock_fetch(); + struct RestoreFetch; + impl Drop for RestoreFetch { + fn drop(&mut self) { + restore_fetch(); + } + } + let _restore = RestoreFetch; + + let root = document().create_element("div").unwrap(); + document().body().unwrap().append_child(&root).unwrap(); + let mut app = yew::Renderer::::with_root_and_props( + root.clone(), + AppProps { + second: 1, + revision: 0, + }, + ) + .render(); + + wait_for(|| request_count() == 1).await; + respond(0, "invalid JSON"); + wait_for(|| { + text("first").as_deref() == Some("error") && text("second").as_deref() == Some("error") + }) + .await; + assert_eq!(request_count(), 1); + + click("first"); + click("first"); + click("second"); + wait_for(|| { + text("first").as_deref() == Some("error refreshing") + && text("second").as_deref() == Some("error refreshing") + }) + .await; + assert_eq!(request_count(), 2); + respond(1, r#"{"ok": 10}"#); + wait_for(|| text("first").as_deref() == Some("10") && text("second").as_deref() == Some("10")) + .await; + + app.update(AppProps { + second: 2, + revision: 1, + }); + wait_for(|| request_count() == 3).await; + respond(2, r#"{"ok": 20}"#); + wait_for(|| text("second").as_deref() == Some("20")).await; + + // The cache holds only input 2 now. Re-rendering the first hook keeps its result. + app.update(AppProps { + second: 2, + revision: 2, + }); + sleep(Duration::ZERO).await; + assert_eq!(text("first").as_deref(), Some("10")); + assert_eq!(request_count(), 3); + + click("first"); + wait_for(|| text("first").as_deref() == Some("10 refreshing") && request_count() == 4).await; + respond(3, "invalid JSON"); + wait_for(|| text("first").as_deref() == Some("10")).await; + assert_eq!(request_count(), 4); + + // A changed input is a new query and can fetch after eviction. + app.update(AppProps { + second: 1, + revision: 3, + }); + wait_for(|| request_count() == 5).await; + respond(4, r#"{"ok": 11}"#); + wait_for(|| text("second").as_deref() == Some("11")).await; + assert_eq!(text("first").as_deref(), Some("10")); + + app.destroy(); + root.remove(); +}