authoravatarclover caruso<git@paperclover.net>2026-11-11 09:56:11-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-11 11:13:55-08:00
logfe2445675b26022550a41a0f80dc6f3cc32b1aef
tree6854f9a104b3e05c17be9ae57b7eab9168eba760
parentcf0988729b9a3695215b40bc5090ed5cebde810e
signature Signed by SSH key SHA256:cOKiuRFOeSRxne6EWgHtdQQSlBxjOXm2hOCFnCdLQbQ

fix: attribute helper restores and refetches to their call

Optimistic helpers were created once per channel and registered their restores straight onto the channel's rollback list, uncounted. A call retired its rollbacks by splicing its count from the front of that list, so a succeeded call left its helper restores behind (or retired another call's entry in their place), and a later failure on the same key replayed them, putting back the value from before the confirmed write. The throw, no-op snapshot and debounced paths spliced by count from the end with the same blind spot. Refetches were shared the same way. The shared helpers' refetch dedupe was never cleared, so while a listener kept the channel alive only the first call refetched a query, and a settling call ran every queued call's refetches before their writes landed, leaving the cache stale after the later write succeeded. Each call now creates its own helpers and owns its restores and refetches. Success drops them with the call; failure runs the restores of the failed, queued and pending debounced calls newest first, then the refetches of the failed and cancelled calls; a throw, a no-op snapshot and a superseded debounced call run only their own restores. The public API is unchanged. Assisted-by: claude-opus-5.5

4 files changed, 323 insertions(+), 108 deletions(-)

