feat: Add flexible matching strategies for electric-db-collection (#402) #499
MergedKyleAMathewsmerged 23 commits into
main fromrefs/pull/499/headmerged by KyleAMathews - @@ -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 ShapeStream8689 */8790 shapeOptions: ShapeStreamOptions<GetExtensions<T>>91+92+ /**93+ * All standard Collection configuration properties94+ */95+ id?: string96+ schema?: TSchema97+ getKey: CollectionConfig<T, string | number, TSchema>[`getKey`]
- @@ -230,7 +230,8 @@230230231231 // Apply mutations to the new transaction232232 directOpTransaction.applyMutations(mutations)233- directOpTransaction.commit()233+ // Errors still reject tx.isPersisted.promise; this catch only prevents global unhandled rejections234+ directOpTransaction.commit().catch(() => undefined)234235235236 // Add the transaction to the collection's transactions store236237 state.transactions.set(directOpTransaction.id, directOpTransaction)
samwillis approved these changes
@@ -54,8 +54,13 @@54545555 ### Persistence Handlers565657+Handlers are called before mutations and support three different matching strategies:58+5759 `onInsert`: Handler called before insert operations5860 `onUpdate`: Handler called before update operations5961 `onDelete`: Handler called before delete operations606261-## Persistence Handlers63+Each handler can return:64+`{ txid: number | number[] }` - Txid strategy (recommended)65+`{ matchFn: (message) => boolean, timeout?: number }` - Custom match function strategy66+`{}` - Void strategy (3-second timeout)- @@ -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 newMatches452+ })453+ return true253454 }455+ return false456+ }254457255- // Handle both single txid and array of txids256- 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 conditions459+ for (const message of currentBatchMessages.state) {460+ if (checkMatch(message)) {
- @@ -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 synchronization513+ */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 txids520+ if (Array.isArray(result.txid)) {521+ await Promise.all(result.txid.map((id) => awaitTxId(id)))
- @@ -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 safety704+ if (newBuffer.length > MAX_BATCH_MESSAGES) {705+ newBuffer.splice(0, newBuffer.length - MAX_BATCH_MESSAGES)706+ }707+ return newBuffer708+ })709+ }710+416711 // Check for txids in the message and add them to our store417712 if (hasTxids(message)) {418713 message.headers.txids?.forEach((txid) => newTxids.add(txid))419714 }420715716+ // Check pending matches against this message717+ // Note: matchFn will mark matches internally, we don't resolve here718+ const matchesToRemove: Array<string> = []@@ -491,3 +817,6 @@491817 newSnapshots.length = 0492818 return seen493819 })820+821+ // Resolve all matched pending matches on up-to-date822+ const matchesToResolve: Array<string> = []
samwillis approved these changes
KyleAMathews merged this3cb5180
KyleAMathews closed this
Sign in to join this conversation.
🦋 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
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