Skip to content
Source
Sign inSign up
TanStack/db

feat: Add flexible matching strategies for electric-db-collection (#402) #499

MergedKyleAMathewsmerged 23 commits intomain fromrefs/pull/499/headmerged by KyleAMathews

KyleAMathewscommented

Summary

This PR adds a new awaitMatch utility function to electric-db-collection, enabling custom synchronization matching logic for backends that cannot provide PostgreSQL transaction IDs. It also reduces the default timeout for awaitTxId from 30 seconds to 5 seconds for faster feedback.

New Features

collection.utils.awaitMatch() Utility

For cases where transaction IDs aren't available, use the awaitMatch utility function with custom matching logic:

import { isChangeMessage } from '@tanstack/electric-db-collection'

const todosCollection = createCollection(
  electricCollectionOptions({
    onInsert: async ({ transaction, collection }) => {
      const newItem = transaction.mutations[0].modified
      await api.todos.create(newItem)

      // Wait for sync using custom match logic
      await collection.utils.awaitMatch(
        (message) => isChangeMessage(message) &&
                     message.headers.operation === 'insert' &&
                     message.value.text === newItem.text,
        5000 // timeout in ms (optional, defaults to 5000)
      )
    }
  })
)

Helper Functions

Export utility functions for custom match logic:

  • isChangeMessage(message) - Check if message is a data change (insert/update/delete)
  • isControlMessage(message) - Check if message is a control message (up-to-date, must-refetch)

Use in Custom Optimistic Actions

const addTodoAction = createOptimisticAction({
  onMutate: ({ text }) => {
    const tempId = crypto.randomUUID()
    todosCollection.insert({ id: tempId, text, completed: false })
  },
  mutationFn: async ({ text }) => {
    await api.todos.create({ data: { text, completed: false } })
    
    // Wait for matching message
    await todosCollection.utils.awaitMatch(
      (message) => isChangeMessage(message) && 
                   message.headers.operation === 'insert' &&
                   message.value.text === text
    )
  }
})

Breaking Changes

  • Default timeout for awaitTxId reduced from 30 seconds to 5 seconds for faster feedback when txids don't match

Benefits

  • Flexible: Supports backends that can't provide transaction IDs
  • Heuristic Matching: Custom logic for finding synchronized data
  • Backward Compatible: Works alongside existing { txid } approach (though default timeout changed)
  • Type-safe: Full TypeScript support
  • Faster Feedback: 5 second timeout provides quicker error detection

Test plan

  • All existing tests pass
  • New tests for awaitMatch utility with custom match functions
  • Timeout behavior testing
  • Integration tests with Electric stream simulation
  • Linting and type checking passes

🤖 Generated with Claude Code

    1. changeset-bot[bot](GitHub profile, opens in a new tab)commented

      🦋 Changeset detected

      Latest commit: 7d1c7df1e6be820e4ba8353fb8eb6e820e7b84e8

      The changes in this PR will be included in the next version bump.

      This PR includes changesets to release 2 packages
      NameType
      @tanstack/electric-db-collectionPatch
      @tanstack/db-example-react-todoPatch

      Not sure what this means? Click here to learn what changesets are.

      Click here if you're a maintainer who wants to add another changeset to this PR

    2. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented
      More templates

      @tanstack/angular-db

      npm i https://pkg.pr.new/@tanstack/angular-db@499

      @tanstack/db

      npm i https://pkg.pr.new/@tanstack/db@499

      @tanstack/db-ivm

      npm i https://pkg.pr.new/@tanstack/db-ivm@499

      @tanstack/electric-db-collection

      npm i https://pkg.pr.new/@tanstack/electric-db-collection@499

      @tanstack/query-db-collection

      npm i https://pkg.pr.new/@tanstack/query-db-collection@499

      @tanstack/react-db

      npm i https://pkg.pr.new/@tanstack/react-db@499

      @tanstack/rxdb-db-collection

      npm i https://pkg.pr.new/@tanstack/rxdb-db-collection@499

      @tanstack/solid-db

      npm i https://pkg.pr.new/@tanstack/solid-db@499

      @tanstack/svelte-db

      npm i https://pkg.pr.new/@tanstack/svelte-db@499

      @tanstack/trailbase-db-collection

      npm i https://pkg.pr.new/@tanstack/trailbase-db-collection@499

      @tanstack/vue-db

      npm i https://pkg.pr.new/@tanstack/vue-db@499

      commit: 7d1c7df

    3. github-actions[bot](GitHub profile, opens in a new tab)commented

      Size Change: +14 B (+0.02%)

      Total Size: 76 kB

      FilenameSizeChange
      ./packages/db/dist/esm/collection/mutations.js2.52 kB+14 B (+0.56%)
      ℹ️ View Unchanged
      FilenameSize
      ./packages/db/dist/esm/collection/change-events.js963 B
      ./packages/db/dist/esm/collection/changes.js1.01 kB
      ./packages/db/dist/esm/collection/events.js660 B
      ./packages/db/dist/esm/collection/index.js3.31 kB
      ./packages/db/dist/esm/collection/indexes.js1.16 kB
      ./packages/db/dist/esm/collection/lifecycle.js1.82 kB
      ./packages/db/dist/esm/collection/state.js3.82 kB
      ./packages/db/dist/esm/collection/subscription.js1.83 kB
      ./packages/db/dist/esm/collection/sync.js1.65 kB
      ./packages/db/dist/esm/deferred.js230 B
      ./packages/db/dist/esm/errors.js3.1 kB
      ./packages/db/dist/esm/index.js1.58 kB
      ./packages/db/dist/esm/indexes/auto-index.js828 B
      ./packages/db/dist/esm/indexes/base-index.js835 B
      ./packages/db/dist/esm/indexes/btree-index.js2 kB
      ./packages/db/dist/esm/indexes/lazy-index.js1.21 kB
      ./packages/db/dist/esm/indexes/reverse-index.js577 B
      ./packages/db/dist/esm/local-only.js827 B
      ./packages/db/dist/esm/local-storage.js2.02 kB
      ./packages/db/dist/esm/optimistic-action.js294 B
      ./packages/db/dist/esm/proxy.js3.86 kB
      ./packages/db/dist/esm/query/builder/functions.js615 B
      ./packages/db/dist/esm/query/builder/index.js4.04 kB
      ./packages/db/dist/esm/query/builder/ref-proxy.js938 B
      ./packages/db/dist/esm/query/compiler/evaluators.js1.55 kB
      ./packages/db/dist/esm/query/compiler/expressions.js760 B
      ./packages/db/dist/esm/query/compiler/group-by.js2.04 kB
      ./packages/db/dist/esm/query/compiler/index.js2.04 kB
      ./packages/db/dist/esm/query/compiler/joins.js2.52 kB
      ./packages/db/dist/esm/query/compiler/order-by.js1.21 kB
      ./packages/db/dist/esm/query/compiler/select.js1.28 kB
      ./packages/db/dist/esm/query/ir.js785 B
      ./packages/db/dist/esm/query/live-query-collection.js340 B
      ./packages/db/dist/esm/query/live/collection-config-builder.js2.69 kB
      ./packages/db/dist/esm/query/live/collection-subscriber.js1.92 kB
      ./packages/db/dist/esm/query/optimizer.js3.08 kB
      ./packages/db/dist/esm/SortedMap.js1.24 kB
      ./packages/db/dist/esm/transactions.js3 kB
      ./packages/db/dist/esm/utils.js1.01 kB
      ./packages/db/dist/esm/utils/browser-polyfills.js365 B
      ./packages/db/dist/esm/utils/btree.js6.01 kB
      ./packages/db/dist/esm/utils/comparison.js754 B
      ./packages/db/dist/esm/utils/index-optimization.js1.73 kB
      compressed-size-action::db-package-size
    4. github-actions[bot](GitHub profile, opens in a new tab)commented

      Size Change: 0 B

      Total Size: 1.47 kB

      ℹ️ View Unchanged
      FilenameSize
      ./packages/react-db/dist/esm/index.js152 B
      ./packages/react-db/dist/esm/useLiveQuery.js1.32 kB
      compressed-size-action::react-db-package-size
    5. @@ -75,13 +84,14 @@
      7584 T extends Row<unknown> = Row<unknown>,
      7685 TSchema extends StandardSchemaV1 = never,
      77-> extends BaseCollectionConfig<
      78- T,
      79- string | number,
      80- TSchema,
      81- Record<string, Fn>,
      82- { txid: Txid | Array<Txid> }
      83- > {
      86+> {
      8487 /**
      8588 * Configuration options for the ElectricSQL ShapeStream
      8689 */
      8790 shapeOptions: ShapeStreamOptions<GetExtensions<T>>
      91+
      92+ /**
      93+ * All standard Collection configuration properties
      94+ */
      95+ id?: string
      96+ schema?: TSchema
      97+ getKey: CollectionConfig<T, string | number, TSchema>[`getKey`]
      kevin-dp(GitHub profile, opens in a new tab)commented

      Most of these properties and methods (getKey, onInsert, etc.) are defined in the BaseCollectionConfig. Let's not introduce them here but extend the BaseCollectionConfig class as it used to do and only add Electric-specific things that are not part of the base config.

      This PR originally predates the refactor when BaseCollectionConfig was introduced - all these props were here and modified in the first commit to this PR. I think Claude has not caught that context when addressing the merge conflict when merging in main.

      Yeah i was expecting that it had rebased correctly. Anyways, it will have to do that :)

    6. @@ -230,7 +230,8 @@
      230230
      231231 // Apply mutations to the new transaction
      232232 directOpTransaction.applyMutations(mutations)
      233- directOpTransaction.commit()
      233+ // Errors still reject tx.isPersisted.promise; this catch only prevents global unhandled rejections
      234+ directOpTransaction.commit().catch(() => undefined)
      234235
      235236 // Add the transaction to the collection's transactions store
      236237 state.transactions.set(directOpTransaction.id, directOpTransaction)
      kevin-dp(GitHub profile, opens in a new tab)commented

      If the commit fails, do we still want to store this TX ID in the state.transactions?

      yes because the transaction still exists even if it failed

    7. samwillis approved these changes

      Other than the comment on removing the duplicate interface we needs addressing before being merged, all look ok.

      Question I do have is on why have two different methods for awaiting a match. We have this returned object with a txid or match function, as well as the utility functions to do the same. Could we standardise on just one way to do this?

      The advantages of the unity methods is that you can compose multiple together, awaiting both/either a txid or another match, where with the returned value you can't. If a mutation functions calls multiple backend apis that all do inserts/udates, there could be multiple txids to await, the utility functions handle that well.

      I think it also makes it conceptional easer to understand, your mutation function returns when the transaction is over, rather than it returning a value that tells the system when the transaction is over.

      I'm approving as I know you are keen to get this out, but wanted to flag those thoughts.

      @@ -54,8 +54,13 @@
      5454
      5555 ### Persistence Handlers
      5656
      57+Handlers are called before mutations and support three different matching strategies:
      58+
      5759 - `onInsert`: Handler called before insert operations
      5860 - `onUpdate`: Handler called before update operations
      5961 - `onDelete`: Handler called before delete operations
      6062
      61-## Persistence Handlers
      63+Each handler can return:
      64+- `{ txid: number | number[] }` - Txid strategy (recommended)
      65+- `{ matchFn: (message) => boolean, timeout?: number }` - Custom match function strategy
      66+- `{}` - Void strategy (3-second timeout)
      samwilliscommented

      Could we let a user return the timeout on the void strategy?

      Suggested change
      66-- `{}` - Void strategy (3-second timeout)
      66+- `{ timeout?: number }` - Void strategy (default 3-second timeout)
    8. @@ -253,7 +445,16 @@
      445+ pendingMatches.setState((current) => {
      446+ const newMatches = new Map(current)
      447+ const existing = newMatches.get(matchId)
      448+ if (existing) {
      449+ newMatches.set(matchId, { ...existing, matched: true })
      450+ }
      451+ return newMatches
      452+ })
      453+ return true
      253454 }
      455+ return false
      456+ }
      254457
      255- // Handle both single txid and array of txids
      256- if (Array.isArray(txid)) {
      257- await Promise.all(txid.map((id) => awaitTxId(id)))
      258- } else {
      259- await awaitTxId(txid)
      458+ // Check against current batch messages first to handle race conditions
      459+ for (const message of currentBatchMessages.state) {
      460+ if (checkMatch(message)) {
      kevin-dp(GitHub profile, opens in a new tab)commented

      Why is checkMatch looking up the match and setting match.matched to true if we are also doing that here on L465? Isn't L465 going to override whatever we set on L449?

    9. @@ -260,0 +501,21 @@
      501+ const awaitVoid = async (timeout: number = 3000): Promise<boolean> => {
      502+ debug(`awaitVoid called with timeout %dms`, timeout)
      503+ return new Promise((resolve) => {
      504+ setTimeout(() => {
      505+ debug(`awaitVoid completed after %dms`, timeout)
      506+ resolve(true)
      507+ }, timeout)
      508+ })
      509+ }
      510+
      511+ /**
      512+ * Process matching strategy and wait for synchronization
      513+ */
      514+ const processMatchingStrategy = async (
      515+ result: MatchingStrategy<any>
      516+ ): Promise<void> => {
      517+ // Check for txid strategy (backward compatible)
      518+ if (`txid` in result) {
      519+ // Handle both single txid and array of txids
      520+ if (Array.isArray(result.txid)) {
      521+ await Promise.all(result.txid.map((id) => awaitTxId(id)))
      kevin-dp(GitHub profile, opens in a new tab)commented

      nit: we can shorten result.txid.map((id) => awaitTxId(id)) to result.txid.map(awaitTxId)

    10. Good work, this is almost ready to be merged. We just need to fix the rebase that went a bit wrong (i.e. use the BaseCollectionConfig to inherit common properties) and extract some of the logic to helper functions.

      @@ -415,6 +698,21 @@
      415698 for (const message of messages) {
      699+ // Add message to current batch buffer (for race condition handling)
      700+ if (isChangeMessage(message)) {
      701+ currentBatchMessages.setState((currentBuffer) => {
      702+ const newBuffer = [...currentBuffer, message]
      703+ // Limit buffer size for safety
      704+ if (newBuffer.length > MAX_BATCH_MESSAGES) {
      705+ newBuffer.splice(0, newBuffer.length - MAX_BATCH_MESSAGES)
      706+ }
      707+ return newBuffer
      708+ })
      709+ }
      710+
      416711 // Check for txids in the message and add them to our store
      417712 if (hasTxids(message)) {
      418713 message.headers.txids?.forEach((txid) => newTxids.add(txid))
      419714 }
      420715
      716+ // Check pending matches against this message
      717+ // Note: matchFn will mark matches internally, we don't resolve here
      718+ const matchesToRemove: Array<string> = []
      kevin-dp(GitHub profile, opens in a new tab)commented

      It's worth extracting this logic to clean up matches into a helper function and call the helper function here in order to keep the code readable and concise.

      @@ -491,3 +817,6 @@
      491817 newSnapshots.length = 0
      492818 return seen
      493819 })
      820+
      821+ // Resolve all matched pending matches on up-to-date
      822+ const matchesToResolve: Array<string> = []
      kevin-dp(GitHub profile, opens in a new tab)commented

      It's worth also extracting this logic to clean up matches into a helper function and call the helper function here in order to keep the code readable and concise.

    11. samwillis approved these changes

      :shipit: great work!

    12. KyleAMathews merged this3cb5180

    13. KyleAMathews closed this

Sign in to join this conversation.