UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

1 lines • 4.93 kB
{"version":3,"file":"queueStrategy.cjs","names":["LiteQueuer","runWithCommitCompletion","QueueDisposedError"],"sources":["../../../src/strategies/queueStrategy.ts"],"sourcesContent":["import { LiteQueuer } from '@tanstack/pacer-lite/lite-queuer'\nimport { QueueDisposedError } from '../errors'\nimport { runWithCommitCompletion } from './commit-completion'\nimport type { QueueStrategy, QueueStrategyOptions } from './types'\nimport type { Transaction } from '../transactions'\n\n/**\n * Creates a queue strategy that processes admitted mutations in order with proper serialization.\n *\n * Unlike other strategies that may drop executions, queue ensures every\n * admitted mutation is attempted sequentially. Each transaction commit completes before\n * the next one starts. Useful when data consistency is critical and\n * every admitted operation must be attempted in order. When a bounded queue is\n * full, the returned transaction fails and its optimistic mutation rolls back.\n * Cleanup stops new admission. The existing timer drains admitted waiting work\n * at its configured pace behind earlier writes. Cleanup does not wait for settlement.\n *\n * **Error handling behavior:**\n * - If a mutation fails, it is NOT automatically retried - the transaction transitions to \"failed\" state\n * - Failed mutations surface their error via `transaction.when('settled')` (which will reject)\n * - Subsequent mutations continue processing - a single failure does not block the queue\n * - Each mutation is independent; there is no all-or-nothing transaction semantics\n *\n * @param options - Configuration for queue behavior (FIFO/LIFO, timing, size limits)\n * @returns A queue strategy instance\n *\n * @example\n * ```ts\n * // FIFO queue - process in order received\n * const mutate = usePacedMutations({\n * mutationFn: async ({ transaction }) => {\n * await api.save(transaction.mutations)\n * },\n * strategy: queueStrategy({\n * wait: 200,\n * addItemsTo: 'back',\n * getItemsFrom: 'front'\n * })\n * })\n * ```\n *\n * @example\n * ```ts\n * // LIFO queue - process most recent first\n * const mutate = usePacedMutations({\n * mutationFn: async ({ transaction }) => {\n * await api.save(transaction.mutations)\n * },\n * strategy: queueStrategy({\n * wait: 200,\n * addItemsTo: 'back',\n * getItemsFrom: 'back'\n * })\n * })\n * ```\n */\nexport function queueStrategy(options?: QueueStrategyOptions): QueueStrategy {\n // Manual promise chaining to ensure async serialization\n // LiteQueuer (unlike AsyncQueuer from @tanstack/pacer) lacks built-in async queue\n // primitives and concurrency control. We compensate by manually chaining promises\n // to ensure each transaction completes before the next one starts.\n let processingChain = Promise.resolve()\n let disposed = false\n\n const queuer = new LiteQueuer<{\n run: () => Transaction\n onCommit?: () => Promise<unknown> | undefined\n }>(\n ({ run, onCommit }) => {\n // Chain each transaction to the previous one's completion\n processingChain = processingChain\n .then(async () => {\n // A rolled-back receipt can settle before its backend handler returns.\n await runWithCommitCompletion(run, onCommit)\n })\n .catch(() => {\n // Errors are handled via transaction.when(`settled`) and surfaced there.\n // This catch prevents unhandled promise rejections from breaking the chain,\n // ensuring subsequent transactions can still execute even if one fails.\n })\n },\n {\n wait: options?.wait ?? 0,\n maxSize: options?.maxSize,\n addItemsTo: options?.addItemsTo ?? `back`, // Default FIFO: add to back\n getItemsFrom: options?.getItemsFrom ?? `front`, // Default FIFO: get from front\n started: true, // Start processing immediately\n },\n )\n\n return {\n _type: `queue`,\n options,\n execute: <T extends object = Record<string, unknown>>(\n fn: () => Transaction<T>,\n _onAdmit?: () => void,\n onCommit?: () => Promise<unknown> | undefined,\n ) => {\n if (disposed) throw new QueueDisposedError()\n return queuer.addItem({ run: fn as () => Transaction, onCommit })\n },\n cleanup: () => {\n disposed = true\n if (queuer.isEmpty) queuer.stop()\n },\n }\n}\n"],"mappings":";;;AAwDA,SAAgB,cAAc,SAA+C;CAK3E,IAAI,kBAAkB,QAAQ,QAAQ;CACtC,IAAI,WAAW;CAEf,MAAM,SAAS,IAAIA,oBAAAA,YAIhB,EAAE,KAAK,eAAe;EAErB,kBAAkB,gBACf,KAAK,YAAY;GAEhB,MAAMC,0BAAAA,wBAAwB,KAAK,QAAQ;EAC7C,CAAC,CAAA,CACA,YAAY,CAIb,CAAC;CACL,GACA;EACE,MAAM,SAAS,QAAQ;EACvB,SAAS,SAAS;EAClB,YAAY,SAAS,cAAc;EACnC,cAAc,SAAS,gBAAgB;EACvC,SAAS;CACX,CACF;CAEA,OAAO;EACL,OAAO;EACP;EACA,UACE,IACA,UACA,aACG;GACH,IAAI,UAAU,MAAM,IAAIC,eAAAA,mBAAmB;GAC3C,OAAO,OAAO,QAAQ;IAAE,KAAK;IAAyB;GAAS,CAAC;EAClE;EACA,eAAe;GACb,WAAW;GACX,IAAI,OAAO,SAAS,OAAO,KAAK;EAClC;CACF;AACF"}