feat(kanban): resolve divergent queue head
req: sync/010 req: sync/011
This commit is contained in:
@@ -42,11 +42,11 @@ encryption, retention, backup, and deployment policy remain host concerns.
|
|||||||
## Slice 4 — authoritative reconnect and convergence
|
## Slice 4 — authoritative reconnect and convergence
|
||||||
|
|
||||||
- [ ] **User value:** offline and concurrent work reconnects without duplicate mutation, silent loss, stale authorization, or ambiguous conflict.
|
- [ ] **User value:** offline and concurrent work reconnects without duplicate mutation, silent loss, stale authorization, or ambiguous conflict.
|
||||||
- **State:** In progress — one app-owned `move_card` server command validates a durable client command id, applies the authoritative canonical column once, returns the same acknowledgement for an identical retry, rejects id reuse with a different payload, assigns one server sequence, and redelivers that canonical acknowledgement after a real EventSource disconnect/reconnect. Canonical acknowledgements and the next sequence are durably stored in a strict versioned JSON envelope using fsync plus atomic replacement; startup refuses malformed/unknown state, rebuilds the canonical board, and preserves idempotency and event replay across a real process restart. A dedicated opt-in sync route reads one pending IndexedDB command, retries transient failures with capped exponential backoff and randomized jitter, exposes online/offline state plus an accessible manual retry after exhaustion, waits for canonical acknowledgement on the reconnecting transport, and only then removes the durable command; later retry converges without a new local mutation. Canonical payload conflicts are not retried and remain durable with a visible reason. If requested history predates retained events, the stream emits a typed snapshot-required event and the client loads a versioned canonical snapshot. One deterministic rebase rule treats `reorder_card` as converged only when the canonical snapshot already places that card in `done`; it then atomically stores the snapshot/cursor and removes the satisfied command. If a later canonical command instead places the same card in `doing`, the rebase is explicitly `conflicted`, retains the local command and last committed snapshot/cursor unchanged, and exposes the divergent canonical column/reason. Two same-origin tabs coordinate an app-owned expiring IndexedDB lease so only one uploads; the standby exposes its role without issuing a request, and after the leader closes it takes over, receives one canonical acknowledgement/sequence, and removes the queue once. Each activation serializes uploads with one in flight, processes at most two acknowledged commands, exposes the retained durable count when backpressured, and resumes the next bounded run only through the visible retry action. A mixed queue commits and removes its accepted prefix exactly once, then stops on the first permanent rejection with the typed server cause visible, the rejected command plus untouched suffix durable, and blind retry disabled. The IndexedDB v1-to-v2 command migration transactionally adds the explicit target column, records a typed migration receipt, preserves causal order and interaction intent through an interrupted upload, and later drains in the original order. Every command POST now derives its principal, permission, and tenant from the current same-origin session before idempotency lookup or mutation; authenticated mode accepts only app-configured opaque session tokens and fails closed when signed out. Direct cross-tenant and stale-permission command attempts receive typed authorization denial before mutation. IndexedDB v3 additionally indexes every command and lease by the current server-derived tenant/principal partition: switched users enumerate zero foreign commands, issue no foreign replay, cannot export foreign payloads, and the owning account can export then resume its intact queue. Signed-out context lookup fails closed before opening the queue. Canonical snapshots and replayable acknowledgement history now derive the same current session, filter card state and events by tenant before serialization, use tenant-local sequence cursors, and reject signed-out reads. Broader conflict decisions remain.
|
- **State:** In progress — one app-owned `move_card` server command validates a durable client command id, applies the authoritative canonical column once, returns the same acknowledgement for an identical retry, rejects id reuse with a different payload, assigns one server sequence, and redelivers that canonical acknowledgement after a real EventSource disconnect/reconnect. Canonical acknowledgements and the next sequence are durably stored in a strict versioned JSON envelope using fsync plus atomic replacement; startup refuses malformed/unknown state, rebuilds the canonical board, and preserves idempotency and event replay across a real process restart. A dedicated opt-in sync route reads one pending IndexedDB command, retries transient failures with capped exponential backoff and randomized jitter, exposes online/offline state plus an accessible manual retry after exhaustion, waits for canonical acknowledgement on the reconnecting transport, and only then removes the durable command; later retry converges without a new local mutation. Canonical payload conflicts are not retried and remain durable with a visible reason. If requested history predates retained events, the stream emits a typed snapshot-required event and the client loads a versioned canonical snapshot. One deterministic rebase rule treats `reorder_card` as converged only when the canonical snapshot already places that card in `done`; it then atomically stores the snapshot/cursor and removes the satisfied command. If a later canonical command instead places the same card in `doing`, the rebase is explicitly `conflicted`, retains the local command and last committed snapshot/cursor unchanged, and exposes the divergent canonical column/reason. Two same-origin tabs coordinate an app-owned expiring IndexedDB lease so only one uploads; the standby exposes its role without issuing a request, and after the leader closes it takes over, receives one canonical acknowledgement/sequence, and removes the queue once. Each activation serializes uploads with one in flight, processes at most two acknowledged commands, exposes the retained durable count when backpressured, and resumes the next bounded run only through the visible retry action. A mixed queue commits and removes its accepted prefix exactly once, then stops on the first permanent rejection with the typed server cause visible, the rejected command plus untouched suffix durable, and blind retry disabled. The IndexedDB v1-to-v2 command migration transactionally adds the explicit target column, records a typed migration receipt, preserves causal order and interaction intent through an interrupted upload, and later drains in the original order. Every command POST now derives its principal, permission, and tenant from the current same-origin session before idempotency lookup or mutation; authenticated mode accepts only app-configured opaque session tokens and fails closed when signed out. Direct cross-tenant and stale-permission command attempts receive typed authorization denial before mutation. IndexedDB v3 additionally indexes every command and lease by the current server-derived tenant/principal partition: switched users enumerate zero foreign commands, issue no foreign replay, cannot export foreign payloads, and the owning account can export then resume its intact queue. Signed-out context lookup fails closed before opening the queue. Canonical snapshots and replayable acknowledgement history now derive the same current session, filter card state and events by tenant before serialization, use tenant-local sequence cursors, and reject signed-out reads. A divergent snapshot enables one explicit “Use canonical state and continue” action: it removes only the conflicted head, records that choice, retains the ordered suffix, releases uploader ownership, and resumes the suffix through the ordinary bounded sync path. Broader domain-specific merge choices remain.
|
||||||
- **Build:** materialize `hemx-sync` over an integration transport with idempotent server command processing, snapshot/change cursor, durable acknowledgements, bounded ordered replay, current auth checks, rejection/conflict results, canonical replacement, reconnect jitter/backoff, multi-tab coordination, and redacted diagnostics.
|
- **Build:** materialize `hemx-sync` over an integration transport with idempotent server command processing, snapshot/change cursor, durable acknowledgements, bounded ordered replay, current auth checks, rejection/conflict results, canonical replacement, reconnect jitter/backoff, multi-tab coordination, and redacted diagnostics.
|
||||||
- **Refusals:** no default CRDT, transport in core, cached enqueue-time permission, unbounded queue, or silent last-write-wins policy.
|
- **Refusals:** no default CRDT, transport in core, cached enqueue-time permission, unbounded queue, or silent last-write-wins policy.
|
||||||
- **Requirements:** `sync/001-023`, `operations/001-005`, `security/002-005`, `performance/004-005`.
|
- **Requirements:** `sync/001-023`, `operations/001-005`, `security/002-005`, `performance/004-005`.
|
||||||
- **Proof:** `cargo test -p hemx-kanban-example --test browser_e2e idempotent_server_command_is_acknowledged_after_reconnect -- --exact` proves duplicate POST delivery yields one identical canonical acknowledgement/sequence, conflicting id reuse is rejected, EventSource reconnects after a server-closed first stream, the acknowledgement is delivered once with its sequence as event id, and a page reload shows the authoritative card in the canonical column. `cargo test -p hemx-kanban-example --test browser_e2e pending_local_command_uploads_with_bounded_retry_and_is_removed_on_ack -- --exact` proves automatic platform-store upload, one explicit transient failure, bounded exponential backoff plus jitter, reconnect acknowledgement, pending-before-ack ordering, acknowledged removal, canonical board convergence, and non-retried 409 rejection remaining durable with a visible reason. `cargo test -p hemx-kanban-example --test browser_e2e canonical_acknowledgement_survives_server_restart -- --exact` proves the versioned store is materialized before success, a real process restart reloads the same idempotent acknowledgement/sequence, EventSource replays it by id, and canonical board state is rebuilt. `cargo test -p hemx-kanban-example --test browser_e2e exhausted_offline_retries_keep_command_until_later_reconnect -- --exact` proves three bounded retries exhaust into visible offline/manual-recovery state while the command remains durable, then a later retry acknowledges/removes it and converges canonically. `cargo test -p hemx-kanban-example --test browser_e2e missing_history_rebase_converges_without_losing_local_intent -- --exact` proves retained-history gap detection, typed/versioned snapshot fallback, deterministic already-canonical convergence, atomic snapshot/cursor commit with acknowledged removal, then a divergent canonical update producing explicit conflict while the local command and prior committed snapshot/cursor remain intact. `cargo test -p hemx-kanban-example --test browser_e2e two_tabs_coordinate_single_uploader_and_takeover_without_duplicate_application -- --exact` proves one retry-exhausted leader/one explicit standby, zero follower upload before takeover, lease takeover after the leader closes, one canonical sequence/event, one queue removal, and one board application. `cargo test -p hemx-kanban-example --test browser_e2e upload_backpressure_keeps_pending_work_visible_and_recoverable -- --exact` proves one in-flight upload, a two-acknowledgement activation limit, one retained durable command with visible recovery state, and explicit retry draining the final command without loss. `cargo test -p hemx-kanban-example --test browser_e2e mixed_queue_removes_accepted_prefix_and_retains_rejected_tail -- --exact` proves an accepted prefix is canonically applied and removed once before a permanent rejection stops processing, exposes its typed HTTP/server cause, disables blind retry, and leaves both the rejected command and untouched suffix durable. `cargo test -p hemx-kanban-example --test browser_e2e schema_upgrade_preserves_queued_order_and_local_intent -- --exact` proves a three-command v1 queue migrates atomically to the explicit-target v2 schema, remains byte-for-intent ordered after interrupted upload, then receives canonical sequences 1–3 in original order and drains without loss. `cargo test -p hemx-kanban-example --test browser_e2e account_partition_hides_replay_and_export_until_owner_returns -- --exact` proves a beta editor and alpha viewer enumerate zero commands and issue no replay for an alpha owner queue, signed-out startup cannot open a partition, no foreign id/export surface leaks, and only the returning alpha owner can export the intact command then resume it exactly once. `cargo test -p hemx-kanban-example --test browser_e2e canonical_snapshot_and_history_are_tenant_scoped -- --exact` proves alpha and beta sessions receive only their own canonical cards and acknowledgement events with independent sequence 1 cursors, while signed-out snapshot/history reads receive 401 and expose no stream. The completed slice proof must additionally cover broader conflict decisions.
|
- **Proof:** `cargo test -p hemx-kanban-example --test browser_e2e idempotent_server_command_is_acknowledged_after_reconnect -- --exact` proves duplicate POST delivery yields one identical canonical acknowledgement/sequence, conflicting id reuse is rejected, EventSource reconnects after a server-closed first stream, the acknowledgement is delivered once with its sequence as event id, and a page reload shows the authoritative card in the canonical column. `cargo test -p hemx-kanban-example --test browser_e2e pending_local_command_uploads_with_bounded_retry_and_is_removed_on_ack -- --exact` proves automatic platform-store upload, one explicit transient failure, bounded exponential backoff plus jitter, reconnect acknowledgement, pending-before-ack ordering, acknowledged removal, canonical board convergence, and non-retried 409 rejection remaining durable with a visible reason. `cargo test -p hemx-kanban-example --test browser_e2e canonical_acknowledgement_survives_server_restart -- --exact` proves the versioned store is materialized before success, a real process restart reloads the same idempotent acknowledgement/sequence, EventSource replays it by id, and canonical board state is rebuilt. `cargo test -p hemx-kanban-example --test browser_e2e exhausted_offline_retries_keep_command_until_later_reconnect -- --exact` proves three bounded retries exhaust into visible offline/manual-recovery state while the command remains durable, then a later retry acknowledges/removes it and converges canonically. `cargo test -p hemx-kanban-example --test browser_e2e missing_history_rebase_and_user_conflict_resolution_preserve_suffix -- --exact` proves retained-history gap detection, typed/versioned snapshot fallback, deterministic already-canonical convergence, atomic snapshot/cursor commit, then a divergent canonical update producing explicit conflict with a two-command queue; the user’s canonical-state action removes only the conflicted head, retains and resumes the suffix, and reaches canonical convergence with an empty queue. `cargo test -p hemx-kanban-example --test browser_e2e two_tabs_coordinate_single_uploader_and_takeover_without_duplicate_application -- --exact` proves one retry-exhausted leader/one explicit standby, zero follower upload before takeover, lease takeover after the leader closes, one canonical sequence/event, one queue removal, and one board application. `cargo test -p hemx-kanban-example --test browser_e2e upload_backpressure_keeps_pending_work_visible_and_recoverable -- --exact` proves one in-flight upload, a two-acknowledgement activation limit, one retained durable command with visible recovery state, and explicit retry draining the final command without loss. `cargo test -p hemx-kanban-example --test browser_e2e mixed_queue_removes_accepted_prefix_and_retains_rejected_tail -- --exact` proves an accepted prefix is canonically applied and removed once before a permanent rejection stops processing, exposes its typed HTTP/server cause, disables blind retry, and leaves both the rejected command and untouched suffix durable. `cargo test -p hemx-kanban-example --test browser_e2e schema_upgrade_preserves_queued_order_and_local_intent -- --exact` proves a three-command v1 queue migrates atomically to the explicit-target v2 schema, remains byte-for-intent ordered after interrupted upload, then receives canonical sequences 1–3 in original order and drains without loss. `cargo test -p hemx-kanban-example --test browser_e2e account_partition_hides_replay_and_export_until_owner_returns -- --exact` proves a beta editor and alpha viewer enumerate zero commands and issue no replay for an alpha owner queue, signed-out startup cannot open a partition, no foreign id/export surface leaks, and only the returning alpha owner can export the intact command then resume it exactly once. `cargo test -p hemx-kanban-example --test browser_e2e canonical_snapshot_and_history_are_tenant_scoped -- --exact` proves alpha and beta sessions receive only their own canonical cards and acknowledgement events with independent sequence 1 cursors, while signed-out snapshot/history reads receive 401 and expose no stream. The completed slice proof must additionally cover broader domain-specific merge choices.
|
||||||
|
|
||||||
## Slice 5 — local-first multiplayer Kanban milestone
|
## Slice 5 — local-first multiplayer Kanban milestone
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ let uploadsThisRun = 0;
|
|||||||
let uploadedTotal = 0;
|
let uploadedTotal = 0;
|
||||||
let inFlightUploads = 0;
|
let inFlightUploads = 0;
|
||||||
let maxObservedInFlight = 0;
|
let maxObservedInFlight = 0;
|
||||||
|
let activeConflict;
|
||||||
let stopped = false;
|
let stopped = false;
|
||||||
|
|
||||||
class UploadError extends Error {
|
class UploadError extends Error {
|
||||||
@@ -92,7 +93,7 @@ async function pendingCommands(database) {
|
|||||||
return commands.sort((left, right) => left.causal - right.causal);
|
return commands.sort((left, right) => left.causal - right.causal);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function removeAcknowledged(database, commandId) {
|
async function removePendingCommand(database, commandId) {
|
||||||
const transaction = database.transaction(COMMANDS, "readwrite");
|
const transaction = database.transaction(COMMANDS, "readwrite");
|
||||||
const done = transactionDone(transaction);
|
const done = transactionDone(transaction);
|
||||||
transaction.objectStore(COMMANDS).delete(commandId);
|
transaction.objectStore(COMMANDS).delete(commandId);
|
||||||
@@ -178,6 +179,30 @@ function setExportAvailable(available) {
|
|||||||
root.querySelector("[data-sync-export]").disabled = !available;
|
root.querySelector("[data-sync-export]").disabled = !available;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function setConflictResolutionAvailable(available) {
|
||||||
|
root.querySelector("[data-sync-use-canonical]").disabled = !available;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function useCanonicalState() {
|
||||||
|
if (!activeConflict) return;
|
||||||
|
const { command, snapshot } = activeConflict;
|
||||||
|
setConflictResolutionAvailable(false);
|
||||||
|
await removePendingCommand(database, command.id);
|
||||||
|
const remaining = await pendingCommands(database);
|
||||||
|
root.setAttribute("data-sync-conflict-resolution", "used-canonical-state");
|
||||||
|
root.setAttribute("data-sync-resolved-command-id", command.id);
|
||||||
|
root.setAttribute("data-sync-pending-count", String(remaining.length));
|
||||||
|
setExportAvailable(remaining.length > 0);
|
||||||
|
setPhase("conflict-resolved", `Used canonical snapshot ${snapshot.serverSequence}; removed ${command.id} and retained ${remaining.length} queued command${remaining.length === 1 ? "" : "s"}.`);
|
||||||
|
activeConflict = undefined;
|
||||||
|
uploadsThisRun = 0;
|
||||||
|
synchronizing = false;
|
||||||
|
clearTimeout(leaseTimer);
|
||||||
|
await releaseUploaderLease(database);
|
||||||
|
root.setAttribute("data-sync-leader", "false");
|
||||||
|
await continuePendingWork();
|
||||||
|
}
|
||||||
|
|
||||||
async function exportPendingWork() {
|
async function exportPendingWork() {
|
||||||
const commands = await pendingCommands(database);
|
const commands = await pendingCommands(database);
|
||||||
if (commands.length === 0) return;
|
if (commands.length === 0) return;
|
||||||
@@ -305,7 +330,7 @@ async function synchronize(command) {
|
|||||||
if (canonical.commandId !== command.id) return;
|
if (canonical.commandId !== command.id) return;
|
||||||
source.close();
|
source.close();
|
||||||
root.setAttribute("data-sync-pending-before-ack", String((await pendingCommands(database)).length));
|
root.setAttribute("data-sync-pending-before-ack", String((await pendingCommands(database)).length));
|
||||||
await removeAcknowledged(database, command.id);
|
await removePendingCommand(database, command.id);
|
||||||
uploadsThisRun += 1;
|
uploadsThisRun += 1;
|
||||||
uploadedTotal += 1;
|
uploadedTotal += 1;
|
||||||
root.setAttribute("data-sync-uploaded-this-run", String(uploadsThisRun));
|
root.setAttribute("data-sync-uploaded-this-run", String(uploadsThisRun));
|
||||||
@@ -339,17 +364,24 @@ async function synchronize(command) {
|
|||||||
root.setAttribute("data-sync-rebase-reason", decision.reason);
|
root.setAttribute("data-sync-rebase-reason", decision.reason);
|
||||||
root.setAttribute("data-sync-canonical-column", decision.canonicalColumn);
|
root.setAttribute("data-sync-canonical-column", decision.canonicalColumn);
|
||||||
if (decision.kind === "converged") {
|
if (decision.kind === "converged") {
|
||||||
|
activeConflict = undefined;
|
||||||
|
setConflictResolutionAvailable(false);
|
||||||
await commitConvergedRebase(database, snapshot, command);
|
await commitConvergedRebase(database, snapshot, command);
|
||||||
root.setAttribute("data-sync-pending-count", String((await pendingCommands(database)).length));
|
root.setAttribute("data-sync-pending-count", String((await pendingCommands(database)).length));
|
||||||
root.setAttribute("data-sync-ack-sequence", String(snapshot.serverSequence));
|
root.setAttribute("data-sync-ack-sequence", String(snapshot.serverSequence));
|
||||||
setPhase("rebased", `Canonical snapshot ${snapshot.serverSequence} already satisfies ${command.id}; committed and removed the pending command.`);
|
setPhase("rebased", `Canonical snapshot ${snapshot.serverSequence} already satisfies ${command.id}; committed and removed the pending command.`);
|
||||||
root.dispatchEvent(new CustomEvent("kanban:sync-rebased", { detail: { snapshot, command, decision } }));
|
root.dispatchEvent(new CustomEvent("kanban:sync-rebased", { detail: { snapshot, command, decision } }));
|
||||||
} else {
|
} else {
|
||||||
|
activeConflict = { command, snapshot, decision };
|
||||||
|
setConflictResolutionAvailable(true);
|
||||||
setPhase("conflicted", `Canonical snapshot ${snapshot.serverSequence} conflicts with ${command.id} (${decision.reason}); the pending command remains queued.`);
|
setPhase("conflicted", `Canonical snapshot ${snapshot.serverSequence} conflicts with ${command.id} (${decision.reason}); the pending command remains queued.`);
|
||||||
root.dispatchEvent(new CustomEvent("kanban:sync-conflicted", { detail: { snapshot, command, decision } }));
|
root.dispatchEvent(new CustomEvent("kanban:sync-conflicted", { detail: { snapshot, command, decision } }));
|
||||||
}
|
}
|
||||||
synchronizing = false;
|
synchronizing = false;
|
||||||
source.close();
|
source.close();
|
||||||
|
clearTimeout(leaseTimer);
|
||||||
|
await releaseUploaderLease(database);
|
||||||
|
root.setAttribute("data-sync-leader", "false");
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
synchronizing = false;
|
synchronizing = false;
|
||||||
@@ -429,6 +461,7 @@ async function start() {
|
|||||||
root.setAttribute("data-sync-max-observed-in-flight", "0");
|
root.setAttribute("data-sync-max-observed-in-flight", "0");
|
||||||
root.setAttribute("data-sync-pending-count", String(commands.length));
|
root.setAttribute("data-sync-pending-count", String(commands.length));
|
||||||
setExportAvailable(commands.length > 0);
|
setExportAvailable(commands.length > 0);
|
||||||
|
setConflictResolutionAvailable(false);
|
||||||
setManualRetryAvailable(false);
|
setManualRetryAvailable(false);
|
||||||
if (commands.length === 0) {
|
if (commands.length === 0) {
|
||||||
setPhase("idle", "No pending commands.");
|
setPhase("idle", "No pending commands.");
|
||||||
@@ -436,6 +469,10 @@ async function start() {
|
|||||||
}
|
}
|
||||||
const command = validatePending(commands[0]);
|
const command = validatePending(commands[0]);
|
||||||
root.addEventListener("click", async (event) => {
|
root.addEventListener("click", async (event) => {
|
||||||
|
if (event.target.closest("[data-sync-use-canonical]")) {
|
||||||
|
await useCanonicalState();
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (event.target.closest("[data-sync-export]")) {
|
if (event.target.closest("[data-sync-export]")) {
|
||||||
await exportPendingWork();
|
await exportPendingWork();
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
<p role="status" aria-live="polite">Waiting for pending commands.</p>
|
<p role="status" aria-live="polite">Waiting for pending commands.</p>
|
||||||
<button type="button" data-sync-retry>Retry sync now</button>
|
<button type="button" data-sync-retry>Retry sync now</button>
|
||||||
<button type="button" data-sync-export disabled>Export this account's queue</button>
|
<button type="button" data-sync-export disabled>Export this account's queue</button>
|
||||||
|
<button type="button" data-sync-use-canonical disabled>Use canonical state and continue</button>
|
||||||
</section>
|
</section>
|
||||||
<script +src="self.runtime_src" defer></script>
|
<script +src="self.runtime_src" defer></script>
|
||||||
<script src="/sync.js" defer></script>
|
<script src="/sync.js" defer></script>
|
||||||
|
|||||||
@@ -1413,8 +1413,9 @@ async fn exhausted_offline_retries_keep_command_until_later_reconnect() -> WebDr
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn missing_history_rebase_converges_without_losing_local_intent() -> WebDriverResult<()> {
|
async fn missing_history_rebase_and_user_conflict_resolution_preserve_suffix() -> WebDriverResult<()>
|
||||||
// test req: sync/007 req: sync/011 req: sync/020
|
{
|
||||||
|
// test req: sync/007 req: sync/010 req: sync/011 req: sync/020
|
||||||
let app_port = available_port();
|
let app_port = available_port();
|
||||||
let app_addr = format!("127.0.0.1:{app_port}");
|
let app_addr = format!("127.0.0.1:{app_port}");
|
||||||
let mut app_command = Command::new(env!("CARGO_BIN_EXE_hemx-kanban-example"));
|
let mut app_command = Command::new(env!("CARGO_BIN_EXE_hemx-kanban-example"));
|
||||||
@@ -1576,10 +1577,15 @@ async fn missing_history_rebase_converges_without_losing_local_intent() -> WebDr
|
|||||||
const open = indexedDB.open('hemx-kanban-v1');
|
const open = indexedDB.open('hemx-kanban-v1');
|
||||||
open.onsuccess = () => {
|
open.onsuccess = () => {
|
||||||
const tx = open.result.transaction('commands', 'readwrite');
|
const tx = open.result.transaction('commands', 'readwrite');
|
||||||
tx.objectStore('commands').add({
|
const commands = tx.objectStore('commands');
|
||||||
|
commands.add({
|
||||||
id: 'history:3', schemaVersion: 2, accountPartition: 'demo:demo', actor: 'history', session: 'history-session',
|
id: 'history:3', schemaVersion: 2, accountPartition: 'demo:demo', actor: 'history', session: 'history-session',
|
||||||
causal: 3, kind: 'reorder_card', cardId: '2', targetColumn: 'done', eventKind: 'click', key: null,
|
causal: 3, kind: 'reorder_card', cardId: '2', targetColumn: 'done', eventKind: 'click', key: null,
|
||||||
});
|
});
|
||||||
|
commands.add({
|
||||||
|
id: 'history:4', schemaVersion: 2, accountPartition: 'demo:demo', actor: 'history', session: 'history-session',
|
||||||
|
causal: 4, kind: 'reorder_card', cardId: '1', targetColumn: 'done', eventKind: 'click', key: null,
|
||||||
|
});
|
||||||
tx.oncomplete = () => done({ seeded: true });
|
tx.oncomplete = () => done({ seeded: true });
|
||||||
tx.onabort = () => done({ error: tx.error && tx.error.name });
|
tx.onabort = () => done({ error: tx.error && tx.error.name });
|
||||||
};
|
};
|
||||||
@@ -1599,7 +1605,7 @@ async fn missing_history_rebase_converges_without_losing_local_intent() -> WebDr
|
|||||||
.await?;
|
.await?;
|
||||||
let conflicted = driver
|
let conflicted = driver
|
||||||
.execute(
|
.execute(
|
||||||
"const root = document.querySelector('[data-kanban-sync]'); return { phase: root.getAttribute('data-sync-phase'), uploadSequence: root.getAttribute('data-sync-upload-sequence'), snapshotSequence: root.getAttribute('data-sync-snapshot-sequence'), pending: root.getAttribute('data-sync-pending-count'), rebasePending: root.getAttribute('data-sync-rebase-pending-count'), decision: root.getAttribute('data-sync-rebase-decision'), reason: root.getAttribute('data-sync-rebase-reason'), canonicalColumn: root.getAttribute('data-sync-canonical-column'), status: root.querySelector('[role=status]').textContent, error: root.getAttribute('data-sync-error') }",
|
"const root = document.querySelector('[data-kanban-sync]'); return { phase: root.getAttribute('data-sync-phase'), uploadSequence: root.getAttribute('data-sync-upload-sequence'), snapshotSequence: root.getAttribute('data-sync-snapshot-sequence'), pending: root.getAttribute('data-sync-pending-count'), rebasePending: root.getAttribute('data-sync-rebase-pending-count'), decision: root.getAttribute('data-sync-rebase-decision'), reason: root.getAttribute('data-sync-rebase-reason'), canonicalColumn: root.getAttribute('data-sync-canonical-column'), resolutionDisabled: root.querySelector('[data-sync-use-canonical]').disabled, status: root.querySelector('[role=status]').textContent, error: root.getAttribute('data-sync-error') }",
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
@@ -1608,17 +1614,18 @@ async fn missing_history_rebase_converges_without_losing_local_intent() -> WebDr
|
|||||||
assert_eq!(conflicted["phase"], "conflicted", "unexpected conflict state: {conflicted}");
|
assert_eq!(conflicted["phase"], "conflicted", "unexpected conflict state: {conflicted}");
|
||||||
assert_eq!(conflicted["uploadSequence"], "3");
|
assert_eq!(conflicted["uploadSequence"], "3");
|
||||||
assert_eq!(conflicted["snapshotSequence"], "4");
|
assert_eq!(conflicted["snapshotSequence"], "4");
|
||||||
assert_eq!(conflicted["pending"], "1");
|
assert_eq!(conflicted["pending"], "2");
|
||||||
assert_eq!(conflicted["rebasePending"], "1");
|
assert_eq!(conflicted["rebasePending"], "2");
|
||||||
assert_eq!(conflicted["decision"], "conflicted");
|
assert_eq!(conflicted["decision"], "conflicted");
|
||||||
assert_eq!(conflicted["reason"], "canonical-state-diverged");
|
assert_eq!(conflicted["reason"], "canonical-state-diverged");
|
||||||
assert_eq!(conflicted["canonicalColumn"], "doing");
|
assert_eq!(conflicted["canonicalColumn"], "doing");
|
||||||
|
assert_eq!(conflicted["resolutionDisabled"], false);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
conflicted["status"],
|
conflicted["status"],
|
||||||
"Canonical snapshot 4 conflicts with history:3 (canonical-state-diverged); the pending command remains queued."
|
"Canonical snapshot 4 conflicts with history:3 (canonical-state-diverged); the pending command remains queued."
|
||||||
);
|
);
|
||||||
assert!(conflicted["error"].is_null());
|
assert!(conflicted["error"].is_null());
|
||||||
assert_eq!(command_count(&driver).await?, 1);
|
assert_eq!(command_count(&driver).await?, 2);
|
||||||
let preserved = driver
|
let preserved = driver
|
||||||
.execute_async(
|
.execute_async(
|
||||||
r#"
|
r#"
|
||||||
@@ -1626,10 +1633,10 @@ async fn missing_history_rebase_converges_without_losing_local_intent() -> WebDr
|
|||||||
const open = indexedDB.open('hemx-kanban-v1');
|
const open = indexedDB.open('hemx-kanban-v1');
|
||||||
open.onsuccess = () => {
|
open.onsuccess = () => {
|
||||||
const tx = open.result.transaction(['commands', 'meta'], 'readonly');
|
const tx = open.result.transaction(['commands', 'meta'], 'readonly');
|
||||||
const command = tx.objectStore('commands').get('history:3');
|
const commands = tx.objectStore('commands').getAll();
|
||||||
const cursor = tx.objectStore('meta').get('acknowledgementCursor');
|
const cursor = tx.objectStore('meta').get('acknowledgementCursor');
|
||||||
const snapshot = tx.objectStore('meta').get('canonicalSnapshot');
|
const snapshot = tx.objectStore('meta').get('canonicalSnapshot');
|
||||||
tx.oncomplete = () => done({ command: command.result, cursor: cursor.result, snapshot: snapshot.result });
|
tx.oncomplete = () => done({ commands: commands.result.sort((left, right) => left.causal - right.causal), cursor: cursor.result, snapshot: snapshot.result });
|
||||||
tx.onabort = () => done({ error: tx.error && tx.error.name });
|
tx.onabort = () => done({ error: tx.error && tx.error.name });
|
||||||
};
|
};
|
||||||
"#,
|
"#,
|
||||||
@@ -1638,7 +1645,8 @@ async fn missing_history_rebase_converges_without_losing_local_intent() -> WebDr
|
|||||||
.await?
|
.await?
|
||||||
.json()
|
.json()
|
||||||
.clone();
|
.clone();
|
||||||
assert_eq!(preserved["command"]["id"], "history:3");
|
assert_eq!(preserved["commands"][0]["id"], "history:3");
|
||||||
|
assert_eq!(preserved["commands"][1]["id"], "history:4");
|
||||||
assert_eq!(preserved["cursor"], 2);
|
assert_eq!(preserved["cursor"], 2);
|
||||||
assert_eq!(preserved["snapshot"]["serverSequence"], 2);
|
assert_eq!(preserved["snapshot"]["serverSequence"], 2);
|
||||||
|
|
||||||
@@ -1654,6 +1662,41 @@ async fn missing_history_rebase_converges_without_losing_local_intent() -> WebDr
|
|||||||
assert_eq!(divergent_board[1]["title"], "Doing");
|
assert_eq!(divergent_board[1]["title"], "Doing");
|
||||||
assert_eq!(divergent_board[1]["cards"], serde_json::json!(["2"]));
|
assert_eq!(divergent_board[1]["cards"], serde_json::json!(["2"]));
|
||||||
assert_eq!(divergent_board[2]["cards"], serde_json::json!(["1", "3"]));
|
assert_eq!(divergent_board[2]["cards"], serde_json::json!(["1", "3"]));
|
||||||
|
|
||||||
|
driver.goto(&format!("http://{app_addr}/sync-demo")).await?;
|
||||||
|
wait_until(
|
||||||
|
&driver,
|
||||||
|
"return document.querySelector('[data-kanban-sync]')?.getAttribute('data-sync-phase') === 'conflicted'",
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
driver
|
||||||
|
.find(By::Css("[data-sync-use-canonical]"))
|
||||||
|
.await?
|
||||||
|
.click()
|
||||||
|
.await?;
|
||||||
|
wait_until(
|
||||||
|
&driver,
|
||||||
|
"const root = document.querySelector('[data-kanban-sync]'); return root?.getAttribute('data-sync-phase') === 'rebased' && root?.getAttribute('data-sync-pending-count') === '0'",
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let resolved = driver
|
||||||
|
.execute(
|
||||||
|
"const root = document.querySelector('[data-kanban-sync]'); return { resolution: root.getAttribute('data-sync-conflict-resolution'), resolvedCommand: root.getAttribute('data-sync-resolved-command-id'), pending: root.getAttribute('data-sync-pending-count'), ackSequence: root.getAttribute('data-sync-ack-sequence'), canonicalColumn: root.getAttribute('data-sync-canonical-column'), status: root.querySelector('[role=status]').textContent }",
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
.json()
|
||||||
|
.clone();
|
||||||
|
assert_eq!(resolved["resolution"], "used-canonical-state");
|
||||||
|
assert_eq!(resolved["resolvedCommand"], "history:3");
|
||||||
|
assert_eq!(resolved["pending"], "0");
|
||||||
|
assert_eq!(resolved["ackSequence"], "5");
|
||||||
|
assert_eq!(resolved["canonicalColumn"], "done");
|
||||||
|
assert_eq!(
|
||||||
|
resolved["status"],
|
||||||
|
"Canonical snapshot 5 already satisfies history:4; committed and removed the pending command."
|
||||||
|
);
|
||||||
|
assert_eq!(command_count(&driver).await?, 0);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
.await;
|
.await;
|
||||||
|
|||||||
Reference in New Issue
Block a user