| ... | ... | @@ -124,8 +124,8 @@ interface PendingDebouncedState<Args extends unknown[], Result, Context> { |
| 124 | 124 | args: Args; |
| 125 | 125 | /** Context captured when the most recent call was allowed */ |
| 126 | 126 | context: Context; |
| 127 | | /** Number of rollbacks the most recent call added */ |
| 128 | | rollbackCount: number; |
| 127 | /** Restores registered by the most recent call */ |
| 128 | rollbacks: Array<() => void>; |
| 129 | 129 | /** All pending promises from all superseded calls */ |
| 130 | 130 | pending: Array<{ |
| 131 | 131 | resolve: (result: Result) => void; |
| ... | ... | @@ -133,6 +133,8 @@ interface PendingDebouncedState<Args extends unknown[], Result, Context> { |
| 133 | 133 | }>; |
| 134 | 134 | /** Success callbacks from the most recent call */ |
| 135 | 135 | onSuccess: Array<(result: Result) => void>; |
| 136 | /** Refetch callbacks from the most recent call */ |
| 137 | refetches: Array<() => Promise<void>>; |
| 136 | 138 | /** Initial snapshot before any debounced calls (for no-op detection) */ |
| 137 | 139 | initialSnapshot?: unknown; |
| 138 | 140 | /** Whether the last call wanted global handlers to be called */ |
| ... | ... | @@ -157,14 +159,10 @@ function unwrapMutationError(caught: unknown) { |
| 157 | 159 | return { error: caught, description: null }; |
| 158 | 160 | } |
| 159 | 161 | |
| 160 | | interface Channel<Args extends unknown[], Result, OptimisticHelpers, Context> { |
| 162 | interface Channel<Args extends unknown[], Result, Context> { |
| 161 | 163 | listeners: Set<(update: MutationEvent<Result>) => void>; |
| 162 | 164 | status: "idle" | "waiting" | "mutating" | "refetching" | "skipped"; |
| 163 | | rollbacks: Array<() => void>; |
| 164 | | refetches: Array<() => Promise<void>>; |
| 165 | 165 | queue: Array<Item<Args, Result, Context>>; |
| 166 | | // Shared optimistic helpers instance for the channel |
| 167 | | helpers: OptimisticHelpers | null; |
| 168 | 166 | // Debounce state (only used if debounce option is set) |
| 169 | 167 | debounceTimer: ReturnType<typeof setTimeout> | null; |
| 170 | 168 | pendingDebounced: PendingDebouncedState<Args, Result, Context> | null; |
| ... | ... | @@ -175,7 +173,8 @@ interface Channel<Args extends unknown[], Result, OptimisticHelpers, Context> { |
| 175 | 173 | interface Item<Args extends unknown[], Result, Context> { |
| 176 | 174 | args: Args; |
| 177 | 175 | context: Context; |
| 178 | | rollbacks: number; |
| 176 | rollbacks: Array<() => void>; |
| 177 | refetches: Array<() => Promise<void>>; |
| 179 | 178 | onSuccess: Array<(result: Result) => void>; |
| 180 | 179 | resolve: (result: Result) => void; |
| 181 | 180 | reject: (error: unknown) => void; |
| ... | ... | @@ -191,7 +190,7 @@ export class BlockingMutation< |
| 191 | 190 | #client: MutationClientFromConfig<Config>; |
| 192 | 191 | #channels: Map< |
| 193 | 192 | string, |
| 194 | | Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>> |
| 193 | Channel<Args, Result, Context<Config, Auth>> |
| 195 | 194 | > = new Map(); |
| 196 | 195 | client: MutationClientFromConfig<Config>; |
| 197 | 196 | |
| ... | ... | @@ -255,14 +254,10 @@ export class BlockingMutation< |
| 255 | 254 | #getOrPutChannel(key: string) { |
| 256 | 255 | let channel = this.#channels.get(key); |
| 257 | 256 | if (!channel) { |
| 258 | | const rollbacks: Array<() => []> = []; |
| 259 | 257 | channel = { |
| 260 | 258 | listeners: new Set(), |
| 261 | 259 | status: "idle", |
| 262 | | rollbacks, |
| 263 | | refetches: [], |
| 264 | 260 | queue: [], |
| 265 | | helpers: null, |
| 266 | 261 | debounceTimer: null, |
| 267 | 262 | pendingDebounced: null, |
| 268 | 263 | lastDebouncedExecutionTime: null, |
| ... | ... | @@ -282,7 +277,7 @@ export class BlockingMutation< |
| 282 | 277 | } |
| 283 | 278 | |
| 284 | 279 | #notify( |
| 285 | | channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>, |
| 280 | channel: Channel<Args, Result, Context<Config, Auth>>, |
| 286 | 281 | status: MutationEvent<Result>["status"], |
| 287 | 282 | result: Result | null = null, |
| 288 | 283 | error: unknown = null, |
| ... | ... | @@ -293,7 +288,7 @@ export class BlockingMutation< |
| 293 | 288 | |
| 294 | 289 | #setIdle( |
| 295 | 290 | key: string, |
| 296 | | channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>, |
| 291 | channel: Channel<Args, Result, Context<Config, Auth>>, |
| 297 | 292 | ) { |
| 298 | 293 | // Check if there are pending debounced calls waiting |
| 299 | 294 | if (channel.pendingDebounced !== null) { |
| ... | ... | @@ -303,8 +298,6 @@ export class BlockingMutation< |
| 303 | 298 | } else { |
| 304 | 299 | // Normal idle transition |
| 305 | 300 | channel.status = "idle"; |
| 306 | | // Discard any unconsumed refetch callbacks |
| 307 | | channel.refetches = []; |
| 308 | 301 | this.#notify(channel, "idle", null, null); |
| 309 | 302 | // Clean up the channel if there are no listeners |
| 310 | 303 | if (channel.listeners.size === 0) { |
| ... | ... | @@ -477,44 +470,39 @@ export class BlockingMutation< |
| 477 | 470 | ? this.#options.snapshot.call(context, { ...context, args }) |
| 478 | 471 | : undefined; |
| 479 | 472 | |
| 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 | 473 | const onSuccess: Array<(result: Result) => void> = []; |
| 495 | 474 | let expired = false; |
| 496 | | let rollbacks = 0; |
| 475 | const rollbacks: Array<() => void> = []; |
| 476 | const refetches: Array<() => Promise<void>> = []; |
| 497 | 477 | const onRestore = (cb: () => void) => { |
| 498 | 478 | if (expired) { |
| 499 | 479 | throw new Error( |
| 500 | 480 | "Can only call onRestore from within the optimistic update function.", |
| 501 | 481 | ); |
| 502 | 482 | } |
| 503 | | channel.rollbacks.push(cb); |
| 504 | | rollbacks += 1; |
| 483 | rollbacks.push(cb); |
| 505 | 484 | }; |
| 506 | 485 | |
| 507 | 486 | // Register user's onRestore callback if provided |
| 508 | 487 | if (userOnRestore) { |
| 509 | | channel.rollbacks.push(userOnRestore); |
| 510 | | rollbacks += 1; |
| 488 | rollbacks.push(userOnRestore); |
| 511 | 489 | } |
| 512 | 490 | |
| 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 | 501 | try { |
| 514 | 502 | this.#options.optimistic({ |
| 515 | 503 | ...context, |
| 516 | 504 | args, |
| 517 | | helpers: channel.helpers, |
| 505 | helpers, |
| 518 | 506 | onRestore, |
| 519 | 507 | onSuccess(cb) { |
| 520 | 508 | if (expired) { |
| ... | ... | @@ -530,17 +518,13 @@ export class BlockingMutation< |
| 530 | 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 | 524 | } catch (error) { |
| 537 | 525 | expired = true; |
| 538 | 526 | let next; |
| 539 | | while ( |
| 540 | | next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0] |
| 541 | | ) { |
| 542 | | next(); |
| 543 | | } |
| 527 | while (next = rollbacks.pop()) next(); |
| 544 | 528 | return Promise.reject(error); |
| 545 | 529 | } |
| 546 | 530 | expired = true; |
| ... | ... | @@ -555,11 +539,7 @@ export class BlockingMutation< |
| 555 | 539 | |
| 556 | 540 | if (isNoOp) { |
| 557 | 541 | let next; |
| 558 | | while ( |
| 559 | | next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0] |
| 560 | | ) { |
| 561 | | next(); |
| 562 | | } |
| 542 | while (next = rollbacks.pop()) next(); |
| 563 | 543 | |
| 564 | 544 | // Notify listeners of skipped status |
| 565 | 545 | this.#notify(channel, "skipped"); |
| ... | ... | @@ -573,6 +553,7 @@ export class BlockingMutation< |
| 573 | 553 | args, |
| 574 | 554 | context, |
| 575 | 555 | rollbacks, |
| 556 | refetches, |
| 576 | 557 | onSuccess, |
| 577 | 558 | resolve, |
| 578 | 559 | reject, |
| ... | ... | @@ -587,7 +568,7 @@ export class BlockingMutation< |
| 587 | 568 | |
| 588 | 569 | #executeNext( |
| 589 | 570 | key: string, |
| 590 | | channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>, |
| 571 | channel: Channel<Args, Result, Context<Config, Auth>>, |
| 591 | 572 | ) { |
| 592 | 573 | const item = channel.queue.shift(); |
| 593 | 574 | if (!item) { |
| ... | ... | @@ -595,21 +576,19 @@ export class BlockingMutation< |
| 595 | 576 | return; |
| 596 | 577 | } |
| 597 | 578 | |
| 598 | | const { args, context, onSuccess, resolve, reject } = item; |
| 579 | const { args, context, refetches, onSuccess, resolve, reject } = item; |
| 599 | 580 | channel.status = "mutating"; |
| 600 | 581 | this.#notify(channel, "mutating"); |
| 601 | 582 | |
| 602 | 583 | new Promise<Result>((resolve) => resolve(this.#options.mutate.call(context, ...args))).then((result) => { |
| 603 | | // remove rollbacks and apply optimistic success handlers |
| 604 | | channel.rollbacks.splice(0, item.rollbacks); |
| 584 | // the call's rollbacks retire with it; apply optimistic success handlers |
| 605 | 585 | onSuccess.forEach((cb) => cb(result)); |
| 606 | 586 | |
| 607 | 587 | if (this.#options.refetchOnSuccess !== false) { |
| 608 | 588 | channel.status = "refetching"; |
| 609 | 589 | this.#notify(channel, "refetching", result); |
| 610 | 590 | // Call refetch and all refetch callbacks in parallel |
| 611 | | const refetchCallbacks = channel.refetches.splice(0); |
| 612 | | Promise.allSettled(refetchCallbacks.map((cb) => cb())).then( |
| 591 | Promise.allSettled(refetches.map((cb) => cb())).then( |
| 613 | 592 | (results) => { |
| 614 | 593 | // Report any errors from refetch or callbacks |
| 615 | 594 | results.forEach((result) => { |
| ... | ... | @@ -623,8 +602,6 @@ export class BlockingMutation< |
| 623 | 602 | this.#executeNext(key, channel); |
| 624 | 603 | }); |
| 625 | 604 | } else { |
| 626 | | // Discard refetch callbacks if refetchOnSuccess is false |
| 627 | | channel.refetches = []; |
| 628 | 605 | // Notify listeners with success status and result before moving to next |
| 629 | 606 | this.#notify(channel, "mutating", result); |
| 630 | 607 | this.#executeNext(key, channel); |
| ... | ... | @@ -635,12 +612,14 @@ export class BlockingMutation< |
| 635 | 612 | const description = this.describe(...args); |
| 636 | 613 | const wrappedError = new MutationError(error, description); |
| 637 | 614 | |
| 638 | | // if an error happens, then every rollback is called in reverse order |
| 639 | | let next; |
| 640 | | while (next = channel.rollbacks.pop()) next(); |
| 615 | // if an error happens, then every pending call's rollbacks are called in reverse order |
| 616 | const remainingItems = channel.queue.splice(0); |
| 617 | for (const call of [item, ...remainingItems, channel.pendingDebounced].reverse()) { |
| 618 | let next; |
| 619 | while (next = call?.rollbacks.pop()) next(); |
| 620 | } |
| 641 | 621 | |
| 642 | 622 | // Cancel all remaining items in the channel |
| 643 | | const remainingItems = channel.queue.splice(0); |
| 644 | 623 | remainingItems.forEach((queuedItem) => { |
| 645 | 624 | queuedItem.reject(wrappedError); |
| 646 | 625 | }); |
| ... | ... | @@ -651,8 +630,8 @@ export class BlockingMutation< |
| 651 | 630 | // Refetch to restore correct state |
| 652 | 631 | channel.status = "refetching"; |
| 653 | 632 | this.#notify(channel, "refetching", null, error); |
| 654 | | // Call refetch and all refetch callbacks in parallel |
| 655 | | const refetchCallbacks = channel.refetches.splice(0); |
| 633 | // Refetch for the failed and cancelled calls in parallel |
| 634 | const refetchCallbacks = [item, ...remainingItems].flatMap((call) => call.refetches); |
| 656 | 635 | Promise.allSettled(refetchCallbacks.map((cb) => cb())).then((results) => { |
| 657 | 636 | // Report any errors from refetch or callbacks |
| 658 | 637 | results.forEach((result) => { |
| ... | ... | @@ -672,7 +651,7 @@ export class BlockingMutation< |
| 672 | 651 | #runDebouncedAndReturn( |
| 673 | 652 | args: Args, |
| 674 | 653 | key: string, |
| 675 | | channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>, |
| 654 | channel: Channel<Args, Result, Context<Config, Auth>>, |
| 676 | 655 | context: Context<Config, Auth>, |
| 677 | 656 | userOnRestore: (() => void) | undefined, |
| 678 | 657 | shouldExecuteImmediate: boolean, |
| ... | ... | @@ -693,44 +672,40 @@ export class BlockingMutation< |
| 693 | 672 | this.#rollbackPendingDebounced(channel); |
| 694 | 673 | } |
| 695 | 674 | |
| 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 | 675 | // Apply optimistic update (same logic as current runAndReturn) |
| 710 | 676 | const onSuccess: Array<(result: Result) => void> = []; |
| 711 | 677 | let expired = false; |
| 712 | | let rollbacks = 0; |
| 678 | const rollbacks: Array<() => void> = []; |
| 679 | const refetches: Array<() => Promise<void>> = []; |
| 713 | 680 | const onRestore = (cb: () => void) => { |
| 714 | 681 | if (expired) { |
| 715 | 682 | throw new Error( |
| 716 | 683 | "Can only call onRestore from within the optimistic update function.", |
| 717 | 684 | ); |
| 718 | 685 | } |
| 719 | | channel.rollbacks.push(cb); |
| 720 | | rollbacks += 1; |
| 686 | rollbacks.push(cb); |
| 721 | 687 | }; |
| 722 | 688 | |
| 723 | 689 | // Register user's onRestore callback if provided |
| 724 | 690 | if (userOnRestore) { |
| 725 | | channel.rollbacks.push(userOnRestore); |
| 726 | | rollbacks += 1; |
| 691 | rollbacks.push(userOnRestore); |
| 727 | 692 | } |
| 728 | 693 | |
| 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 | 704 | try { |
| 730 | 705 | this.#options.optimistic({ |
| 731 | 706 | ...context, |
| 732 | 707 | args, |
| 733 | | helpers: channel.helpers, |
| 708 | helpers, |
| 734 | 709 | onRestore, |
| 735 | 710 | onSuccess(cb) { |
| 736 | 711 | if (expired) { |
| ... | ... | @@ -746,18 +721,14 @@ export class BlockingMutation< |
| 746 | 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 | 727 | } catch (error) { |
| 753 | 728 | expired = true; |
| 754 | 729 | // Roll back the rollbacks we just added |
| 755 | 730 | let next; |
| 756 | | while ( |
| 757 | | next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0] |
| 758 | | ) { |
| 759 | | next(); |
| 760 | | } |
| 731 | while (next = rollbacks.pop()) next(); |
| 761 | 732 | return Promise.reject(error); |
| 762 | 733 | } |
| 763 | 734 | expired = true; |
| ... | ... | @@ -778,11 +749,7 @@ export class BlockingMutation< |
| 778 | 749 | ) { |
| 779 | 750 | // No-op detected - rollback optimistic update |
| 780 | 751 | let next; |
| 781 | | while ( |
| 782 | | next = channel.rollbacks.splice(channel.rollbacks.length - rollbacks, 1)[0] |
| 783 | | ) { |
| 784 | | next(); |
| 785 | | } |
| 752 | while (next = rollbacks.pop()) next(); |
| 786 | 753 | |
| 787 | 754 | // Clear debounce timer |
| 788 | 755 | if (channel.debounceTimer !== null) { |
| ... | ... | @@ -810,9 +777,10 @@ export class BlockingMutation< |
| 810 | 777 | channel.pendingDebounced = { |
| 811 | 778 | args, |
| 812 | 779 | context, |
| 813 | | rollbackCount: rollbacks, |
| 780 | rollbacks, |
| 814 | 781 | pending: [{ resolve, reject }], |
| 815 | 782 | onSuccess, |
| 783 | refetches, |
| 816 | 784 | initialSnapshot: isFirstDebouncedCall ? initialSnapshot : undefined, |
| 817 | 785 | shouldCallGlobalHandler, |
| 818 | 786 | }; |
| ... | ... | @@ -826,9 +794,10 @@ export class BlockingMutation< |
| 826 | 794 | // Subsequent debounced call - update state |
| 827 | 795 | channel.pendingDebounced.args = args; |
| 828 | 796 | channel.pendingDebounced.context = context; |
| 829 | | channel.pendingDebounced.rollbackCount = rollbacks; |
| 797 | channel.pendingDebounced.rollbacks = rollbacks; |
| 830 | 798 | channel.pendingDebounced.pending.push({ resolve, reject }); |
| 831 | 799 | channel.pendingDebounced.onSuccess = onSuccess; |
| 800 | channel.pendingDebounced.refetches = refetches; |
| 832 | 801 | channel.pendingDebounced.shouldCallGlobalHandler = shouldCallGlobalHandler; |
| 833 | 802 | // Keep the initial snapshot from the first call |
| 834 | 803 | // Status stays "waiting" |
| ... | ... | @@ -849,18 +818,15 @@ export class BlockingMutation< |
| 849 | 818 | } |
| 850 | 819 | |
| 851 | 820 | #rollbackPendingDebounced( |
| 852 | | channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>, |
| 821 | channel: Channel<Args, Result, Context<Config, Auth>>, |
| 853 | 822 | ) { |
| 854 | 823 | if (!channel.pendingDebounced) return; |
| 855 | 824 | |
| 856 | | const { rollbackCount } = channel.pendingDebounced; |
| 825 | const { rollbacks } = channel.pendingDebounced; |
| 857 | 826 | |
| 858 | 827 | // Roll back this call's optimistic updates (in reverse order) |
| 859 | | // Remove from the end of the rollbacks array |
| 860 | | for (let i = 0; i < rollbackCount; i++) { |
| 861 | | const rollback = channel.rollbacks.pop(); |
| 862 | | if (rollback) rollback(); |
| 863 | | } |
| 828 | let next; |
| 829 | while (next = rollbacks.pop()) next(); |
| 864 | 830 | |
| 865 | 831 | // Note: We do NOT reject the promises here |
| 866 | 832 | // They will all resolve when the final call completes |
| ... | ... | @@ -868,7 +834,7 @@ export class BlockingMutation< |
| 868 | 834 | |
| 869 | 835 | #enqueueDebouncedCall( |
| 870 | 836 | key: string, |
| 871 | | channel: Channel<Args, Result, Config["optimisticHelpers"], Context<Config, Auth>>, |
| 837 | channel: Channel<Args, Result, Context<Config, Auth>>, |
| 872 | 838 | ) { |
| 873 | 839 | // Clear timer |
| 874 | 840 | channel.debounceTimer = null; |
| ... | ... | @@ -879,7 +845,8 @@ export class BlockingMutation< |
| 879 | 845 | return; |
| 880 | 846 | } |
| 881 | 847 | |
| 882 | | const { args, context, rollbackCount, pending, onSuccess, shouldCallGlobalHandler } = channel.pendingDebounced; |
| 848 | const { args, context, rollbacks, pending, onSuccess, refetches, shouldCallGlobalHandler } = |
| 849 | channel.pendingDebounced; |
| 883 | 850 | channel.pendingDebounced = null; |
| 884 | 851 | |
| 885 | 852 | // Track execution time for debounceImmediate |
| ... | ... | @@ -928,7 +895,8 @@ export class BlockingMutation< |
| 928 | 895 | channel.queue.push({ |
| 929 | 896 | args, |
| 930 | 897 | context, |
| 931 | | rollbacks: rollbackCount, |
| 898 | rollbacks, |
| 899 | refetches, |
| 932 | 900 | onSuccess, |
| 933 | 901 | resolve: wrapperResolve, |
| 934 | 902 | reject: wrapperReject, |