Skip to content

Commit d65a4c2

Browse files
committed
add a sequence number to transactions for sorting
1 parent 2636202 commit d65a4c2

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

.changeset/khaki-cougars-give.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@tanstack/db": patch
3+
---
4+
5+
add a sequence number to transactions to when sorting we can ensure that those created in the same ms are sorted in the correct order

packages/db/src/collection.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -277,8 +277,8 @@ export class CollectionImpl<
277277
throw new Error(`Collection requires a sync config`)
278278
}
279279

280-
this.transactions = new SortedMap<string, Transaction<any>>(
281-
(a, b) => a.createdAt.getTime() - b.createdAt.getTime()
280+
this.transactions = new SortedMap<string, Transaction<any>>((a, b) =>
281+
a.compareCreatedAt(b)
282282
)
283283

284284
this.config = config

packages/db/src/transactions.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import type {
1212
const transactions: Array<Transaction<any>> = []
1313
let transactionStack: Array<Transaction<any>> = []
1414

15+
let sequenceNumber = 0
16+
1517
export function createTransaction<
1618
TData extends object = Record<string, unknown>,
1719
>(config: TransactionConfig<TData>): Transaction<TData> {
@@ -54,6 +56,7 @@ export class Transaction<
5456
public isPersisted: Deferred<Transaction<T, TOperation>>
5557
public autoCommit: boolean
5658
public createdAt: Date
59+
public sequenceNumber: number
5760
public metadata: Record<string, unknown>
5861
public error?: {
5962
message: string
@@ -71,6 +74,7 @@ export class Transaction<
7174
this.isPersisted = createDeferred<Transaction<T, TOperation>>()
7275
this.autoCommit = config.autoCommit ?? true
7376
this.createdAt = new Date()
77+
this.sequenceNumber = sequenceNumber++
7478
this.metadata = config.metadata ?? {}
7579
}
7680

@@ -200,4 +204,19 @@ export class Transaction<
200204

201205
return this
202206
}
207+
208+
/**
209+
* Compare two transactions by their createdAt time and sequence number in order
210+
* to sort them in the order they were created.
211+
* @param other - The other transaction to compare to
212+
* @returns -1 if this transaction was created before the other, 1 if it was created after, 0 if they were created at the same time
213+
*/
214+
compareCreatedAt(other: Transaction<any>): number {
215+
const createdAtComparison =
216+
this.createdAt.getTime() - other.createdAt.getTime()
217+
if (createdAtComparison !== 0) {
218+
return createdAtComparison
219+
}
220+
return this.sequenceNumber - other.sequenceNumber
221+
}
203222
}

0 commit comments

Comments
 (0)