jsr.json+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1{1{
2 "name": "@clo/react-mutation",2 "name": "@clo/react-mutation",
3 "version": "3.0.3",3 "version": "3.0.4",
4 "exports": {4 "exports": {
5 ".": "./src/mod.ts",5 ".": "./src/mod.ts",
6 "./tanstack-query": "./src/tanstack-query.ts",6 "./tanstack-query": "./src/tanstack-query.ts",
readme.changes.md+16
...@@ -1,5 +1,21 @@...@@ -1,5 +1,21 @@
1# notable changes in React Mutation1# notable changes in React Mutation
22
3## v3.0.4
4
5### bugfixes
6
7- resolve a failed call replaying the optimistic helper restores of an earlier
8 call on the same key that had succeeded, putting back the value from before
9 the confirmed write
10- resolve a successful call that also used optimistic helpers retiring another
11 call's `onRestore` callbacks instead of its own
12- resolve helper updates not being rolled back when `optimistic` throws, when
13 `snapshot` skips a no-op call, or when a debounced call is superseded
14- resolve helpers refetching a query only for the first call on a key while a
15 `useMutate` stays subscribed to it
16- resolve a queued call's refetches running when the call ahead of it settled,
17 before its own write, which left the cache stale after both succeeded
18
3## v3.0.319## v3.0.3
420
5### bugfixes21### bugfixes
src/mutation.ts+73-105
...@@ -124,8 +124,8 @@ interface PendingDebouncedState<Args extends unknown[], Result, Context> {...@@ -124,8 +124,8 @@ interface PendingDebouncedState<Args extends unknown[], Result, Context> {
124 args: Args;124 args: Args;
125 /** Context captured when the most recent call was allowed */125 /** Context captured when the most recent call was allowed */
126 context: Context;126 context: Context;
127 /** Number of rollbacks the most recent call added */127 /** Restores registered by the most recent call */
128 rollbackCount: number;128 rollbacks: Array<() => void>;
129 /** All pending promises from all superseded calls */129 /** All pending promises from all superseded calls */
130 pending: Array<{130 pending: Array<{
131 resolve: (result: Result) => void;131 resolve: (result: Result) => void;
...@@ -133,6 +133,8 @@ interface PendingDebouncedState<Args extends unknown[], Result, Context> {...@@ -133,6 +133,8 @@ interface PendingDebouncedState<Args extends unknown[], Result, Context> {
133 }>;133 }>;
134 /** Success callbacks from the most recent call */134 /** Success callbacks from the most recent call */
135 onSuccess: Array<(result: Result) => void>;135 onSuccess: Array<(result: Result) => void>;
136 /** Refetch callbacks from the most recent call */
137 refetches: Array<() => Promise<void>>;
136 /** Initial snapshot before any debounced calls (for no-op detection) */138 /** Initial snapshot before any debounced calls (for no-op detection) */
137 initialSnapshot?: unknown;139 initialSnapshot?: unknown;
138 /** Whether the last call wanted global handlers to be called */140 /** Whether the last call wanted global handlers to be called */
...@@ -157,14 +159,10 @@ function unwrapMutationError(caught: unknown) {...@@ -157,14 +159,10 @@ function unwrapMutationError(caught: unknown) {
157 return { error: caught, description: null };159 return { error: caught, description: null };
158}160}
159161
160interface Channel<Args extends unknown[], Result, OptimisticHelpers, Context> {162interface Channel<Args extends unknown[], Result, Context> {
161 listeners: Set<(update: MutationEvent<Result>) => void>;163 listeners: Set<(update: MutationEvent<Result>) => void>;
162 status: "idle" | "waiting" | "mutating" | "refetching" | "skipped";164 status: "idle" | "waiting" | "mutating" | "refetching" | "skipped";
163 rollbacks: Array<() => void>;
164 refetches: Array<() => Promise<void>>;
165 queue: Array<Item<Args, Result, Context>>;165 queue: Array<Item<Args, Result, Context>>;
166 // Shared optimistic helpers instance for the channel
167 helpers: OptimisticHelpers | null;
168 // Debounce state (only used if debounce option is set)166 // Debounce state (only used if debounce option is set)
169 debounceTimer: ReturnType<typeof setTimeout> | null;167 debounceTimer: ReturnType<typeof setTimeout> | null;
170 pendingDebounced: PendingDebouncedState<Args, Result, Context> | null;168 pendingDebounced: PendingDebouncedState<Args, Result, Context> | null;
...@@ -175,7 +173,8 @@ interface Channel<Args extends unknown[], Result, OptimisticHelpers, Context> {...@@ -175,7 +173,8 @@ interface Channel<Args extends unknown[], Result, OptimisticHelpers, Context> {
175interface Item<Args extends unknown[], Result, Context> {173interface Item<Args extends unknown[], Result, Context> {
176 args: Args;174 args: Args;
177 context: Context;175 context: Context;
178 rollbacks: number;176 rollbacks: Array<() => void>;
177 refetches: Array<() => Promise<void>>;
179 onSuccess: Array<(result: Result) => void>;178 onSuccess: Array<(result: Result) => void>;
180 resolve: (result: Result) => void;179 resolve: (result: Result) => void;
181 reject: (error: unknown) => void;180 reject: (error: unknown) => void;
...@@ -191,7 +190,7 @@ export class BlockingMutation<...@@ -191,7 +190,7 @@ export class BlockingMutation<
191 #client: MutationClientFromConfig<Config>;190 #client: MutationClientFromConfig<Config>;
192 #channels: Map<191 #channels: Map<
193 string,192 string,
194 Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>193 Channel<Args, Result, Context<Config, Auth>>
195 > = new Map();194 > = new Map();
196 client: MutationClientFromConfig<Config>;195 client: MutationClientFromConfig<Config>;
197196
...@@ -255,14 +254,10 @@ export class BlockingMutation<...@@ -255,14 +254,10 @@ export class BlockingMutation<
255 #getOrPutChannel(key: string) {254 #getOrPutChannel(key: string) {
256 let channel = this.#channels.get(key);255 let channel = this.#channels.get(key);
257 if (!channel) {256 if (!channel) {
258 const rollbacks: Array<() => []> = [];
259 channel = {257 channel = {
260 listeners: new Set(),258 listeners: new Set(),
261 status: "idle",259 status: "idle",
262 rollbacks,
263 refetches: [],
264 queue: [],260 queue: [],
265 helpers: null,
266 debounceTimer: null,261 debounceTimer: null,
267 pendingDebounced: null,262 pendingDebounced: null,
268 lastDebouncedExecutionTime: null,263 lastDebouncedExecutionTime: null,
...@@ -282,7 +277,7 @@ export class BlockingMutation<...@@ -282,7 +277,7 @@ export class BlockingMutation<
282 }277 }
283278
284 #notify(279 #notify(
285 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,280 channel: Channel<Args, Result, Context<Config, Auth>>,
286 status: MutationEvent<Result>["status"],281 status: MutationEvent<Result>["status"],
287 result: Result | null = null,282 result: Result | null = null,
288 error: unknown = null,283 error: unknown = null,
...@@ -293,7 +288,7 @@ export class BlockingMutation<...@@ -293,7 +288,7 @@ export class BlockingMutation<
293288
294 #setIdle(289 #setIdle(
295 key: string,290 key: string,
296 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,291 channel: Channel<Args, Result, Context<Config, Auth>>,
297 ) {292 ) {
298 // Check if there are pending debounced calls waiting293 // Check if there are pending debounced calls waiting
299 if (channel.pendingDebounced !== null) {294 if (channel.pendingDebounced !== null) {
...@@ -303,8 +298,6 @@ export class BlockingMutation<...@@ -303,8 +298,6 @@ export class BlockingMutation<
303 } else {298 } else {
304 // Normal idle transition299 // Normal idle transition
305 channel.status = "idle";300 channel.status = "idle";
306 // Discard any unconsumed refetch callbacks
307 channel.refetches = [];
308 this.#notify(channel, "idle", null, null);301 this.#notify(channel, "idle", null, null);
309 // Clean up the channel if there are no listeners302 // Clean up the channel if there are no listeners
310 if (channel.listeners.size === 0) {303 if (channel.listeners.size === 0) {
...@@ -477,44 +470,39 @@ export class BlockingMutation<...@@ -477,44 +470,39 @@ export class BlockingMutation<
477 ? this.#options.snapshot.call(context, { ...context, args })470 ? this.#options.snapshot.call(context, { ...context, args })
478 : undefined;471 : undefined;
479472
480 // Create shared optimistic helpers instance for the channel if it doesn't exist
481 if (channel.helpers === null) {
482 const onRefetch = (cb: () => Promise<void>) => {
483 channel.refetches.push(cb);
484 };
485
486 channel.helpers = this.#client.getOptimisticHelpers({
487 onRestore: (cb: () => void) => {
488 channel.rollbacks.push(cb);
489 },
490 onRefetch,
491 });
492 }
493
494 const onSuccess: Array<(result: Result) => void> = [];473 const onSuccess: Array<(result: Result) => void> = [];
495 let expired = false;474 let expired = false;
496 let rollbacks = 0;475 const rollbacks: Array<() => void> = [];
476 const refetches: Array<() => Promise<void>> = [];
497 const onRestore = (cb: () => void) => {477 const onRestore = (cb: () => void) => {
498 if (expired) {478 if (expired) {
499 throw new Error(479 throw new Error(
500 "Can only call onRestore from within the optimistic update function.",480 "Can only call onRestore from within the optimistic update function.",
501 );481 );
502 }482 }
503 channel.rollbacks.push(cb);483 rollbacks.push(cb);
504 rollbacks += 1;
505 };484 };
506485
507 // Register user's onRestore callback if provided486 // Register user's onRestore callback if provided
508 if (userOnRestore) {487 if (userOnRestore) {
509 channel.rollbacks.push(userOnRestore);488 rollbacks.push(userOnRestore);
510 rollbacks += 1;
511 }489 }
512490
491 // Per call, so restores, refetches and refetch dedupe belong to this call
492 const helpers = this.#client.getOptimisticHelpers({
493 onRestore: (cb) => {
494 rollbacks.push(cb);
495 },
496 onRefetch: (cb) => {
497 refetches.push(cb);
498 },
499 });
500
513 try {501 try {
514 this.#options.optimistic({502 this.#options.optimistic({
515 ...context,503 ...context,
516 args,504 args,
517 helpers: channel.helpers,505 helpers,
518 onRestore,506 onRestore,
519 onSuccess(cb) {507 onSuccess(cb) {
520 if (expired) {508 if (expired) {
...@@ -530,17 +518,13 @@ export class BlockingMutation<...@@ -530,17 +518,13 @@ export class BlockingMutation<
530 "Can only call onRefetch from within the optimistic update function.",518 "Can only call onRefetch from within the optimistic update function.",
531 );519 );
532 }520 }
533 channel.refetches.push(cb);521 refetches.push(cb);
534 },522 },
535 });523 });
536 } catch (error) {524 } catch (error) {
537 expired = true;525 expired = true;
538 let next;526 let next;
539 while (527 while (next = rollbacks.pop()) next();
540 next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0]
541 ) {
542 next();
543 }
544 return Promise.reject(error);528 return Promise.reject(error);
545 }529 }
546 expired = true;530 expired = true;
...@@ -555,11 +539,7 @@ export class BlockingMutation<...@@ -555,11 +539,7 @@ export class BlockingMutation<
555539
556 if (isNoOp) {540 if (isNoOp) {
557 let next;541 let next;
558 while (542 while (next = rollbacks.pop()) next();
559 next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0]
560 ) {
561 next();
562 }
563543
564 // Notify listeners of skipped status544 // Notify listeners of skipped status
565 this.#notify(channel, "skipped");545 this.#notify(channel, "skipped");
...@@ -573,6 +553,7 @@ export class BlockingMutation<...@@ -573,6 +553,7 @@ export class BlockingMutation<
573 args,553 args,
574 context,554 context,
575 rollbacks,555 rollbacks,
556 refetches,
576 onSuccess,557 onSuccess,
577 resolve,558 resolve,
578 reject,559 reject,
...@@ -587,7 +568,7 @@ export class BlockingMutation<...@@ -587,7 +568,7 @@ export class BlockingMutation<
587568
588 #executeNext(569 #executeNext(
589 key: string,570 key: string,
590 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,571 channel: Channel<Args, Result, Context<Config, Auth>>,
591 ) {572 ) {
592 const item = channel.queue.shift();573 const item = channel.queue.shift();
593 if (!item) {574 if (!item) {
...@@ -595,21 +576,19 @@ export class BlockingMutation<...@@ -595,21 +576,19 @@ export class BlockingMutation<
595 return;576 return;
596 }577 }
597578
598 const { args, context, onSuccess, resolve, reject } = item;579 const { args, context, refetches, onSuccess, resolve, reject } = item;
599 channel.status = "mutating";580 channel.status = "mutating";
600 this.#notify(channel, "mutating");581 this.#notify(channel, "mutating");
601582
602 new Promise<Result>((resolve) => resolve(this.#options.mutate.call(context, ...args))).then((result) => {583 new Promise<Result>((resolve) => resolve(this.#options.mutate.call(context, ...args))).then((result) => {
603 // remove rollbacks and apply optimistic success handlers584 // the call's rollbacks retire with it; apply optimistic success handlers
604 channel.rollbacks.splice(0, item.rollbacks);
605 onSuccess.forEach((cb) => cb(result));585 onSuccess.forEach((cb) => cb(result));
606586
607 if (this.#options.refetchOnSuccess !== false) {587 if (this.#options.refetchOnSuccess !== false) {
608 channel.status = "refetching";588 channel.status = "refetching";
609 this.#notify(channel, "refetching", result);589 this.#notify(channel, "refetching", result);
610 // Call refetch and all refetch callbacks in parallel590 // Call refetch and all refetch callbacks in parallel
611 const refetchCallbacks = channel.refetches.splice(0);591 Promise.allSettled(refetches.map((cb) => cb())).then(
612 Promise.allSettled(refetchCallbacks.map((cb) => cb())).then(
613 (results) => {592 (results) => {
614 // Report any errors from refetch or callbacks593 // Report any errors from refetch or callbacks
615 results.forEach((result) => {594 results.forEach((result) => {
...@@ -623,8 +602,6 @@ export class BlockingMutation<...@@ -623,8 +602,6 @@ export class BlockingMutation<
623 this.#executeNext(key, channel);602 this.#executeNext(key, channel);
624 });603 });
625 } else {604 } else {
626 // Discard refetch callbacks if refetchOnSuccess is false
627 channel.refetches = [];
628 // Notify listeners with success status and result before moving to next605 // Notify listeners with success status and result before moving to next
629 this.#notify(channel, "mutating", result);606 this.#notify(channel, "mutating", result);
630 this.#executeNext(key, channel);607 this.#executeNext(key, channel);
...@@ -635,12 +612,14 @@ export class BlockingMutation<...@@ -635,12 +612,14 @@ export class BlockingMutation<
635 const description = this.describe(...args);612 const description = this.describe(...args);
636 const wrappedError = new MutationError(error, description);613 const wrappedError = new MutationError(error, description);
637614
638 // if an error happens, then every rollback is called in reverse order615 // if an error happens, then every pending call's rollbacks are called in reverse order
639 let next;616 const remainingItems = channel.queue.splice(0);
640 while (next = channel.rollbacks.pop()) next();617 for (const call of [item, ...remainingItems, channel.pendingDebounced].reverse()) {
618 let next;
619 while (next = call?.rollbacks.pop()) next();
620 }
641621
642 // Cancel all remaining items in the channel622 // Cancel all remaining items in the channel
643 const remainingItems = channel.queue.splice(0);
644 remainingItems.forEach((queuedItem) => {623 remainingItems.forEach((queuedItem) => {
645 queuedItem.reject(wrappedError);624 queuedItem.reject(wrappedError);
646 });625 });
...@@ -651,8 +630,8 @@ export class BlockingMutation<...@@ -651,8 +630,8 @@ export class BlockingMutation<
651 // Refetch to restore correct state630 // Refetch to restore correct state
652 channel.status = "refetching";631 channel.status = "refetching";
653 this.#notify(channel, "refetching", null, error);632 this.#notify(channel, "refetching", null, error);
654 // Call refetch and all refetch callbacks in parallel633 // Refetch for the failed and cancelled calls in parallel
655 const refetchCallbacks = channel.refetches.splice(0);634 const refetchCallbacks = [item, ...remainingItems].flatMap((call) => call.refetches);
656 Promise.allSettled(refetchCallbacks.map((cb) => cb())).then((results) => {635 Promise.allSettled(refetchCallbacks.map((cb) => cb())).then((results) => {
657 // Report any errors from refetch or callbacks636 // Report any errors from refetch or callbacks
658 results.forEach((result) => {637 results.forEach((result) => {
...@@ -672,7 +651,7 @@ export class BlockingMutation<...@@ -672,7 +651,7 @@ export class BlockingMutation<
672 #runDebouncedAndReturn(651 #runDebouncedAndReturn(
673 args: Args,652 args: Args,
674 key: string,653 key: string,
675 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,654 channel: Channel<Args, Result, Context<Config, Auth>>,
676 context: Context<Config, Auth>,655 context: Context<Config, Auth>,
677 userOnRestore: (() => void) | undefined,656 userOnRestore: (() => void) | undefined,
678 shouldExecuteImmediate: boolean,657 shouldExecuteImmediate: boolean,
...@@ -693,44 +672,40 @@ export class BlockingMutation<...@@ -693,44 +672,40 @@ export class BlockingMutation<
693 this.#rollbackPendingDebounced(channel);672 this.#rollbackPendingDebounced(channel);
694 }673 }
695674
696 // Create shared helpers if needed (same as current implementation)
697 if (channel.helpers === null) {
698 const onRefetch = (cb: () => Promise<void>) => {
699 channel.refetches.push(cb);
700 };
701 channel.helpers = this.#client.getOptimisticHelpers({
702 onRestore: (cb: () => void) => {
703 channel.rollbacks.push(cb);
704 },
705 onRefetch,
706 });
707 }
708
709 // Apply optimistic update (same logic as current runAndReturn)675 // Apply optimistic update (same logic as current runAndReturn)
710 const onSuccess: Array<(result: Result) => void> = [];676 const onSuccess: Array<(result: Result) => void> = [];
711 let expired = false;677 let expired = false;
712 let rollbacks = 0;678 const rollbacks: Array<() => void> = [];
679 const refetches: Array<() => Promise<void>> = [];
713 const onRestore = (cb: () => void) => {680 const onRestore = (cb: () => void) => {
714 if (expired) {681 if (expired) {
715 throw new Error(682 throw new Error(
716 "Can only call onRestore from within the optimistic update function.",683 "Can only call onRestore from within the optimistic update function.",
717 );684 );
718 }685 }
719 channel.rollbacks.push(cb);686 rollbacks.push(cb);
720 rollbacks += 1;
721 };687 };
722688
723 // Register user's onRestore callback if provided689 // Register user's onRestore callback if provided
724 if (userOnRestore) {690 if (userOnRestore) {
725 channel.rollbacks.push(userOnRestore);691 rollbacks.push(userOnRestore);
726 rollbacks += 1;
727 }692 }
728693
694 // Per call, so restores, refetches and refetch dedupe belong to this call
695 const helpers = this.#client.getOptimisticHelpers({
696 onRestore: (cb) => {
697 rollbacks.push(cb);
698 },
699 onRefetch: (cb) => {
700 refetches.push(cb);
701 },
702 });
703
729 try {704 try {
730 this.#options.optimistic({705 this.#options.optimistic({
731 ...context,706 ...context,
732 args,707 args,
733 helpers: channel.helpers,708 helpers,
734 onRestore,709 onRestore,
735 onSuccess(cb) {710 onSuccess(cb) {
736 if (expired) {711 if (expired) {
...@@ -746,18 +721,14 @@ export class BlockingMutation<...@@ -746,18 +721,14 @@ export class BlockingMutation<
746 "Can only call onRefetch from within the optimistic update function.",721 "Can only call onRefetch from within the optimistic update function.",
747 );722 );
748 }723 }
749 channel.refetches.push(cb);724 refetches.push(cb);
750 },725 },
751 });726 });
752 } catch (error) {727 } catch (error) {
753 expired = true;728 expired = true;
754 // Roll back the rollbacks we just added729 // Roll back the rollbacks we just added
755 let next;730 let next;
756 while (731 while (next = rollbacks.pop()) next();
757 next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0]
758 ) {
759 next();
760 }
761 return Promise.reject(error);732 return Promise.reject(error);
762 }733 }
763 expired = true;734 expired = true;
...@@ -778,11 +749,7 @@ export class BlockingMutation<...@@ -778,11 +749,7 @@ export class BlockingMutation<
778 ) {749 ) {
779 // No-op detected - rollback optimistic update750 // No-op detected - rollback optimistic update
780 let next;751 let next;
781 while (752 while (next = rollbacks.pop()) next();
782 next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0]
783 ) {
784 next();
785 }
786753
787 // Clear debounce timer754 // Clear debounce timer
788 if (channel.debounceTimer !== null) {755 if (channel.debounceTimer !== null) {
...@@ -810,9 +777,10 @@ export class BlockingMutation<...@@ -810,9 +777,10 @@ export class BlockingMutation<
810 channel.pendingDebounced = {777 channel.pendingDebounced = {
811 args,778 args,
812 context,779 context,
813 rollbackCount: rollbacks,780 rollbacks,
814 pending: [{ resolve, reject }],781 pending: [{ resolve, reject }],
815 onSuccess,782 onSuccess,
783 refetches,
816 initialSnapshot: isFirstDebouncedCall ? initialSnapshot : undefined,784 initialSnapshot: isFirstDebouncedCall ? initialSnapshot : undefined,
817 shouldCallGlobalHandler,785 shouldCallGlobalHandler,
818 };786 };
...@@ -826,9 +794,10 @@ export class BlockingMutation<...@@ -826,9 +794,10 @@ export class BlockingMutation<
826 // Subsequent debounced call - update state794 // Subsequent debounced call - update state
827 channel.pendingDebounced.args = args;795 channel.pendingDebounced.args = args;
828 channel.pendingDebounced.context = context;796 channel.pendingDebounced.context = context;
829 channel.pendingDebounced.rollbackCount = rollbacks;797 channel.pendingDebounced.rollbacks = rollbacks;
830 channel.pendingDebounced.pending.push({ resolve, reject });798 channel.pendingDebounced.pending.push({ resolve, reject });
831 channel.pendingDebounced.onSuccess = onSuccess;799 channel.pendingDebounced.onSuccess = onSuccess;
800 channel.pendingDebounced.refetches = refetches;
832 channel.pendingDebounced.shouldCallGlobalHandler = shouldCallGlobalHandler;801 channel.pendingDebounced.shouldCallGlobalHandler = shouldCallGlobalHandler;
833 // Keep the initial snapshot from the first call802 // Keep the initial snapshot from the first call
834 // Status stays "waiting"803 // Status stays "waiting"
...@@ -849,18 +818,15 @@ export class BlockingMutation<...@@ -849,18 +818,15 @@ export class BlockingMutation<
849 }818 }
850819
851 #rollbackPendingDebounced(820 #rollbackPendingDebounced(
852 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,821 channel: Channel<Args, Result, Context<Config, Auth>>,
853 ) {822 ) {
854 if (!channel.pendingDebounced) return;823 if (!channel.pendingDebounced) return;
855824
856 const { rollbackCount } = channel.pendingDebounced;825 const { rollbacks } = channel.pendingDebounced;
857826
858 // Roll back this call's optimistic updates (in reverse order)827 // Roll back this call's optimistic updates (in reverse order)
859 // Remove from the end of the rollbacks array828 let next;
860 for (let i = 0; i < rollbackCount; i++) {829 while (next = rollbacks.pop()) next();
861 const rollback = channel.rollbacks.pop();
862 if (rollback) rollback();
863 }
864830
865 // Note: We do NOT reject the promises here831 // Note: We do NOT reject the promises here
866 // They will all resolve when the final call completes832 // They will all resolve when the final call completes
...@@ -868,7 +834,7 @@ export class BlockingMutation<...@@ -868,7 +834,7 @@ export class BlockingMutation<
868834
869 #enqueueDebouncedCall(835 #enqueueDebouncedCall(
870 key: string,836 key: string,
871 channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>,837 channel: Channel<Args, Result, Context<Config, Auth>>,
872 ) {838 ) {
873 // Clear timer839 // Clear timer
874 channel.debounceTimer = null;840 channel.debounceTimer = null;
...@@ -879,7 +845,8 @@ export class BlockingMutation<...@@ -879,7 +845,8 @@ export class BlockingMutation<
879 return;845 return;
880 }846 }
881847
882 const { args, context, rollbackCount, pending, onSuccess, shouldCallGlobalHandler } = channel.pendingDebounced;848 const { args, context, rollbacks, pending, onSuccess, refetches, shouldCallGlobalHandler } =
849 channel.pendingDebounced;
883 channel.pendingDebounced = null;850 channel.pendingDebounced = null;
884851
885 // Track execution time for debounceImmediate852 // Track execution time for debounceImmediate
...@@ -928,7 +895,8 @@ export class BlockingMutation<...@@ -928,7 +895,8 @@ export class BlockingMutation<
928 channel.queue.push({895 channel.queue.push({
929 args,896 args,
930 context,897 context,
931 rollbacks: rollbackCount,898 rollbacks,
899 refetches,
932 onSuccess,900 onSuccess,
933 resolve: wrapperResolve,901 resolve: wrapperResolve,
934 reject: wrapperReject,902 reject: wrapperReject,
test/tanstack-query-helpers.test.ts+233-2
...@@ -1,6 +1,8 @@...@@ -1,6 +1,8 @@
1import { delay } from "@clo/lib/async.ts";
1import { assertEquals } from "@std/assert";2import { assertEquals } from "@std/assert";
2import { QueryClient, queryOptions } from "@tanstack/react-query";3import { QueryClient, QueryObserver, queryOptions } from "@tanstack/react-query";
3import { test } from "vitest";4import { test, vi } from "vitest";
5import { MutationClient } from "../src/client.ts";
4import { queryClientOptimisticHelpers, reactiveFromQueryCache } from "../src/tanstack-query.ts";6import { queryClientOptimisticHelpers, reactiveFromQueryCache } from "../src/tanstack-query.ts";
57
6interface TestData {8interface TestData {
...@@ -1114,3 +1116,232 @@ test("integration - multiple operations work together", () => {...@@ -1114,3 +1116,232 @@ test("integration - multiple operations work together", () => {
1114 assertEquals(restored?.active, true);1116 assertEquals(restored?.active, true);
1115 assertEquals(restored?.items.length, 3);1117 assertEquals(restored?.items.length, 3);
1116});1118});
1119
1120// ============================================================================
1121// Mutation integration: each call owns the restores and refetches its helpers register
1122// ============================================================================
1123
1124function createToggleClient() {
1125 const queryClient = new QueryClient({
1126 defaultOptions: { queries: { retry: false } },
1127 });
1128 const server = { enabled: true, online: true, fetches: 0 };
1129
1130 const queryToggle = queryOptions({
1131 queryKey: ["toggle"],
1132 queryFn: async () => {
1133 server.fetches += 1;
1134 if (!server.online) throw new Error("offline");
1135 return { enabled: server.enabled };
1136 },
1137 });
1138 queryClient.setQueryData(queryToggle.queryKey, { enabled: true });
1139 // Observed, so invalidation refetches it; the refetch fails while offline.
1140 new QueryObserver(queryClient, queryToggle).subscribe(() => {});
1141
1142 const mutations = new MutationClient({
1143 context: {},
1144 getOptimisticHelpers: queryClientOptimisticHelpers(queryClient),
1145 reportError: () => {},
1146 });
1147
1148 const save = async (enabled: boolean) => {
1149 await delay(10);
1150 if (!server.online) throw new Error("offline");
1151 server.enabled = enabled;
1152 return enabled;
1153 };
1154 const read = () => queryClient.getQueryData(queryToggle.queryKey)?.enabled;
1155
1156 return { queryClient, queryToggle, server, mutations, save, read };
1157}
1158
1159test("a failure does not replay the helper restores of a call that succeeded", async () => {
1160 vi.useFakeTimers();
1161 const { queryToggle, server, mutations, save, read } = createToggleClient();
1162 const mutToggle = mutations.define({
1163 id: "toggle",
1164 mutate: save,
1165 optimistic: ({ helpers, args: [enabled] }) => {
1166 helpers.updateExisting(queryToggle, { enabled });
1167 },
1168 describe: "toggle",
1169 describeResult: null,
1170 });
1171 // `useMutate` keeps the channel alive between calls
1172 mutToggle.subscribe(mutToggle.key([true]), () => {});
1173
1174 mutToggle.run(false);
1175 await vi.advanceTimersByTimeAsync(100);
1176 assertEquals([server.enabled, read()], [false, false]);
1177
1178 server.online = false;
1179 mutToggle.run(true);
1180 assertEquals(read(), true);
1181 await vi.advanceTimersByTimeAsync(100);
1182 assertEquals(read(), false);
1183});
1184
1185test("a queued failure does not replay the helper restores of the call ahead of it", async () => {
1186 vi.useFakeTimers();
1187 const { queryToggle, server, mutations, save, read } = createToggleClient();
1188 const mutToggle = mutations.define({
1189 id: "toggle",
1190 mutate: save,
1191 optimistic: ({ helpers, args: [enabled] }) => {
1192 helpers.updateExisting(queryToggle, { enabled });
1193 },
1194 describe: "toggle",
1195 describeResult: null,
1196 });
1197
1198 mutToggle.run(false);
1199 mutToggle.run(true);
1200 await vi.advanceTimersByTimeAsync(10);
1201 assertEquals(server.enabled, false);
1202
1203 server.online = false;
1204 await vi.advanceTimersByTimeAsync(100);
1205 assertEquals(read(), false);
1206});
1207
1208test("a success retires its own onRestore callbacks, not the channel's oldest restores", async () => {
1209 vi.useFakeTimers();
1210 const { queryToggle, server, mutations, save, read } = createToggleClient();
1211 let lastChoice: boolean | null = null;
1212 const mutToggle = mutations.define({
1213 id: "toggle",
1214 mutate: save,
1215 optimistic: ({ helpers, args: [enabled], onRestore }) => {
1216 helpers.updateExisting(queryToggle, { enabled });
1217 const prev = lastChoice;
1218 lastChoice = enabled;
1219 onRestore(() => {
1220 lastChoice = prev;
1221 });
1222 },
1223 describe: "toggle",
1224 describeResult: null,
1225 });
1226 mutToggle.subscribe(mutToggle.key([true]), () => {});
1227
1228 mutToggle.run(false);
1229 await vi.advanceTimersByTimeAsync(100);
1230
1231 server.online = false;
1232 mutToggle.run(true);
1233 await vi.advanceTimersByTimeAsync(100);
1234 assertEquals([lastChoice, read()], [false, false]);
1235});
1236
1237test("an optimistic update that throws restores its helper updates", () => {
1238 const { queryToggle, mutations, save, read } = createToggleClient();
1239 const mutToggle = mutations.define({
1240 id: "toggle",
1241 mutate: save,
1242 optimistic: ({ helpers, args: [enabled] }) => {
1243 helpers.updateExisting(queryToggle, { enabled });
1244 throw new Error("optimistic update failed");
1245 },
1246 describe: "toggle",
1247 describeResult: null,
1248 });
1249
1250 mutToggle.run(false);
1251 assertEquals(read(), true);
1252});
1253
1254test("a skipped no-op call's helper restores are not replayed by a later failure", async () => {
1255 vi.useFakeTimers();
1256 const { queryClient, queryToggle, server, mutations, save, read } = createToggleClient();
1257 const mutToggle = mutations.define({
1258 id: "toggle",
1259 mutate: save,
1260 optimistic: ({ helpers, args: [enabled] }) => {
1261 helpers.updateExisting(queryToggle, { enabled });
1262 },
1263 snapshot: () => read(),
1264 describe: "toggle",
1265 describeResult: null,
1266 });
1267
1268 mutToggle.run(true);
1269 // Another client turns it off.
1270 server.enabled = false;
1271 queryClient.setQueryData(queryToggle.queryKey, { enabled: false });
1272
1273 server.online = false;
1274 mutToggle.run(true);
1275 await vi.advanceTimersByTimeAsync(100);
1276 assertEquals(read(), false);
1277});
1278
1279test("a debounced success retires the helper restores of every call it covers", async () => {
1280 vi.useFakeTimers();
1281 const { queryToggle, server, mutations, save, read } = createToggleClient();
1282 const mutToggle = mutations.define({
1283 id: "toggle",
1284 mutate: save,
1285 optimistic: ({ helpers, args: [enabled] }) => {
1286 helpers.updateExisting(queryToggle, { enabled });
1287 },
1288 describe: "toggle",
1289 describeResult: null,
1290 debounceMs: 50,
1291 });
1292 mutToggle.subscribe(mutToggle.key([true]), () => {});
1293
1294 mutToggle.run(false);
1295 mutToggle.run(false);
1296 await vi.advanceTimersByTimeAsync(200);
1297 assertEquals([server.enabled, read()], [false, false]);
1298
1299 server.online = false;
1300 mutToggle.run(true);
1301 await vi.advanceTimersByTimeAsync(200);
1302 assertEquals(read(), false);
1303});
1304
1305test("every call refetches the queries its helpers touched", async () => {
1306 vi.useFakeTimers();
1307 const { queryToggle, server, mutations, save } = createToggleClient();
1308 const mutToggle = mutations.define({
1309 id: "toggle",
1310 mutate: save,
1311 optimistic: ({ helpers, args: [enabled] }) => {
1312 helpers.updateExisting(queryToggle, { enabled });
1313 },
1314 describe: "toggle",
1315 describeResult: null,
1316 });
1317 mutToggle.subscribe(mutToggle.key([true]), () => {});
1318 await vi.advanceTimersByTimeAsync(0);
1319 const fetchesBefore = server.fetches;
1320
1321 mutToggle.run(false);
1322 await vi.advanceTimersByTimeAsync(100);
1323 assertEquals(server.fetches, fetchesBefore + 1);
1324
1325 mutToggle.run(true);
1326 await vi.advanceTimersByTimeAsync(100);
1327 assertEquals(server.fetches, fetchesBefore + 2);
1328});
1329
1330test("a queued call refetches after its own write, not with the call ahead of it", async () => {
1331 vi.useFakeTimers();
1332 const { queryToggle, server, mutations, save, read } = createToggleClient();
1333 const mutToggle = mutations.define({
1334 id: "toggle",
1335 mutate: save,
1336 optimistic: ({ helpers, args: [enabled] }) => {
1337 helpers.updateExisting(queryToggle, { enabled });
1338 },
1339 describe: "toggle",
1340 describeResult: null,
1341 });
1342
1343 mutToggle.run(false);
1344 mutToggle.run(true);
1345 await vi.advanceTimersByTimeAsync(100);
1346 assertEquals([server.enabled, read()], [true, true]);
1347});