Open History to see the last commit
1import pDefer from 'p-defer'
2import type { DiffTriggerOperation } from '@powersync/common'
3import type { DeferredPromise } from 'p-defer'
4
5export type PendingOperation = {
6 tableName: string
7 operation: DiffTriggerOperation
8 id: string
9 timestamp: string
10}
11
12/**
13 * Optimistic mutations have their optimistic state discarded once transactions have
14 * been applied.
15 * We need to ensure that an applied transaction has been observed by the sync diff trigger
16 * before resolving the transaction application call.
17 * This store allows registering a wait for a pending operation to have been observed.
18 */
19export class PendingOperationStore {
20 private pendingOperations = new Map<PendingOperation, DeferredPromise<void>>()
21
22 /**
23 * Globally accessible PendingOperationStore
24 */
25 static GLOBAL = new PendingOperationStore()
26
27 /**
28 * @returns A promise which will resolve once the specified operation has been seen.
29 */
30 waitFor(operation: PendingOperation): Promise<void> {
31 const managedPromise = pDefer<void>()
32 this.pendingOperations.set(operation, managedPromise)
33 return managedPromise.promise
34 }
35
36 /**
37 * Marks a set of operations as seen. This will resolve any pending promises.
38 */
39 resolvePendingFor(operations: Array<PendingOperation>) {
40 for (const operation of operations) {
41 for (const [pendingOp, deferred] of this.pendingOperations.entries()) {
42 if (
43 pendingOp.tableName == operation.tableName &&
44 pendingOp.operation == operation.operation &&
45 pendingOp.id == operation.id &&
46 pendingOp.timestamp == operation.timestamp
47 ) {
48 deferred.resolve()
49 this.pendingOperations.delete(pendingOp)
50 }
51 }
52 }
53 }
54}