Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/development/QUALITY_GATES.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,10 @@ Paired loan-history CSV uses the protected Host export when supported. A
current Host returns all matching loans from one database snapshot. Older Hosts
and cached history export the rows available in the All view as a snapshot CSV.
When the active-loan read fails, live history supplies current details for its
own rows and the active cache supplies older loans outside that page. Tests cover
own rows and the active cache supplies older loans outside that page.
Concurrent reads publish the active list and the standard history page independently.
A late reply returns the committed rows and capture time. Custom history limits
return a live page without replacing the shared offline history. Tests cover
empty and 10,000-row histories, both directions, and stale replies.

Settings full-backup export serializes portable rows from one SQLite snapshot
Expand Down
15 changes: 2 additions & 13 deletions src-tauri/src/library_sync_cache_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,12 +291,7 @@ pub(crate) fn fetch_cached_library_sync_loans_blocking(
with_current_library_sync_target(state, &target, |engine| {
let settings =
engine.get_library_sync_settings_for_domains(&[LibrarySyncCacheDomain::LoanHistory])?;
Ok(settings
.cached_loans
.map(|cached| LibrarySyncCachedLoanList {
captured_at: cached.captured_at,
rows: cached.rows,
}))
Ok(settings.cached_loans)
})
}

Expand All @@ -318,13 +313,7 @@ pub(crate) fn fetch_cached_library_sync_active_loans_blocking(
engine.get_library_sync_settings_for_domains(&[LibrarySyncCacheDomain::ActiveLoans])?;
// An existing installation might go offline before its first dedicated
// refresh. The caller filters the legacy snapshot to its active rows.
Ok(settings
.cached_active_loans
.or(settings.cached_loans)
.map(|cached| LibrarySyncCachedLoanList {
captured_at: cached.captured_at,
rows: cached.rows,
}))
Ok(settings.cached_active_loans.or(settings.cached_loans))
})
}

Expand Down
43 changes: 25 additions & 18 deletions src-tauri/src/library_sync_cache_refresh.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use crate::backend::filament_database::{
PrinterOverviewRow, SpoolLoanDetailsRow, SpoolWithMasterRow, WishlistItemRow,
};
use crate::backend::filament_database::{PrinterOverviewRow, SpoolWithMasterRow, WishlistItemRow};
use crate::library_sync_host_client::get_library_sync_host_json_authenticated_for_target;
use crate::library_sync_models::{LibrarySyncCachedLoanList, LibrarySyncSpoolSnapshot};
use crate::library_sync_target_guard::{with_current_library_sync_target, LibrarySyncTargetGuard};
Expand Down Expand Up @@ -120,32 +118,41 @@ pub(crate) fn fetch_and_cache_library_sync_printers(
})
}

pub(crate) const LOAN_HISTORY_LIMIT: i64 = 2000;
pub(crate) const ACTIVE_LOAN_LIMIT: i64 = 2500;

pub(crate) fn fetch_and_cache_library_sync_loans(
state: &AppState,
target: &LibrarySyncTargetGuard,
active_only: bool,
limit: i64,
) -> Result<LibrarySyncCachedLoanList, String> {
let limit = limit.clamp(1, ACTIVE_LOAN_LIMIT);
let cache_limit = if active_only {
ACTIVE_LOAN_LIMIT
} else {
LOAN_HISTORY_LIMIT
};
let request = if limit == cache_limit {
Some(with_current_library_sync_target(state, target, |engine| {
engine.begin_loan_request()
})?)
} else {
None
};
let path = format!(
"/api/v1/library/loans?include_returned={}&direction=ALL&limit={}",
!active_only,
limit.clamp(1, 2500)
"/api/v1/library/loans?include_returned={}&direction=ALL&limit={limit}",
!active_only
);
let rows: Vec<SpoolLoanDetailsRow> =
get_library_sync_host_json_authenticated_for_target(state, &path, target)?;
let captured_at = with_current_library_sync_target(state, target, |engine| {
if active_only {
engine.save_library_sync_cached_active_loans(&rows)
} else {
engine.save_library_sync_cached_loans(&rows)
}
})?;
Ok(LibrarySyncCachedLoanList { captured_at, rows })
let rows = get_library_sync_host_json_authenticated_for_target(state, &path, target)?;
with_current_library_sync_target(state, target, |engine| {
engine.finish_loan_request(rows, active_only, request)
})
}

pub(crate) fn refresh_library_sync_loan_cache(state: &AppState, target: &LibrarySyncTargetGuard) {
let _ = fetch_and_cache_library_sync_loans(state, target, true, 2500);
let _ = fetch_and_cache_library_sync_loans(state, target, false, 2000);
let _ = fetch_and_cache_library_sync_loans(state, target, true, ACTIVE_LOAN_LIMIT);
let _ = fetch_and_cache_library_sync_loans(state, target, false, LOAN_HISTORY_LIMIT);
}

