diff --git a/docs/development/QUALITY_GATES.md b/docs/development/QUALITY_GATES.md index ed6c9ff7..1afddb0b 100644 --- a/docs/development/QUALITY_GATES.md +++ b/docs/development/QUALITY_GATES.md @@ -112,7 +112,10 @@ must remain row-for-row identical. Host health and library snapshots read only the public library identity fields. The snapshot counts printers and active outbound loans within the same SQLite -read transaction as inventory. API tests cover legacy loan directions, returned +read transaction as inventory. Paired Clients order successful summary reads by +request. An overlapping Dashboard read updates its own projection independently +of ordinary summaries. Tests complete requests out of order with equal Host +timestamps and exercise the fallback for older Hosts. API tests cover legacy loan directions, returned loans, deleted spools and unreadable fields outside the response. The [packaged multiprocess runner](../../scripts/run-packaged-host-client-e2e.mjs) diff --git a/src-tauri/src/library_sync_read_commands.rs b/src-tauri/src/library_sync_read_commands.rs index c329eb56..1295cd06 100644 --- a/src-tauri/src/library_sync_read_commands.rs +++ b/src-tauri/src/library_sync_read_commands.rs @@ -738,6 +738,7 @@ mod tests { mod spool_detail; mod spool_snapshot; mod stock_cards; + mod summary_snapshot; mod wishlist_purchase; fn not_found_envelope() -> String { diff --git a/src-tauri/src/library_sync_read_commands/tests/summary_snapshot.rs b/src-tauri/src/library_sync_read_commands/tests/summary_snapshot.rs new file mode 100644 index 00000000..bb4800a0 --- /dev/null +++ b/src-tauri/src/library_sync_read_commands/tests/summary_snapshot.rs @@ -0,0 +1,85 @@ +use super::{fake_health, fake_host_state, spawn_fake_host_with, FakeHostResponse}; +use crate::backend::database_library_sync_models::LibrarySyncCachedSnapshotRow; +use crate::backend::filament_database::FilamentDatabase; +use crate::backend::statistics::InventoryOverview; +use crate::library_sync_command_support::library_sync_host_input; +use crate::library_sync_snapshot_commands::fetch_library_sync_snapshot_blocking; +use serde_json::json; + +#[test] +fn delayed_summary_returns_the_committed_rows_and_rejects_an_old_pairing() { + let route = "GET /api/v1/library/snapshot "; + for switch_target in [false, true] { + let (tx, rx) = std::sync::mpsc::channel::(); + let later = LibrarySyncCachedSnapshotRow { + dashboard_stock: None, + captured_at: "2026-12-01 12:00:00".into(), + app_version: None, + library_id: "library-test".into(), + device_name: "Host".into(), + sync_mode: "HOST".into(), + inventory: InventoryOverview::default(), + total_spools: 0, + in_use: 0, + low_stock: 0, + active_loans: 8, + printers: 2, + }; + let mut earlier = json!(later); + earlier["ok"] = json!(true); + earlier["active_loans"] = json!(3); + let (url, server) = spawn_fake_host_with( + vec![ + FakeHostResponse { + expected_request_prefix: "GET /api/v1/health ", + status: "200 OK", + body: fake_health(), + }, + FakeHostResponse { + expected_request_prefix: route, + status: "200 OK", + body: earlier.to_string(), + }, + ], + move |request| { + if request.starts_with(route) { + let db = FilamentDatabase::open(rx.recv().unwrap()).unwrap(); + if switch_target { + let original = db.get_library_sync_settings().unwrap(); + let mut replacement = original.clone(); + replacement.library_id = "other".into(); + db.save_library_sync_settings(&replacement).unwrap(); + db.save_library_sync_settings(&original).unwrap(); + } + let next = db.begin_summary_request().unwrap(); + db.finish_summary_request(later.clone(), false, next) + .unwrap(); + } + }, + ); + let (state, path) = fake_host_state(&url); + let db = FilamentDatabase::open(&path).unwrap(); + let generation = db.get_library_sync_page_status().unwrap().target_generation; + tx.send(path.clone()).unwrap(); + let live = fetch_library_sync_snapshot_blocking( + &state, + library_sync_host_input(&url, Some("library-test")), + false, + Some(generation), + ); + server.join().unwrap(); + let cached = db + .get_library_sync_settings() + .unwrap() + .cached_snapshot + .unwrap(); + assert_eq!(cached.active_loans, 8); + if switch_target { + assert!(live.unwrap_err().contains("common.invalid_request")); + } else { + assert_eq!(live.unwrap(), cached); + } + drop(db); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/src-tauri/src/library_sync_snapshot_commands.rs b/src-tauri/src/library_sync_snapshot_commands.rs index 22286910..1532f30d 100644 --- a/src-tauri/src/library_sync_snapshot_commands.rs +++ b/src-tauri/src/library_sync_snapshot_commands.rs @@ -27,7 +27,7 @@ pub(crate) async fn fetch_library_sync_snapshot( .await } -fn fetch_library_sync_snapshot_blocking( +pub(crate) fn fetch_library_sync_snapshot_blocking( state: &AppState, input: ValidateLibrarySyncHostInput, dashboard: bool, @@ -35,6 +35,8 @@ fn fetch_library_sync_snapshot_blocking( ) -> Result { let (_, _, target) = prepare_library_sync_host_write_for_generation(state, &input, expected_generation)?; + let request = + with_current_library_sync_target(state, &target, |engine| engine.begin_summary_request())?; let parsed: LibrarySyncSnapshotResponse = get_library_sync_host_json_authenticated_for_target( state, if dashboard { @@ -71,9 +73,8 @@ fn fetch_library_sync_snapshot_blocking( printers: parsed.printers, }; - with_current_library_sync_target(state, &target, |engine| { - engine.save_library_sync_host_snapshot(snapshot.clone(), dashboard)?; - Ok(()) + let snapshot = with_current_library_sync_target(state, &target, |engine| { + engine.finish_summary_request(snapshot, dashboard, request) })?; save_library_sync_success( state, diff --git a/src/backend/database_library_sync_cache.rs b/src/backend/database_library_sync_cache.rs index 3fa2b161..027dc41a 100644 --- a/src/backend/database_library_sync_cache.rs +++ b/src/backend/database_library_sync_cache.rs @@ -21,28 +21,79 @@ pub(crate) const DASHBOARD_SNAPSHOT_KEY: &str = "library_sync_cached_dashboard_s pub(crate) const SNAPSHOT_CAPTURED_AT_KEY: &str = "library_sync_snapshot_captured_at"; pub(crate) const CACHED_ACTIVE_LOANS_KEY: &str = "library_sync_cached_active_loans_json"; +pub(crate) const SUMMARY_REQUEST: &str = "library_sync_summary_request"; +pub(crate) const SAVED_SUMMARY_REQUEST: &str = "library_sync_saved_summary_request"; +pub(crate) const SAVED_DASHBOARD_REQUEST: &str = "library_sync_saved_dashboard_request"; +pub(crate) const SUMMARY_KEY: &str = "library_sync_cached_snapshot_json"; + +pub(crate) fn begin_summary_request(conn: &Connection) -> InventoryResult { + Ok(conn.query_row( + "INSERT INTO settings(key,value) VALUES (?1,1) + ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1 + RETURNING CAST(value AS INTEGER)", + [SUMMARY_REQUEST], + |row| row.get(0), + )?) +} + +// Advance only on a successful response. A later request that failed or is +// still pending must not prevent this one from refreshing the offline copy. +fn advance_saved_request(conn: &Connection, key: &str, request: i64) -> InventoryResult { + Ok(conn.execute( + "INSERT INTO settings(key,value) VALUES (?1,?2) + ON CONFLICT(key) DO UPDATE SET value=excluded.value WHERE CAST(settings.value AS INTEGER) < ?2", + rusqlite::params![key, request], + )? == 1) +} + pub(crate) fn save_library_sync_cached_snapshot( conn: &Connection, mut snapshot: LibrarySyncCachedSnapshotRow, dashboard: bool, -) -> InventoryResult<()> { + request: i64, +) -> InventoryResult { let tx = conn.unchecked_transaction()?; let encode = |snapshot: &LibrarySyncCachedSnapshotRow| { serde_json::to_string(snapshot).map_err(|error| InventoryError::Db(error.to_string())) }; - if dashboard { + let publish_summary = advance_saved_request(&tx, SAVED_SUMMARY_REQUEST, request)?; + let publish_dashboard = + dashboard && advance_saved_request(&tx, SAVED_DASHBOARD_REQUEST, request)?; + if publish_dashboard { if snapshot.dashboard_stock.is_some() { set_setting(&tx, DASHBOARD_SNAPSHOT_KEY, &encode(&snapshot)?)?; } else { super::database_settings::delete_setting(&tx, DASHBOARD_SNAPSHOT_KEY)?; } } - snapshot.dashboard_stock = None; - let serialized = encode(&snapshot)?; - set_setting(&tx, "library_sync_cached_snapshot_json", &serialized)?; - set_setting(&tx, SNAPSHOT_CAPTURED_AT_KEY, &snapshot.captured_at)?; + if publish_summary { + let stock = snapshot.dashboard_stock.take(); + set_setting(&tx, SUMMARY_KEY, &encode(&snapshot)?)?; + set_setting(&tx, SNAPSHOT_CAPTURED_AT_KEY, &snapshot.captured_at)?; + snapshot.dashboard_stock = stock; + } + let use_response = if dashboard && snapshot.dashboard_stock.is_some() { + publish_dashboard + } else { + publish_summary + }; + if !use_response { + // Only a superseded reply needs the saved payload. Legacy Hosts have + // no dedicated Dashboard projection, so return the ordinary summary. + let compact = if dashboard { + get_setting(&tx, DASHBOARD_SNAPSHOT_KEY)? + } else { + None + }; + let saved = match compact { + Some(compact) => compact, + None => get_setting(&tx, SUMMARY_KEY)?.ok_or(InventoryError::NotFound)?, + }; + snapshot = + serde_json::from_str(&saved).map_err(|error| InventoryError::Db(error.to_string()))?; + } tx.commit()?; - Ok(()) + Ok(snapshot) } pub(crate) fn save_library_sync_cached_spools( diff --git a/src/backend/database_library_sync_facade.rs b/src/backend/database_library_sync_facade.rs index 58937163..b1f33137 100644 --- a/src/backend/database_library_sync_facade.rs +++ b/src/backend/database_library_sync_facade.rs @@ -233,7 +233,22 @@ impl FilamentDatabase { snapshot: LibrarySyncCachedSnapshotRow, dashboard: bool, ) -> InventoryResult<()> { - save_library_sync_cached_snapshot_row(self.connection(), snapshot, dashboard) + let request = self.begin_summary_request()?; + self.finish_summary_request(snapshot, dashboard, request) + .map(|_| ()) + } + + pub fn begin_summary_request(&self) -> InventoryResult { + super::database_library_sync_cache::begin_summary_request(self.connection()) + } + + pub fn finish_summary_request( + &self, + snapshot: LibrarySyncCachedSnapshotRow, + dashboard: bool, + request: i64, + ) -> InventoryResult { + save_library_sync_cached_snapshot_row(self.connection(), snapshot, dashboard, request) } pub fn save_library_sync_cached_spools( diff --git a/src/backend/database_library_sync_settings.rs b/src/backend/database_library_sync_settings.rs index e5cb864e..c2bca37b 100644 --- a/src/backend/database_library_sync_settings.rs +++ b/src/backend/database_library_sync_settings.rs @@ -14,7 +14,10 @@ use super::database_settings::{delete_setting, get_setting, set_setting}; use super::library_sync_defaults::{default_library_sync_device_name, normalize_library_sync_mode}; const LIBRARY_SYNC_HOST_CACHE_KEYS: &[&str] = &[ - "library_sync_cached_snapshot_json", + super::database_library_sync_cache::SUMMARY_KEY, + super::database_library_sync_cache::SUMMARY_REQUEST, + super::database_library_sync_cache::SAVED_SUMMARY_REQUEST, + super::database_library_sync_cache::SAVED_DASHBOARD_REQUEST, super::database_loan_workspace::CACHED_COUNTS, super::database_library_sync_cache::LOAN_SPOOL_EPOCH, super::database_library_sync_cache::COMPACTED_LOAN_SPOOL_EPOCH, @@ -478,6 +481,98 @@ mod tests { .is_none()); } + #[test] + fn overlapping_summary_responses_keep_each_views_latest_successful_request() { + use super::super::database_library_sync_models::LibrarySyncCachedSnapshotRow; + use LibrarySyncCacheDomain::{DashboardStock, Snapshot}; + let db = FilamentDatabase::open(":memory:").unwrap(); + db.apply_schema().unwrap(); + let library_id = db.get_library_sync_library_id().unwrap(); + let base = LibrarySyncCachedSnapshotRow { + captured_at: "2026-12-01 12:00:00".into(), + app_version: None, + library_id, + device_name: "Host".into(), + sync_mode: "HOST".into(), + inventory: Default::default(), + total_spools: 0, + in_use: 0, + low_stock: 0, + active_loans: 0, + printers: 0, + dashboard_stock: None, + }; + let reply = |order: i64, with_stock: bool| LibrarySyncCachedSnapshotRow { + active_loans: order, + dashboard_stock: with_stock.then(Default::default), + ..base.clone() + }; + let begin = || db.begin_summary_request().unwrap(); + let finish = |id, dashboard, stock| { + db.finish_summary_request(reply(id, stock), dashboard, id) + .unwrap() + }; + let cached = |domain| { + db.get_library_sync_settings_for_domains(&[domain]) + .unwrap() + .cached_snapshot + .unwrap() + }; + let old_dashboard = begin(); + let new_dashboard = begin(); + let plain = begin(); + let _failed = begin(); + finish(plain, false, false); + let compact = finish(new_dashboard, true, true); + assert_eq!(finish(old_dashboard, true, false), compact); + assert_eq!(cached(DashboardStock), compact); + assert_eq!(cached(Snapshot), reply(plain, false)); + + // A legacy Dashboard response has no projection of its own. + let old_legacy = begin(); + let newer_plain = begin(); + let plain_reply = finish(newer_plain, false, false); + assert_eq!(finish(old_legacy, true, false), plain_reply); + assert_eq!(cached(DashboardStock), plain_reply); + + let older_plain = begin(); + let delayed_compact = begin(); + let legacy = begin(); + let legacy_snapshot = finish(legacy, true, false); + assert_eq!(finish(delayed_compact, true, true), legacy_snapshot); + assert_eq!(finish(older_plain, false, false), legacy_snapshot); + assert_eq!(cached(DashboardStock), legacy_snapshot); + assert_eq!(cached(Snapshot), legacy_snapshot); + assert!(get_setting(db.connection(), DASHBOARD_SNAPSHOT_KEY) + .unwrap() + .is_none()); + + let pending = begin(); + let failed_save = begin(); + db.connection().execute_batch( + "CREATE TEMP TRIGGER reject_summary BEFORE INSERT ON settings + WHEN NEW.key='library_sync_cached_snapshot_json' BEGIN SELECT RAISE(ABORT,'test'); END;" + ).unwrap(); + assert!(db + .finish_summary_request(reply(failed_save, true), true, failed_save) + .is_err()); + assert_eq!(cached(DashboardStock), legacy_snapshot); + db.connection() + .execute_batch("DROP TRIGGER reject_summary") + .unwrap(); + let recovered = finish(pending, true, true); + assert_eq!(cached(DashboardStock), recovered); + assert_eq!(cached(Snapshot), reply(pending, false)); + + let mut settings = db.get_library_sync_settings().unwrap(); + settings.mode = "CLIENT".into(); + settings.host_base_url = Some("http://replacement.local".into()); + db.save_library_sync_settings(&settings).unwrap(); + let fresh = begin(); + assert_eq!(finish(fresh, true, true), reply(fresh, true)); + assert_eq!(cached(DashboardStock), reply(fresh, true)); + } + #[test] fn settings_refresh_skips_unneeded_payloads_and_rejects_old_generations() { use LibrarySyncCacheDomain::{Printers, Spools}; diff --git a/src/backend/inventory_engine.rs b/src/backend/inventory_engine.rs index a6f94d36..35e9c827 100644 --- a/src/backend/inventory_engine.rs +++ b/src/backend/inventory_engine.rs @@ -435,6 +435,19 @@ impl InventoryEngine { self.db.save_library_sync_host_snapshot(snapshot, dashboard) } + pub fn begin_summary_request(&self) -> InventoryResult { + self.db.begin_summary_request() + } + + pub fn finish_summary_request( + &self, + snapshot: LibrarySyncCachedSnapshotRow, + dashboard: bool, + request: i64, + ) -> InventoryResult { + self.db.finish_summary_request(snapshot, dashboard, request) + } + pub fn cached_location_spool_page( &self, query: &super::database_location_spools::LocationSpoolQuery,