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: 5 additions & 0 deletions docs/development/QUALITY_GATES.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,11 @@ 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.

Paired printer overview reads share one publication order across page loads,
post-write refreshes and printer onboarding confirmation. Native tests delay a
reply while a later request starts, publishes, or the pairing switches A–B–A,
then check the returned rows and the offline printer list.

The [packaged multiprocess runner](../../scripts/run-packaged-host-client-e2e.mjs)
launches the installed candidate as isolated Host and Client processes. It
checks offline failure, same-Host restart and session renewal, credential
Expand Down
28 changes: 17 additions & 11 deletions src-tauri/src/library_sync_cache_refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,23 @@ pub(crate) fn refresh_library_sync_printer_cache(
state: &AppState,
target: &LibrarySyncTargetGuard,
) {
let rows: Result<Vec<PrinterOverviewRow>, String> =
get_library_sync_host_json_authenticated_for_target(
state,
"/api/v1/library/printers",
target,
);
if let Ok(rows) = rows {
let _ = with_current_library_sync_target(state, target, |engine| {
engine.save_library_sync_cached_printers(&rows)
});
}
let _ = fetch_and_cache_library_sync_printers(state, target);
}

pub(crate) fn fetch_and_cache_library_sync_printers(
state: &AppState,
target: &LibrarySyncTargetGuard,
) -> Result<Vec<PrinterOverviewRow>, String> {
let request =
with_current_library_sync_target(state, target, |engine| engine.begin_printer_request())?;
let rows = get_library_sync_host_json_authenticated_for_target(
state,
"/api/v1/library/printers",
target,
)?;
with_current_library_sync_target(state, target, |engine| {
engine.finish_printer_request(rows, request)
})
}