pub(crate) fn refresh_library_sync_wishlist_cache(
Expand Down
9 changes: 2 additions & 7 deletions src-tauri/src/library_sync_models.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::backend::filament_database::{
LibraryDomainRevisions, PrinterOverviewRow, SpoolLoanDetailsRow, SpoolWithMasterRow,
WishlistItemRow,
LibraryDomainRevisions, PrinterOverviewRow, SpoolWithMasterRow, WishlistItemRow,
};
use crate::backend::purchase_receipt_metadata::PurchaseReceiptMetadata;
use crate::backend::statistics::{InventoryOverview, StatisticsPeriod, StatisticsTrace};
Expand Down Expand Up @@ -410,11 +409,7 @@ pub(crate) struct LibrarySyncCachedPrinterOverview {
pub(crate) rows: Vec<PrinterOverviewRow>,
}

#[derive(Serialize, Deserialize, Clone)]
pub(crate) struct LibrarySyncCachedLoanList {
pub(crate) captured_at: String,
pub(crate) rows: Vec<SpoolLoanDetailsRow>,
}
pub(crate) use crate::backend::database_library_sync_models::LibrarySyncCachedLoanListRow as LibrarySyncCachedLoanList;

#[derive(Serialize, Deserialize, Clone)]
pub(crate) struct LibrarySyncCachedWishlistList {
Expand Down
7 changes: 4 additions & 3 deletions src-tauri/src/library_sync_read_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use crate::backend::statistics::{
};
use crate::library_sync_blocking_executor::run_library_sync_blocking;
use crate::library_sync_cache_refresh::{
fetch_and_cache_library_sync_loans, fetch_and_cache_library_sync_spools,
fetch_and_cache_library_sync_loans, fetch_and_cache_library_sync_spools, ACTIVE_LOAN_LIMIT,
LOAN_HISTORY_LIMIT,
};
use crate::library_sync_command_support::{
encode_library_sync_path_segment, library_sync_host_input, prepare_library_sync_host_checked,
Expand Down Expand Up @@ -276,7 +277,7 @@ pub(crate) fn fetch_library_sync_loans_blocking(
host,
expected_generation,
false,
input.limit.unwrap_or(2000),
input.limit.unwrap_or(LOAN_HISTORY_LIMIT),
)
}

Expand All @@ -298,7 +299,7 @@ pub(crate) fn fetch_library_sync_active_loans_blocking(
input: ValidateLibrarySyncHostInput,
expected_generation: Option<u64>,
) -> Result<LibrarySyncCachedLoanList, String> {
fetch_loan_snapshot_blocking(state, input, expected_generation, true, 2500)
fetch_loan_snapshot_blocking(state, input, expected_generation, true, ACTIVE_LOAN_LIMIT)
}

fn fetch_loan_snapshot_blocking(
Expand Down
155 changes: 153 additions & 2 deletions src-tauri/src/library_sync_read_commands/tests/loan_workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fn late_loan_snapshots_cannot_repopulate_caches_after_a_b_a() {
let request = if active_only {
"GET /api/v1/library/loans?include_returned=false&direction=ALL&limit=2500 "
} else {
"GET /api/v1/library/loans?include_returned=true&direction=ALL&limit=2500 "
"GET /api/v1/library/loans?include_returned=true&direction=ALL&limit=2000 "
};
let (tx, rx) = std::sync::mpsc::channel::<std::path::PathBuf>();
let (url, server) = spawn_fake_host_with(
Expand Down Expand Up @@ -52,7 +52,7 @@ fn late_loan_snapshots_cannot_repopulate_caches_after_a_b_a() {
),
Some(generation),
active_only,
2500,
if active_only { 2500 } else { 2000 },
)
};
tx.send(path.clone()).unwrap();
Expand All @@ -68,6 +68,157 @@ fn late_loan_snapshots_cannot_repopulate_caches_after_a_b_a() {
}
}

fn loan_row(status: &str) -> crate::backend::filament_database::SpoolLoanDetailsRow {
serde_json::from_value(json!({"loan":{
"id":"loan","spool_id":"roll","borrower_name":"Ada","counterparty_name":"Ada",
"loan_direction":"OUTBOUND","loan_status":status,"grams_out":500,"lent_at":"2026-04-01"
}}))
.unwrap()
}

#[test]
fn delayed_loan_lists_return_the_committed_snapshot_after_a_return_refresh() {
use crate::library_sync_read_commands::fetch_loan_snapshot_blocking;
for (active, limit, route) in [
(
true,
2500,
"GET /api/v1/library/loans?include_returned=false&direction=ALL&limit=2500 ",
),
(
false,
2000,
"GET /api/v1/library/loans?include_returned=true&direction=ALL&limit=2000 ",
),
] {
let (tx, rx) = std::sync::mpsc::channel::<std::path::PathBuf>();
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: json!([loan_row("ACTIVE")]).to_string(),
},
],
move |line| {
if line.starts_with(route) {
let db = FilamentDatabase::open(rx.recv().unwrap()).unwrap();
if active {
db.save_library_sync_cached_active_loans(&[]).unwrap();
} else {
db.save_library_sync_cached_loans(&[loan_row("RETURNED")])
.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_loan_snapshot_blocking(
&state,
crate::library_sync_command_support::library_sync_host_input(
&url,
Some("library-test"),
),
Some(generation),
active,
limit,
)
.unwrap();
server.join().unwrap();
let saved = db.get_library_sync_settings().unwrap();
let offline = if active {
saved.cached_active_loans
} else {
saved.cached_loans
}
.unwrap();
assert_eq!(json!(live), json!(offline));
if active {
assert!(live.rows.is_empty());
} else {
assert_eq!(live.rows.len(), 1);
assert_eq!(live.rows[0].loan.loan_status, "RETURNED");
}
drop(db);
std::fs::remove_file(path).unwrap();
}
}

#[test]
fn custom_history_read_preserves_the_offline_window() {
let (url, server) = spawn_fake_host(vec![
FakeHostResponse {
expected_request_prefix: "GET /api/v1/health ",
status: "200 OK",
body: fake_health(),
},
FakeHostResponse {
expected_request_prefix:
"GET /api/v1/library/loans?include_returned=true&direction=ALL&limit=1 ",
status: "200 OK",
body: json!([loan_row("RETURNED")]).to_string(),
},
]);
let (state, path) = fake_host_state(&url);
let db = FilamentDatabase::open(&path).unwrap();
let mut older = loan_row("RETURNED");
older.loan.id = "older".into();
db.save_library_sync_cached_loans(&[loan_row("RETURNED"), older])
.unwrap();
let initial = db.get_library_sync_settings().unwrap();
let read = super::super::fetch_loan_snapshot_blocking(
&state,
crate::library_sync_command_support::library_sync_host_input(&url, Some("library-test")),
Some(initial.target_generation),
false,
1,
)
.unwrap();
server.join().unwrap();
assert_eq!(read.rows.len(), 1);
assert_eq!(
json!(db.get_library_sync_settings().unwrap().cached_loans),
json!(initial.cached_loans)
);
drop(db);
std::fs::remove_file(path).unwrap();
}

#[test]
fn active_and_history_windows_publish_independently_and_failed_saves_do_not_advance() {
let db = FilamentDatabase::open(":memory:").unwrap();
db.apply_schema().unwrap();
let active = db.begin_loan_request().unwrap();
let history = db.begin_loan_request().unwrap();
db.finish_loan_request(vec![loan_row("RETURNED")], false, Some(history))
.unwrap();
let pending = db.begin_loan_request().unwrap();
db.connection().execute_batch("CREATE TEMP TRIGGER fail_active BEFORE INSERT ON settings
WHEN NEW.key = 'library_sync_cached_active_loans_json' BEGIN SELECT RAISE(ABORT,'interrupted'); END;").unwrap();
assert!(db.finish_loan_request(vec![], true, Some(pending)).is_err());
db.connection()
.execute_batch("DROP TRIGGER fail_active")
.unwrap();
let live = db
.finish_loan_request(vec![loan_row("ACTIVE")], true, Some(active))
.unwrap();
assert_eq!(live.rows.len(), 1);
let saved = db.get_library_sync_settings().unwrap();
assert_eq!(json!(saved.cached_active_loans), json!(live));
assert_eq!(
saved.cached_loans.unwrap().rows[0].loan.loan_status,
"RETURNED"
);
}

#[test]
fn loan_workspace_counts_keep_an_offline_copy_and_reject_a_b_a() {
let mut health: serde_json::Value = serde_json::from_str(&fake_health()).unwrap();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,7 @@ fn stale_workspace_generation_sends_no_host_read_or_purchase_request() {
super::super::fetch_library_sync_catalog_masters_blocking(&state, catalog, generation)
.expect_err("stale catalog"),
super::super::fetch_library_sync_active_loans_blocking(&state, input(), generation)
.err()
.expect("stale active loans"),
.expect_err("stale active loans"),
crate::inventory_create_commands::ensure_dashboard_purchase_blocking(
&state,
suggestion(),
Expand Down
Loading
Loading