fix(kanban): recover malformed commands
req: sync/015
This commit is contained in:
@@ -33,11 +33,11 @@ encryption, retention, backup, and deployment policy remain host concerns.
|
||||
## Slice 3 — durable offline command log
|
||||
|
||||
- [ ] **User value:** an opted-in Kanban mutation remains available after network loss and browser reload without storing DOM patches as truth.
|
||||
- **State:** In progress — the first app-owned `reorder_card` command is transactionally persisted with schema, actor, session, causal id, and app payload before projection; an app-owned service worker caches only the generated shell/resources, and reload restores the projection after the fixture server is stopped and proven unreachable. Native recovery controls export a versioned credential-free command envelope, delete queued commands while preserving actor/causal identity, and reset command data, identity, cache, and registration behind explicit confirmation. Unknown schemas stop with an explicit diagnostic. An injected transactional conflict proves failed persistence neither projects nor emits a durability claim, exposes stage/code without command payload, and remains recoverable through deletion. Quota/corruption-specific recovery, bounded replay, and performance proof remain.
|
||||
- **State:** In progress — the first app-owned `reorder_card` command is transactionally persisted with schema, actor, session, causal id, and app payload before projection; an app-owned service worker caches only the generated shell/resources, and reload restores the projection after the fixture server is stopped and proven unreachable. Native recovery controls export a versioned credential-free command envelope, delete queued commands while preserving actor/causal identity, and reset command data, identity, cache, and registration behind explicit confirmation. Unknown schemas stop with an explicit diagnostic. An injected transactional conflict proves failed persistence neither projects nor emits a durability claim, exposes stage/code without command payload, and remains recoverable through deletion. Malformed current-schema records are rejected field-specifically without partial projection while export/delete recovery remains available. Quota-specific recovery, bounded replay, and performance proof remain.
|
||||
- **Build:** add an optional durable command-log adapter around platform transactional storage; persist versioned command ids and app payload before projection; restore projection after reload; expose queue state, export/delete/reset, quota/corruption failure, and migration refusal.
|
||||
- **Refusals:** no server reconciliation, CRDT, mandatory IndexedDB, credential storage, or policy hidden in core.
|
||||
- **Requirements:** `local/001-004`, `sync/009`, `sync/014-015`, `sync/020`, `security/007`, `performance/006`.
|
||||
- **Proof:** `cargo test -p hemx-wasm --test browser kanban_command_persists_before_projection_and_restores_after_reload -- --exact` proves transactional persist-before-project ordering, app-owned shell caching, current-version replay after a real Firefox reload with the fixture server unreachable, stable identity metadata, and explicit unknown-schema refusal through real WASM. `cargo test -p hemx-wasm --test browser kanban_command_export_delete_and_reset_are_recoverable -- --exact` proves accessible export/delete/reset entry points, versioned credential-free export, confirmation before destructive actions, preserved identity after queue deletion, and fresh identity/baseline projection after reset. `cargo test -p hemx-wasm --test browser kanban_persistence_failure_does_not_project_and_recovers -- --exact` proves transactional failure does not project or emit `kanban:command-persisted`, reports non-payload stage/code diagnostics, and recovers through the ordinary deletion path. The completed slice proof must additionally cover quota and corruption specifically, bound replay, and satisfy the performance budget.
|
||||
- **Proof:** `cargo test -p hemx-wasm --test browser kanban_command_persists_before_projection_and_restores_after_reload -- --exact` proves transactional persist-before-project ordering, app-owned shell caching, current-version replay after a real Firefox reload with the fixture server unreachable, stable identity metadata, and explicit unknown-schema refusal through real WASM. `cargo test -p hemx-wasm --test browser kanban_command_export_delete_and_reset_are_recoverable -- --exact` proves accessible export/delete/reset entry points, versioned credential-free export, confirmation before destructive actions, preserved identity after queue deletion, and fresh identity/baseline projection after reset. `cargo test -p hemx-wasm --test browser kanban_persistence_failure_does_not_project_and_recovers -- --exact` proves transactional failure does not project or emit `kanban:command-persisted`, reports non-payload stage/code diagnostics, and recovers through the ordinary deletion path. `cargo test -p hemx-wasm --test browser kanban_corrupt_command_refuses_projection_and_recovers -- --exact` proves strict current-schema validation, no partial projection, visible non-payload diagnostics, raw versioned export for recovery, and ordinary deletion recovery. The completed slice proof must additionally cover quota specifically, bound replay, and satisfy the performance budget.
|
||||
|
||||
## Slice 4 — authoritative reconnect and convergence
|
||||
|
||||
|
||||
@@ -110,10 +110,26 @@ async function storedCommands(database) {
|
||||
return commands.sort((left, right) => left.causal - right.causal);
|
||||
}
|
||||
|
||||
function invalidCommand(command, field) {
|
||||
const id = command && typeof command.id === "string" && command.id ? command.id : "record";
|
||||
throw new Error(`invalid durable command ${id}: ${field}`);
|
||||
}
|
||||
|
||||
function validate(command) {
|
||||
if (command.schemaVersion !== COMMAND_SCHEMA || command.kind !== "reorder_card" || !command.id || !command.actor || !command.session || !command.cardId || !Number.isSafeInteger(command.causal)) {
|
||||
throw new Error(`unsupported durable command ${command && command.id ? command.id : "record"}`);
|
||||
if (!command || typeof command !== "object") invalidCommand(command, "record");
|
||||
if (!Number.isSafeInteger(command.schemaVersion)) invalidCommand(command, "schemaVersion");
|
||||
if (command.schemaVersion !== COMMAND_SCHEMA) {
|
||||
throw new Error(`unsupported durable command ${command.id || "record"}`);
|
||||
}
|
||||
if (typeof command.id !== "string" || !command.id) invalidCommand(command, "id");
|
||||
if (typeof command.actor !== "string" || !command.actor) invalidCommand(command, "actor");
|
||||
if (typeof command.session !== "string" || !command.session) invalidCommand(command, "session");
|
||||
if (!Number.isSafeInteger(command.causal) || command.causal < 1) invalidCommand(command, "causal");
|
||||
if (command.id !== `${command.actor}:${command.causal}`) invalidCommand(command, "id");
|
||||
if (command.kind !== "reorder_card") invalidCommand(command, "kind");
|
||||
if (typeof command.cardId !== "string" || !command.cardId) invalidCommand(command, "cardId");
|
||||
if (typeof command.eventKind !== "string" || !command.eventKind) invalidCommand(command, "eventKind");
|
||||
if (command.key !== null && typeof command.key !== "string") invalidCommand(command, "key");
|
||||
return command;
|
||||
}
|
||||
|
||||
@@ -138,6 +154,7 @@ function report(root, stage, error) {
|
||||
root.setAttribute("data-kanban-command-error", `${stage}: ${message}`);
|
||||
root.setAttribute("data-kanban-command-error-stage", stage);
|
||||
root.setAttribute("data-kanban-command-error-code", code);
|
||||
announce(root, `Local command ${stage} failed (${code}). Recovery controls remain available.`);
|
||||
root.dispatchEvent(new CustomEvent("kanban:command-error", { detail: { stage, code, message } }));
|
||||
}
|
||||
|
||||
|
||||
+141
-1
@@ -585,7 +585,10 @@ async fn kanban_persistence_failure_does_not_project_and_recovers() -> WebDriver
|
||||
.json()
|
||||
.clone();
|
||||
assert_eq!(failed["order"], "2|1");
|
||||
assert_eq!(failed["notice"], "Moved 1 with click");
|
||||
assert_eq!(
|
||||
failed["notice"],
|
||||
"Local command persist failed (ConstraintError). Recovery controls remain available."
|
||||
);
|
||||
assert_eq!(failed["count"], "1");
|
||||
assert_eq!(failed["stage"], "persist");
|
||||
assert_eq!(failed["code"], "ConstraintError");
|
||||
@@ -633,6 +636,107 @@ async fn kanban_persistence_failure_does_not_project_and_recovers() -> WebDriver
|
||||
result.and(quit)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kanban_corrupt_command_refuses_projection_and_recovers() -> WebDriverResult<()> {
|
||||
// test req: sync/015
|
||||
let workspace = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.expect("workspace root")
|
||||
.to_owned();
|
||||
let (package, bootstrap, rendered) = build_kanban_artifact(&workspace);
|
||||
let runtime = workspace.join("hemx-js/runtime/hemx.js");
|
||||
let server = StaticServer::start(
|
||||
package,
|
||||
runtime,
|
||||
bootstrap,
|
||||
rendered,
|
||||
"kanban_client",
|
||||
Some(kanban_app_assets(&workspace)),
|
||||
);
|
||||
|
||||
let webdriver_port = available_port();
|
||||
let webdriver_addr = format!("127.0.0.1:{webdriver_port}");
|
||||
let mut webdriver = Command::new("geckodriver");
|
||||
webdriver.arg("--port").arg(webdriver_port.to_string());
|
||||
let _webdriver = ProcessGuard::start(webdriver, &webdriver_addr);
|
||||
let mut caps = DesiredCapabilities::firefox();
|
||||
caps.set_headless()?;
|
||||
let driver = WebDriver::new(&format!("http://{webdriver_addr}"), caps).await?;
|
||||
let result = async {
|
||||
driver.goto(&server.url()).await?;
|
||||
wait_until(
|
||||
&driver,
|
||||
"const root = document.querySelector('[data-hemx-root]'); return root.hasAttribute('data-kanban-command-ready') && root.hasAttribute('data-kanban-offline-ready')",
|
||||
)
|
||||
.await?;
|
||||
store_malformed_command(&driver).await?;
|
||||
driver
|
||||
.execute("window.__reloadPending = true; location.reload()", Vec::new())
|
||||
.await?;
|
||||
wait_until(
|
||||
&driver,
|
||||
"const root = document.querySelector('[data-hemx-root]'); return !window.__reloadPending && root.hasAttribute('data-kanban-command-error')",
|
||||
)
|
||||
.await?;
|
||||
let refused = driver
|
||||
.execute(
|
||||
"const root = document.querySelector('[data-hemx-root]'); return { order: [...root.querySelectorAll('[data-key]')].map((node) => node.dataset.key).join('|'), ready: root.hasAttribute('data-kanban-command-ready'), error: root.getAttribute('data-kanban-command-error'), stage: root.getAttribute('data-kanban-command-error-stage'), code: root.getAttribute('data-kanban-command-error-code'), notice: root.querySelector('[role=status]').textContent }",
|
||||
Vec::new(),
|
||||
)
|
||||
.await?
|
||||
.json()
|
||||
.clone();
|
||||
assert_eq!(refused["order"], "1|2");
|
||||
assert_eq!(refused["ready"], false);
|
||||
assert_eq!(
|
||||
refused["error"],
|
||||
"restore: invalid durable command corrupt:1: cardId"
|
||||
);
|
||||
assert_eq!(refused["stage"], "restore");
|
||||
assert_eq!(refused["code"], "Error");
|
||||
assert_eq!(
|
||||
refused["notice"],
|
||||
"Local command restore failed (Error). Recovery controls remain available."
|
||||
);
|
||||
|
||||
let recovery_export = export_commands(&driver).await?.json().clone();
|
||||
assert_eq!(recovery_export["schemaVersion"], 1);
|
||||
assert_eq!(recovery_export["commands"].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(recovery_export["commands"][0]["id"], "corrupt:1");
|
||||
assert_eq!(recovery_export["commands"][0]["cardId"], "");
|
||||
|
||||
driver
|
||||
.execute("window.__reloadPending = true", Vec::new())
|
||||
.await?;
|
||||
let delete = driver
|
||||
.find(By::Css("[data-kanban-command-action='delete']"))
|
||||
.await?;
|
||||
delete.click().await?;
|
||||
delete.click().await?;
|
||||
wait_until(
|
||||
&driver,
|
||||
"const root = document.querySelector('[data-hemx-root]'); return !window.__reloadPending && root.hasAttribute('data-kanban-command-ready') && root.getAttribute('data-kanban-command-count') === '0'",
|
||||
)
|
||||
.await?;
|
||||
let recovered = driver
|
||||
.execute(
|
||||
"const root = document.querySelector('[data-hemx-root]'); return { order: [...root.querySelectorAll('[data-key]')].map((node) => node.dataset.key).join('|'), error: root.getAttribute('data-kanban-command-error') }",
|
||||
Vec::new(),
|
||||
)
|
||||
.await?
|
||||
.json()
|
||||
.clone();
|
||||
assert_eq!(recovered["order"], "1|2");
|
||||
assert!(recovered["error"].is_null());
|
||||
let empty_export = export_commands(&driver).await?.json().clone();
|
||||
assert_eq!(empty_export["commands"].as_array().map(Vec::len), Some(0));
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
let quit = driver.quit().await;
|
||||
result.and(quit)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kanban_reorder_has_pointer_keyboard_focus_and_reduced_motion_parity() -> WebDriverResult<()>
|
||||
{
|
||||
@@ -1044,6 +1148,42 @@ fn fixture_html(rendered: &str, has_app_module: bool) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
async fn store_malformed_command(driver: &WebDriver) -> WebDriverResult<()> {
|
||||
let stored = driver
|
||||
.execute_async(
|
||||
r#"
|
||||
const done = arguments[arguments.length - 1];
|
||||
const open = indexedDB.open('hemx-kanban-v1', 1);
|
||||
open.onerror = () => done({ error: open.error && open.error.name });
|
||||
open.onsuccess = () => {
|
||||
const tx = open.result.transaction('commands', 'readwrite');
|
||||
tx.objectStore('commands').add({
|
||||
id: 'corrupt:1',
|
||||
schemaVersion: 1,
|
||||
actor: 'corrupt',
|
||||
session: 'corrupt',
|
||||
causal: 1,
|
||||
kind: 'reorder_card',
|
||||
cardId: '',
|
||||
eventKind: 'click',
|
||||
key: null,
|
||||
});
|
||||
tx.oncomplete = () => done({ stored: true });
|
||||
tx.onabort = () => done({ error: tx.error && tx.error.name });
|
||||
};
|
||||
"#,
|
||||
Vec::new(),
|
||||
)
|
||||
.await?
|
||||
.json()
|
||||
.clone();
|
||||
assert_eq!(
|
||||
stored["stored"], true,
|
||||
"failed to store malformed command: {stored}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn occupy_next_command_id(driver: &WebDriver) -> WebDriverResult<()> {
|
||||
let occupied = driver
|
||||
.execute_async(
|
||||
|
||||
Reference in New Issue
Block a user