pub(crate) fn fetch_and_cache_library_sync_loans(
Expand Down
20 changes: 17 additions & 3 deletions src-tauri/src/library_sync_printer_write_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,19 +269,33 @@ pub(crate) fn create_library_sync_host_printer_blocking(
Err(HostWriteFailure::Unconfirmed(_)) if input.onboarding_generation.is_some() => {
// The Host may already have committed. Only fresh rows from the original
// target can confirm this generated identity. Never replay the upsert.
let request = crate::library_sync_target_guard::with_current_library_sync_target(
state,
&target,
|engine| Ok(engine.begin_printer_request().ok()),
);
let Ok(request) = request else {
return Ok(false);
};
let rows = get_library_sync_host_json_authenticated_for_target::<
Vec<PrinterOverviewRow>,
>(state, "/api/v1/library/printers", &target);
let Ok(rows) = rows else { return Ok(false) };
let found = rows.iter().any(|row| {
let matches_printer = |row: &PrinterOverviewRow| {
row.printer.id == id && row.printer.name == name && row.printer.model == model
});
};
let found = rows.iter().any(matches_printer);
return Ok(
crate::library_sync_target_guard::with_current_library_sync_target(
state,
&target,
|engine| {
let _ = engine.save_library_sync_cached_printers(&rows);
if let Some(request) = request
&& let Ok(latest) = engine.finish_printer_request(rows, request)
{
return Ok(latest.iter().any(matches_printer));
}
// Local cache failure cannot invalidate direct Host evidence.
Ok(found)
},
)
Expand Down
12 changes: 3 additions & 9 deletions src-tauri/src/library_sync_read_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,15 +172,8 @@ fn fetch_library_sync_printer_overview_blocking(
) -> Result<Vec<PrinterOverviewRow>, String> {
let (_, health, target) =
prepare_library_sync_host_write_for_generation(state, &input, expected_generation)?;
let rows: Vec<PrinterOverviewRow> = get_library_sync_host_json_authenticated_for_target(
state,
"/api/v1/library/printers",
&target,
)?;

with_current_library_sync_target(state, &target, |engine| {
engine.save_library_sync_cached_printers(&rows)
})?;
let rows =
crate::library_sync_cache_refresh::fetch_and_cache_library_sync_printers(state, &target)?;
save_library_sync_success(
state,
&target,
Expand Down Expand Up @@ -733,6 +726,7 @@ mod tests {
mod loan_workspace;
mod loan_writes;
mod location_spools;
mod printer_overview;
mod printer_picker;
mod purchase_queue;
mod spool_detail;
Expand Down
80 changes: 80 additions & 0 deletions src-tauri/src/library_sync_read_commands/tests/printer_overview.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use super::super::fetch_library_sync_printer_overview_blocking;
use super::{fake_health, fake_host_state, spawn_fake_host_with, FakeHostResponse};
use crate::backend::filament_database::{FilamentDatabase, PrinterOverviewRow};
use crate::library_sync_command_support::library_sync_host_input;
use serde_json::json;

fn printers(name: &str) -> Vec<PrinterOverviewRow> {
serde_json::from_value(json!([{
"printer": {"id":"printer-1", "name":name, "model":"P1S", "created_at":"", "updated_at":""},
"usage": {"total_jobs":0, "successful_jobs":0, "failed_jobs":0, "total_used_g":0},
"slots":[]
}]))
.unwrap()
}

#[test]
fn delayed_printer_overviews_follow_the_last_successful_publication_for_the_same_pairing() {
let route = "GET /api/v1/library/printers ";
for (switch_target, publish, expected) in [
(false, false, "First"),
(false, true, "Updated"),
(true, true, "Updated"),
] {
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: serde_json::to_string(&printers("First")).unwrap(),
},
],
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_printer_request().unwrap();
if publish {
db.finish_printer_request(printers("Updated"), 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_printer_overview_blocking(
&state,
library_sync_host_input(&url, Some("library-test")),
Some(generation),
);
server.join().unwrap();
if switch_target {
assert!(live.unwrap_err().contains("common.invalid_request"));
} else {
assert_eq!(live.unwrap()[0].printer.name, expected);
}
let offline = db
.get_library_sync_settings()
.unwrap()
.cached_printers
.unwrap();
assert_eq!(offline.rows[0].printer.name, expected);
drop(db);
std::fs::remove_file(path).unwrap();
}
}
37 changes: 26 additions & 11 deletions src/backend/database_library_sync_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,15 @@ pub(crate) const SAVED_SUMMARY_REQUEST: &str = "library_sync_saved_summary_reque
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<i64> {
pub(crate) const PRINTER_REQUEST: &str = "library_sync_printer_request";
pub(crate) const SAVED_PRINTER_REQUEST: &str = "library_sync_saved_printer_request";

pub(crate) fn begin_cache_request(conn: &Connection, key: &str) -> InventoryResult<i64> {
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],
[key],
|row| row.get(0),
)?)
}
Expand Down Expand Up @@ -239,15 +242,27 @@ pub(crate) fn get_library_sync_cached_locations(

pub(crate) fn save_library_sync_cached_printers(
conn: &Connection,
rows: &[PrinterOverviewRow],
) -> InventoryResult<()> {
let payload = LibrarySyncCachedPrinterOverviewRow {
captured_at: sqlite_now(conn)?,
rows: rows.to_vec(),
};
let serialized =
serde_json::to_string(&payload).map_err(|error| InventoryError::Db(error.to_string()))?;
set_setting(conn, "library_sync_cached_printers_json", &serialized)
rows: Vec<PrinterOverviewRow>,
request: i64,
) -> InventoryResult<Vec<PrinterOverviewRow>> {
const KEY: &str = "library_sync_cached_printers_json";
let tx = conn.unchecked_transaction()?;
let payload: LibrarySyncCachedPrinterOverviewRow =
if advance_saved_request(&tx, SAVED_PRINTER_REQUEST, request)? {
let payload = LibrarySyncCachedPrinterOverviewRow {
captured_at: sqlite_now(&tx)?,
rows,
};
let serialized = serde_json::to_string(&payload)
.map_err(|error| InventoryError::Db(error.to_string()))?;
set_setting(&tx, KEY, &serialized)?;
payload
} else {
let saved = get_setting(&tx, KEY)?.ok_or(InventoryError::NotFound)?;
serde_json::from_str(&saved).map_err(|error| InventoryError::Db(error.to_string()))?
};
tx.commit()?;
Ok(payload.rows)
}

pub(crate) fn save_library_sync_cached_loans(
Expand Down
24 changes: 22 additions & 2 deletions src/backend/database_library_sync_facade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,10 @@ impl FilamentDatabase {
}

pub fn begin_summary_request(&self) -> InventoryResult<i64> {
super::database_library_sync_cache::begin_summary_request(self.connection())
super::database_library_sync_cache::begin_cache_request(
self.connection(),
super::database_library_sync_cache::SUMMARY_REQUEST,
)
}

pub fn finish_summary_request(
Expand Down Expand Up @@ -291,7 +294,24 @@ impl FilamentDatabase {
&self,
rows: &[PrinterOverviewRow],
) -> InventoryResult<()> {
save_library_sync_cached_printer_rows(self.connection(), rows)
let request = self.begin_printer_request()?;
self.finish_printer_request(rows.to_vec(), request)
.map(|_| ())
}

pub fn begin_printer_request(&self) -> InventoryResult<i64> {
super::database_library_sync_cache::begin_cache_request(
self.connection(),
super::database_library_sync_cache::PRINTER_REQUEST,
)
}

pub fn finish_printer_request(
&self,
rows: Vec<PrinterOverviewRow>,
request: i64,
) -> InventoryResult<Vec<PrinterOverviewRow>> {
save_library_sync_cached_printer_rows(self.connection(), rows, request)
}

pub fn save_library_sync_cached_loans(
Expand Down
2 changes: 2 additions & 0 deletions src/backend/database_library_sync_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ 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] = &[
super::database_library_sync_cache::PRINTER_REQUEST,
super::database_library_sync_cache::SAVED_PRINTER_REQUEST,
super::database_library_sync_cache::SUMMARY_KEY,
super::database_library_sync_cache::SUMMARY_REQUEST,
super::database_library_sync_cache::SAVED_SUMMARY_REQUEST,
Expand Down
12 changes: 12 additions & 0 deletions src/backend/inventory_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,18 @@ impl InventoryEngine {
self.db.save_library_sync_cached_printers(rows)
}

pub fn begin_printer_request(&self) -> InventoryResult<i64> {
self.db.begin_printer_request()
}

pub fn finish_printer_request(
&self,
rows: Vec<PrinterOverviewRow>,
request: i64,
) -> InventoryResult<Vec<PrinterOverviewRow>> {
self.db.finish_printer_request(rows, request)
}

pub fn save_library_sync_cached_loans(
&self,
rows: &[SpoolLoanDetailsRow],
Expand Down
Loading