-
Notifications
You must be signed in to change notification settings - Fork 240
feat(offline-transactions): confirm writes off the serial drain path (confirmWrite hook) #1603
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TomasGonzalez
wants to merge
1
commit into
TanStack:main
Choose a base branch
from
TomasGonzalez:feat/offline-transactions-confirm-write
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| --- | ||
| "@tanstack/offline-transactions": minor | ||
| --- | ||
|
|
||
| Add an opt-in `OfflineConfig.confirmWrite` hook that holds optimistic state across the post-commit confirmation window **off** the serial drain path. | ||
|
|
||
| Previously the only way to keep a row painted until an async sync stream (e.g. ElectricSQL's `awaitTxId`) echoed the write back was to `await` that confirmation inside the `mutationFn` — which serializes the whole outbox and collapses drain throughput. `confirmWrite` runs after the write commits and its outbox entry is removed, while the library keeps the just-committed mutations' optimistic overlay painted (reusing the same hold primitive as `restoreOptimisticState`) and releases it when the hook settles. The serial chain still serializes the POSTs (preserving create-then-update ordering); only the confirmation moved off it. | ||
|
|
||
| The hook is never expected to roll back — the write is already durably committed, so a rejection just drops the overlay early (a possible brief flicker), never data loss. A `maxConfirmationHolds` cap (default 1000) bounds concurrent holds to avoid O(n²) optimistic recompute on a large, fast drain, and `getActiveConfirmationHoldCount()` exposes the live count for diagnostics. | ||
|
|
||
| As part of this, the `mutationFn`'s return value is now threaded through to the completion promise and to `confirmWrite` (e.g. a server-assigned txid); previously it was awaited and discarded. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
packages/offline-transactions/src/executor/OptimisticHold.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import { createTransaction } from '@tanstack/db' | ||
| import type { Collection, PendingMutation, Transaction } from '@tanstack/db' | ||
|
|
||
| /** | ||
| * A standalone, never-committed transaction whose only job is to keep an | ||
| * optimistic overlay painted on the affected collections for a bounded window. | ||
| * | ||
| * This is the same primitive `restoreOptimisticState` uses to re-show pending | ||
| * writes after a reload. It is factored out here so the post-commit | ||
| * confirmation window (see `OfflineConfig.confirmWrite`) can reuse it without | ||
| * duplicating the `_state` bookkeeping. | ||
| */ | ||
| export interface OptimisticHold { | ||
| /** The underlying hold transaction. Never auto-commits. */ | ||
| transaction: Transaction | ||
| /** | ||
| * Tear the hold down. Idempotent. By default marks the hold `completed` (the | ||
| * affected rows then render from synced data); pass `{ rollback: true }` to | ||
| * discard the optimistic overlay instead. | ||
| */ | ||
| release: (options?: { rollback?: boolean }) => void | ||
| } | ||
|
|
||
| /** | ||
| * Create an optimistic hold for `mutations` and register it on every touched | ||
| * collection synchronously (before returning), so the overlay is painted with | ||
| * no gap. The returned `release` removes it again. | ||
| * | ||
| * Mirrors the lifecycle the offline executor already drives for restoration | ||
| * transactions: `setState("completed")` + delete + `recomputeOptimisticState` | ||
| * on a normal release, or `rollback()` to discard. | ||
| */ | ||
| export function createOptimisticHold( | ||
| mutations: Array<PendingMutation>, | ||
| options: { id?: string } = {}, | ||
| ): OptimisticHold { | ||
| // `autoCommit: false` + an inert mutationFn means it never POSTs or settles on | ||
| // its own — the caller drives its lifecycle by hand via `release`. | ||
| const transaction = createTransaction({ | ||
| ...(options.id === undefined ? {} : { id: options.id }), | ||
| autoCommit: false, | ||
| mutationFn: async () => {}, | ||
| }) | ||
|
|
||
| // It never commits, so `isPersisted` never resolves through the normal flow; | ||
| // swallow so a stray rejection on teardown can't surface as an unhandled | ||
| // rejection. Mirrors `restoreOptimisticState`. | ||
| transaction.isPersisted.promise.catch(() => { | ||
| // Intentionally ignored - holds are torn down via `release`, not commit. | ||
| }) | ||
|
|
||
| transaction.applyMutations(mutations) | ||
|
|
||
| // Register with each affected collection's state manager. Dedup by collection | ||
| // reference (the same collection can be touched by several mutations). | ||
| const touchedCollections = new Set<Collection<any, any, any, any, any>>() | ||
| for (const mutation of mutations) { | ||
| // Defensive check for corrupted deserialized data | ||
| // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | ||
| if (!mutation.collection) { | ||
| continue | ||
| } | ||
| if (touchedCollections.has(mutation.collection)) { | ||
| continue | ||
| } | ||
| touchedCollections.add(mutation.collection) | ||
| mutation.collection._state.transactions.set(transaction.id, transaction) | ||
| // `recomputeOptimisticState(true)` forces the recompute through even when a | ||
| // sync commit is in flight (the "triggered by user action" path), so the | ||
| // overlay always applies. | ||
| mutation.collection._state.recomputeOptimisticState(true) | ||
| } | ||
|
|
||
| let released = false | ||
| const release = ({ rollback = false }: { rollback?: boolean } = {}): void => { | ||
| if (released) { | ||
| return | ||
| } | ||
| released = true | ||
|
|
||
| if (rollback) { | ||
| // `rollback()` removes the transaction from its collections itself. | ||
| transaction.rollback() | ||
| return | ||
| } | ||
|
|
||
| // Mark completed so `recomputeOptimisticState` stops considering it; this | ||
| // also splices the tx out of @tanstack/db's global transaction registry, so | ||
| // the hold can never leak there. The rows now render from synced data. | ||
| transaction.setState(`completed`) | ||
| for (const collection of touchedCollections) { | ||
| collection._state.transactions.delete(transaction.id) | ||
| collection._state.recomputeOptimisticState(false) | ||
| } | ||
| } | ||
|
|
||
| return { transaction, release } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
confirmWriteis silently skipped when holds are capped or hold creation fails.At Line 202 and Line 213, the function returns before invoking
confirmWrite. That breaks the post-commit hook contract and makes behavior depend on hold availability instead of hook configuration. Also, Line 201 usesmaxConfirmationHoldswithout normalizingNaN/negative values, which can bypass or disable the cap unexpectedly.Suggested patch
Also applies to: 237-270
🤖 Prompt for AI Agents