@hyper-fetch/db 0.0.0-stage → 10.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +180 -2
- package/__tests__/e2e/db.e2e.spec.ts +269 -0
- package/__tests__/features/connection/connection.spec.ts +23 -0
- package/__tests__/features/model/live-query.model.spec.ts +320 -0
- package/__tests__/features/operators/operators.spec.ts +113 -0
- package/__tests__/features/runtime/runtime.spec.ts +185 -0
- package/__tests__/features/serializer/serializer.spec.ts +73 -0
- package/__tests__/features/store/store.spec.ts +147 -0
- package/__tests__/features/types/db.types.spec.ts +337 -0
- package/__tests__/integration/audit.spec.ts +639 -0
- package/__tests__/integration/competitors.spec.ts +393 -0
- package/__tests__/integration/convergence.model.spec.ts +162 -0
- package/__tests__/integration/edge-cases.spec.ts +465 -0
- package/__tests__/integration/errors.spec.ts +178 -0
- package/__tests__/integration/infinite.model.spec.ts +142 -0
- package/__tests__/integration/infinite.spec.ts +290 -0
- package/__tests__/integration/inspect.spec.ts +103 -0
- package/__tests__/integration/joins-many.spec.ts +177 -0
- package/__tests__/integration/joins.spec.ts +179 -0
- package/__tests__/integration/key-loaders.spec.ts +196 -0
- package/__tests__/integration/links.spec.ts +105 -0
- package/__tests__/integration/mutations.spec.ts +337 -0
- package/__tests__/integration/normalize.spec.ts +80 -0
- package/__tests__/integration/offline.spec.ts +479 -0
- package/__tests__/integration/queries.spec.ts +513 -0
- package/__tests__/integration/races.spec.ts +127 -0
- package/__tests__/integration/server-operators.spec.ts +123 -0
- package/__tests__/integration/ssr.spec.ts +111 -0
- package/__tests__/integration/syncs.spec.ts +564 -0
- package/__tests__/integration/transactions.spec.ts +344 -0
- package/__tests__/integration/windows.spec.ts +192 -0
- package/__tests__/tsconfig.json +11 -0
- package/__tests__/type-budget/budget.fixture.ts +2476 -0
- package/__tests__/type-budget/tsconfig.json +4 -0
- package/__tests__/utils/fixtures.ts +225 -0
- package/__tests__/utils/random.ts +19 -0
- package/__tests__/vitest.setup.ts +11 -0
- package/dist/collection/collection.d.ts +111 -0
- package/dist/collection/collection.d.ts.map +1 -0
- package/dist/collection/collection.types.d.ts +316 -0
- package/dist/collection/collection.types.d.ts.map +1 -0
- package/dist/collection/resource.types.d.ts +77 -0
- package/dist/collection/resource.types.d.ts.map +1 -0
- package/dist/db/collection.runtime.d.ts +98 -0
- package/dist/db/collection.runtime.d.ts.map +1 -0
- package/dist/db/db.d.ts +154 -0
- package/dist/db/db.d.ts.map +1 -0
- package/dist/db/db.runtime.d.ts +114 -0
- package/dist/db/db.runtime.d.ts.map +1 -0
- package/dist/db/db.types.d.ts +162 -0
- package/dist/db/db.types.d.ts.map +1 -0
- package/dist/graphql/connection.d.ts +25 -0
- package/dist/graphql/connection.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +4220 -0
- package/dist/index.mjs.map +1 -0
- package/dist/mutation/mutation.d.ts +136 -0
- package/dist/mutation/mutation.d.ts.map +1 -0
- package/dist/mutation/mutation.errors.d.ts +6 -0
- package/dist/mutation/mutation.errors.d.ts.map +1 -0
- package/dist/mutation/mutation.utils.d.ts +35 -0
- package/dist/mutation/mutation.utils.d.ts.map +1 -0
- package/dist/operators/operators.d.ts +33 -0
- package/dist/operators/operators.d.ts.map +1 -0
- package/dist/operators/operators.types.d.ts +68 -0
- package/dist/operators/operators.types.d.ts.map +1 -0
- package/dist/operators/operators.utils.d.ts +19 -0
- package/dist/operators/operators.utils.d.ts.map +1 -0
- package/dist/persistence/persistence.d.ts +42 -0
- package/dist/persistence/persistence.d.ts.map +1 -0
- package/dist/persistence/serializer.d.ts +23 -0
- package/dist/persistence/serializer.d.ts.map +1 -0
- package/dist/persistence/snapshot.d.ts +29 -0
- package/dist/persistence/snapshot.d.ts.map +1 -0
- package/dist/persistence/tabs.d.ts +53 -0
- package/dist/persistence/tabs.d.ts.map +1 -0
- package/dist/query/infinite-query.d.ts +59 -0
- package/dist/query/infinite-query.d.ts.map +1 -0
- package/dist/query/live-query.d.ts +85 -0
- package/dist/query/live-query.d.ts.map +1 -0
- package/dist/query/planner.d.ts +57 -0
- package/dist/query/planner.d.ts.map +1 -0
- package/dist/query/query.d.ts +155 -0
- package/dist/query/query.d.ts.map +1 -0
- package/dist/query/query.types.d.ts +71 -0
- package/dist/query/query.types.d.ts.map +1 -0
- package/dist/schema/schema.types.d.ts +33 -0
- package/dist/schema/schema.types.d.ts.map +1 -0
- package/dist/store/store.d.ts +76 -0
- package/dist/store/store.d.ts.map +1 -0
- package/dist/store/store.types.d.ts +27 -0
- package/dist/store/store.types.d.ts.map +1 -0
- package/dist/subset/base-subset.d.ts +66 -0
- package/dist/subset/base-subset.d.ts.map +1 -0
- package/dist/subset/key-subset.d.ts +23 -0
- package/dist/subset/key-subset.d.ts.map +1 -0
- package/dist/subset/list-subset.d.ts +63 -0
- package/dist/subset/list-subset.d.ts.map +1 -0
- package/dist/sync/sync.d.ts +42 -0
- package/dist/sync/sync.d.ts.map +1 -0
- package/dist/utils/request.utils.d.ts +11 -0
- package/dist/utils/request.utils.d.ts.map +1 -0
- package/package.json +71 -4
- package/project.json +4 -0
- package/scripts/docs-typescript.mjs +24 -0
- package/scripts/type-budget.mjs +37 -0
- package/src/collection/collection.ts +330 -0
- package/src/collection/collection.types.ts +383 -0
- package/src/collection/resource.types.ts +114 -0
- package/src/db/collection.runtime.ts +572 -0
- package/src/db/db.runtime.ts +537 -0
- package/src/db/db.ts +451 -0
- package/src/db/db.types.ts +157 -0
- package/src/graphql/connection.ts +23 -0
- package/src/index.ts +16 -0
- package/src/mutation/mutation.errors.ts +7 -0
- package/src/mutation/mutation.ts +776 -0
- package/src/mutation/mutation.utils.ts +58 -0
- package/src/operators/operators.ts +90 -0
- package/src/operators/operators.types.ts +67 -0
- package/src/operators/operators.utils.ts +169 -0
- package/src/persistence/persistence.ts +168 -0
- package/src/persistence/serializer.ts +123 -0
- package/src/persistence/snapshot.ts +76 -0
- package/src/persistence/tabs.ts +86 -0
- package/src/query/infinite-query.ts +206 -0
- package/src/query/live-query.ts +552 -0
- package/src/query/planner.ts +199 -0
- package/src/query/query.ts +319 -0
- package/src/query/query.types.ts +90 -0
- package/src/schema/schema.types.ts +29 -0
- package/src/store/store.ts +300 -0
- package/src/store/store.types.ts +17 -0
- package/src/subset/base-subset.ts +169 -0
- package/src/subset/key-subset.ts +44 -0
- package/src/subset/list-subset.ts +328 -0
- package/src/sync/sync.ts +99 -0
- package/src/utils/request.utils.ts +67 -0
- package/tsconfig.json +12 -0
- package/vite.config.ts +71 -0
|
@@ -0,0 +1,776 @@
|
|
|
1
|
+
import type { ClientInstance } from "@hyper-fetch/core";
|
|
2
|
+
|
|
3
|
+
import type { RowKey } from "../collection/collection.types";
|
|
4
|
+
import type { CollectionRuntime } from "../db/collection.runtime";
|
|
5
|
+
import type { DbRuntime } from "../db/db.runtime";
|
|
6
|
+
import type {
|
|
7
|
+
DbOfflineOptions,
|
|
8
|
+
MutationOperation,
|
|
9
|
+
MutationResult,
|
|
10
|
+
TransactionConfig,
|
|
11
|
+
TransactionRecord,
|
|
12
|
+
TransactionWrite,
|
|
13
|
+
} from "../db/db.types";
|
|
14
|
+
import type { Row } from "../store/store.types";
|
|
15
|
+
import { applyRequestPatches, isPlainObject } from "../utils/request.utils";
|
|
16
|
+
import { DependencyError } from "./mutation.errors";
|
|
17
|
+
import type { AnyResponse, PreparedWrite, Transaction } from "./mutation.utils";
|
|
18
|
+
import {
|
|
19
|
+
combineResults,
|
|
20
|
+
createTransaction,
|
|
21
|
+
defaultRetryDelay,
|
|
22
|
+
isTemporaryFailure,
|
|
23
|
+
rowsOf,
|
|
24
|
+
waitForOnline,
|
|
25
|
+
} from "./mutation.utils";
|
|
26
|
+
|
|
27
|
+
export type { PreparedWrite, Transaction } from "./mutation.utils";
|
|
28
|
+
export { createTransaction, isTemporaryFailure } from "./mutation.utils";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Sends writes. Each write shows at once as an optimistic layer. Writes to one row go out one at a time, and a failure
|
|
32
|
+
* drops the writes queued after it on that row. With `offline`, every write goes through a persisted outbox that is
|
|
33
|
+
* replayed in order across the whole db by one tab.
|
|
34
|
+
*/
|
|
35
|
+
export class MutationEngine {
|
|
36
|
+
/** The outbox, in replay order */
|
|
37
|
+
outbox: TransactionRecord[] = [];
|
|
38
|
+
/** The last write of each row, which the next write to the row waits for while it is pending */
|
|
39
|
+
private chains = new Map<string, { id: string; run: Promise<boolean> }>();
|
|
40
|
+
private inFlight = new Map<string, number>();
|
|
41
|
+
private settleWaiters = new Map<string, (() => void)[]>();
|
|
42
|
+
private resolvers = new Map<string, (result: MutationResult) => void>();
|
|
43
|
+
/** Writes counted as in flight, so a write is counted once however its sending ends */
|
|
44
|
+
private begun = new Set<string>();
|
|
45
|
+
/** Whether each settled write succeeded, so `dependsOn` can name a write that already settled */
|
|
46
|
+
private outcomes = new Map<string, boolean>();
|
|
47
|
+
private outcomeWaiters = new Map<string, ((success: boolean) => void)[]>();
|
|
48
|
+
/** When each write's request was sent, so a sync event that arrived while it was in flight confirms it */
|
|
49
|
+
private sentAt = new Map<string, number>();
|
|
50
|
+
private pumping = false;
|
|
51
|
+
private retryTimer: ReturnType<typeof setTimeout> | undefined;
|
|
52
|
+
private cancelWait = () => {};
|
|
53
|
+
private readonly offline: DbOfflineOptions | undefined;
|
|
54
|
+
|
|
55
|
+
constructor(
|
|
56
|
+
private readonly db: DbRuntime,
|
|
57
|
+
offline: boolean | DbOfflineOptions | undefined,
|
|
58
|
+
private readonly transactions: Record<string, TransactionConfig> = {},
|
|
59
|
+
) {
|
|
60
|
+
this.offline = offline === true ? {} : offline || undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Applies several writes as one transaction. A named transaction sends them through its `mutationFn` as one request.
|
|
65
|
+
* Without a name, each write goes through its collection's `mutate`, in order, and a failure drops the writes after
|
|
66
|
+
* it and refetches the subsets holding the rows already written.
|
|
67
|
+
*/
|
|
68
|
+
submitTransaction = ({
|
|
69
|
+
id,
|
|
70
|
+
name,
|
|
71
|
+
writes,
|
|
72
|
+
}: {
|
|
73
|
+
id: string;
|
|
74
|
+
name: string | undefined;
|
|
75
|
+
writes: PreparedWrite[];
|
|
76
|
+
}): Transaction => {
|
|
77
|
+
if (writes.length === 0) {
|
|
78
|
+
return createTransaction(id, Promise.resolve({ success: true, data: [], error: null }));
|
|
79
|
+
}
|
|
80
|
+
return name === undefined ? this.submitSequence(id, writes) : this.submitNamed(id, name, writes);
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
private createRecord = (write: PreparedWrite & { id: string; dependsOn: string[] }): TransactionRecord => ({
|
|
84
|
+
id: write.id,
|
|
85
|
+
collection: write.collection.name,
|
|
86
|
+
op: write.op,
|
|
87
|
+
key: write.key,
|
|
88
|
+
values: write.values,
|
|
89
|
+
dependsOn: write.dependsOn,
|
|
90
|
+
sent: false,
|
|
91
|
+
createdAt: Date.now(),
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
/** The result promise of a record, resolved once the record settles */
|
|
95
|
+
private track = (record: TransactionRecord) => {
|
|
96
|
+
return new Promise<MutationResult>((resolve) => {
|
|
97
|
+
this.resolvers.set(record.id, resolve);
|
|
98
|
+
this.generations.set(record.id, this.db.generation);
|
|
99
|
+
});
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
private submitSequence = (id: string, writes: PreparedWrite[]): Transaction => {
|
|
103
|
+
const records = writes.map((write, index) =>
|
|
104
|
+
this.createRecord({ ...write, id: `${id}:${index}`, dependsOn: index > 0 ? [`${id}:${index - 1}`] : [] }),
|
|
105
|
+
);
|
|
106
|
+
const results = records.map(this.track);
|
|
107
|
+
this.db.batch(() => {
|
|
108
|
+
writes.forEach((write, index) => {
|
|
109
|
+
if (write.collection.config.mutations[write.op]?.optimistic !== false) {
|
|
110
|
+
write.collection.store.addLayer({
|
|
111
|
+
id: records[index].id,
|
|
112
|
+
key: write.key,
|
|
113
|
+
type: write.op,
|
|
114
|
+
values: write.values,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
if (this.offline) {
|
|
120
|
+
// The outbox replays them in order, and a rejected write drops the ones that depend on it
|
|
121
|
+
records.forEach((record) => this.enqueue(record));
|
|
122
|
+
} else {
|
|
123
|
+
this.runSequence(records, results, 0);
|
|
124
|
+
}
|
|
125
|
+
return createTransaction(id, Promise.all(results).then(combineResults));
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/** Sends the writes of an unnamed transaction one after another */
|
|
129
|
+
private runSequence = async (records: TransactionRecord[], results: Promise<MutationResult>[], index: number) => {
|
|
130
|
+
const record = records[index];
|
|
131
|
+
this.runDirect(record);
|
|
132
|
+
const result = await results[index];
|
|
133
|
+
if (!result.success) {
|
|
134
|
+
records.slice(index + 1).forEach((later) => this.fail(later, new DependencyError(record.id)));
|
|
135
|
+
records.slice(0, index).forEach((written) => {
|
|
136
|
+
const collection = this.db.collections.get(written.collection)!;
|
|
137
|
+
collection.getSubsetsHolding(collection.resolveKey(written.key)).forEach((subset) => subset.reload());
|
|
138
|
+
});
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (index + 1 < records.length) {
|
|
142
|
+
await this.runSequence(records, results, index + 1);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
private submitNamed = (id: string, name: string, writes: PreparedWrite[]): Transaction => {
|
|
147
|
+
const transactionWrites: TransactionWrite[] = writes.map((write) => ({
|
|
148
|
+
collection: write.collection.name,
|
|
149
|
+
op: write.op,
|
|
150
|
+
key: write.key,
|
|
151
|
+
values: write.values,
|
|
152
|
+
}));
|
|
153
|
+
const record: TransactionRecord = {
|
|
154
|
+
...this.createRecord({ ...writes[0], id, dependsOn: [] }),
|
|
155
|
+
values: {},
|
|
156
|
+
transaction: { name, writes: transactionWrites },
|
|
157
|
+
};
|
|
158
|
+
const result = this.track(record);
|
|
159
|
+
this.addTransactionLayers(record);
|
|
160
|
+
if (this.offline) {
|
|
161
|
+
this.enqueue(record);
|
|
162
|
+
} else {
|
|
163
|
+
this.runDirect(record);
|
|
164
|
+
}
|
|
165
|
+
return createTransaction(id, result);
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
private addTransactionLayers = (record: TransactionRecord) => {
|
|
169
|
+
this.db.batch(() => {
|
|
170
|
+
record.transaction!.writes.forEach((write, index) => {
|
|
171
|
+
this.db.collections
|
|
172
|
+
.get(write.collection)!
|
|
173
|
+
.store.addLayer({ id: `${record.id}:${index}`, key: write.key, type: write.op, values: write.values });
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
/** Runs a callback for each write of a named transaction, as a plain record with its layer id */
|
|
179
|
+
private eachWrite = (record: TransactionRecord, callback: (write: TransactionRecord) => void) => {
|
|
180
|
+
record.transaction!.writes.forEach((write, index) => {
|
|
181
|
+
callback({ ...record, ...write, id: `${record.id}:${index}`, transaction: undefined });
|
|
182
|
+
});
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/** Applies a write optimistically and sends it */
|
|
186
|
+
submit = ({
|
|
187
|
+
collection,
|
|
188
|
+
op,
|
|
189
|
+
key,
|
|
190
|
+
values,
|
|
191
|
+
dependsOn,
|
|
192
|
+
id,
|
|
193
|
+
temporaryKey,
|
|
194
|
+
}: {
|
|
195
|
+
collection: CollectionRuntime;
|
|
196
|
+
op: MutationOperation;
|
|
197
|
+
key: RowKey;
|
|
198
|
+
values: Row;
|
|
199
|
+
dependsOn: string[];
|
|
200
|
+
id: string;
|
|
201
|
+
temporaryKey?: boolean;
|
|
202
|
+
}): Transaction => {
|
|
203
|
+
const record: TransactionRecord = {
|
|
204
|
+
id,
|
|
205
|
+
collection: collection.name,
|
|
206
|
+
op,
|
|
207
|
+
key,
|
|
208
|
+
values,
|
|
209
|
+
dependsOn,
|
|
210
|
+
sent: false,
|
|
211
|
+
createdAt: Date.now(),
|
|
212
|
+
...(temporaryKey ? { temporaryKey: true } : {}),
|
|
213
|
+
};
|
|
214
|
+
const result = new Promise<MutationResult>((resolve) => {
|
|
215
|
+
this.resolvers.set(id, resolve);
|
|
216
|
+
this.generations.set(id, this.db.generation);
|
|
217
|
+
});
|
|
218
|
+
const mutation = collection.config.mutations[op];
|
|
219
|
+
// Backends that apply writes locally on their own, such as Firestore, would apply them twice with a layer
|
|
220
|
+
if (mutation?.optimistic !== false) {
|
|
221
|
+
this.db.batch(() => collection.store.addLayer({ id, key, type: op, values }));
|
|
222
|
+
}
|
|
223
|
+
if (this.offline && mutation?.outbox !== false) {
|
|
224
|
+
this.enqueue(record);
|
|
225
|
+
} else {
|
|
226
|
+
this.runDirect(record);
|
|
227
|
+
}
|
|
228
|
+
return createTransaction(id, result);
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
/** A write rejected before it was sent, for example by validation */
|
|
232
|
+
reject = (error: unknown, id: string): Transaction => {
|
|
233
|
+
return createTransaction(id, Promise.resolve({ success: false, data: null, error }));
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
/** Whether writes go through the outbox */
|
|
237
|
+
get usesOutbox() {
|
|
238
|
+
return Boolean(this.offline);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Resolves once no write of the collection is in flight */
|
|
242
|
+
settled = (collection: string): Promise<void> => {
|
|
243
|
+
if (!this.inFlight.get(collection)) {
|
|
244
|
+
return Promise.resolve();
|
|
245
|
+
}
|
|
246
|
+
return new Promise((resolve) => {
|
|
247
|
+
this.settleWaiters.set(collection, [...(this.settleWaiters.get(collection) ?? []), resolve]);
|
|
248
|
+
});
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/** Rebuilds the optimistic layers of a restored outbox and replays it */
|
|
252
|
+
restore = (records: TransactionRecord[]) => {
|
|
253
|
+
this.addRecords(records);
|
|
254
|
+
this.persistOutbox();
|
|
255
|
+
this.pump();
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Writes another tab made: a follower sent them to this tab, the leader, or this tab became the leader and adopts the
|
|
260
|
+
* outbox the previous leader persisted. They are persisted together with this tab's own writes and replayed.
|
|
261
|
+
*/
|
|
262
|
+
mergeOutbox = (records: TransactionRecord[]) => {
|
|
263
|
+
this.addRecords(records);
|
|
264
|
+
this.persistOutbox();
|
|
265
|
+
this.pump();
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
/** A new leader asks for the writes followers still wait for */
|
|
269
|
+
resendToLeader = () => {
|
|
270
|
+
if (this.outbox.length > 0) {
|
|
271
|
+
this.db.tabs?.post({ type: "enqueue", records: [...this.outbox] });
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
/** Adds records this tab does not hold yet, with their optimistic layers, in the order they were made */
|
|
276
|
+
private addRecords = (records: TransactionRecord[]) => {
|
|
277
|
+
const fresh = this.replayable(records).filter((record) => !this.outbox.some((item) => item.id === record.id));
|
|
278
|
+
if (fresh.length === 0) {
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
fresh.forEach((record) => this.generations.set(record.id, this.db.generation));
|
|
282
|
+
this.db.batch(() => {
|
|
283
|
+
fresh.forEach((record) => {
|
|
284
|
+
if (record.transaction) {
|
|
285
|
+
this.addTransactionLayers(record);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const collection = this.db.collections.get(record.collection)!;
|
|
289
|
+
collection.store.addLayer({ id: record.id, key: record.key, type: record.op, values: record.values });
|
|
290
|
+
});
|
|
291
|
+
});
|
|
292
|
+
this.outbox = [...this.outbox, ...fresh].toSorted((left, right) => left.createdAt - right.createdAt);
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
/** The records this db can replay. The others are reported, never dropped silently. */
|
|
296
|
+
private replayable = (records: TransactionRecord[]) => {
|
|
297
|
+
return records.filter((record) => {
|
|
298
|
+
const canReplay = record.transaction
|
|
299
|
+
? Boolean(this.transactions[record.transaction.name])
|
|
300
|
+
: Boolean(this.db.collections.get(record.collection)?.config.mutations[record.op]);
|
|
301
|
+
if (!canReplay) {
|
|
302
|
+
const target = record.transaction
|
|
303
|
+
? `the transaction "${record.transaction.name}"`
|
|
304
|
+
: `a write to "${record.collection}"`;
|
|
305
|
+
this.db.emitError({
|
|
306
|
+
type: "outbox",
|
|
307
|
+
error: new Error(`The outbox holds ${target} that the db cannot replay`),
|
|
308
|
+
transaction: record,
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
return canReplay;
|
|
312
|
+
});
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
/** The replaying tab reports a write's outcome */
|
|
316
|
+
applyOutcome = (outcome: { id: string; success: boolean; error?: unknown; key?: RowKey }) => {
|
|
317
|
+
const record = this.outbox.find((item) => item.id === outcome.id);
|
|
318
|
+
if (!record) {
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
this.outbox = this.outbox.filter((item) => item.id !== outcome.id);
|
|
322
|
+
if (outcome.success) {
|
|
323
|
+
const collection = this.db.collections.get(record.collection)!;
|
|
324
|
+
// The leader learned the key the server gave this tab's insert, so the row moves to it as on the leader
|
|
325
|
+
if (record.temporaryKey && outcome.key !== undefined && outcome.key !== record.key) {
|
|
326
|
+
collection.aliases.set(record.key, outcome.key);
|
|
327
|
+
collection.setRenderKey(outcome.key, collection.getRenderKey(record.key));
|
|
328
|
+
collection.store.rekeyLayers(record.key, outcome.key);
|
|
329
|
+
}
|
|
330
|
+
this.keep(record);
|
|
331
|
+
this.resolve(record, { success: true, data: null, error: null });
|
|
332
|
+
} else {
|
|
333
|
+
this.fail(record, outcome.error);
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
/** Replays the outbox when this tab is the one that replays it, one write at a time and in order */
|
|
338
|
+
pump = async () => {
|
|
339
|
+
/* oxlint-disable no-await-in-loop -- writes replay strictly one after another */
|
|
340
|
+
if (!this.offline || this.pumping || !this.db.isLeader) {
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
this.pumping = true;
|
|
344
|
+
await this.db.ready;
|
|
345
|
+
let attempt = 0;
|
|
346
|
+
while (this.outbox.length > 0 && !this.db.isDestroyed) {
|
|
347
|
+
const record = this.outbox[0];
|
|
348
|
+
const client = this.getClient(record);
|
|
349
|
+
if (client && !client.appManager.isOnline) {
|
|
350
|
+
const online = waitForOnline(client);
|
|
351
|
+
this.cancelWait = online.cancel;
|
|
352
|
+
await online.promise;
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
record.sent = true;
|
|
356
|
+
await this.persistOutbox();
|
|
357
|
+
try {
|
|
358
|
+
const response = await this.send(record, true);
|
|
359
|
+
if (!response) {
|
|
360
|
+
this.removeFromOutbox([record.id]);
|
|
361
|
+
} else if (response.success) {
|
|
362
|
+
attempt = 0;
|
|
363
|
+
await this.succeed(record, response);
|
|
364
|
+
this.end(record);
|
|
365
|
+
this.removeFromOutbox([record.id]);
|
|
366
|
+
const serverKey = this.db.collections.get(record.collection)?.resolveKey(record.key);
|
|
367
|
+
this.db.tabs?.post({
|
|
368
|
+
type: "outcome",
|
|
369
|
+
id: record.id,
|
|
370
|
+
success: true,
|
|
371
|
+
...(record.temporaryKey ? { key: serverKey } : {}),
|
|
372
|
+
});
|
|
373
|
+
} else if ((this.offline.retryable ?? isTemporaryFailure)(response)) {
|
|
374
|
+
attempt += 1;
|
|
375
|
+
this.end(record);
|
|
376
|
+
const delay = (this.offline.retryDelay ?? defaultRetryDelay)(attempt);
|
|
377
|
+
await new Promise((resolve) => {
|
|
378
|
+
this.retryTimer = setTimeout(resolve, delay);
|
|
379
|
+
});
|
|
380
|
+
} else {
|
|
381
|
+
attempt = 0;
|
|
382
|
+
this.drop(record, response.error ?? response);
|
|
383
|
+
}
|
|
384
|
+
} catch (error) {
|
|
385
|
+
// A mapping or `mutationFn` that throws can never succeed, so the write is dropped and replay goes on
|
|
386
|
+
attempt = 0;
|
|
387
|
+
this.drop(record, error);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
/* oxlint-enable no-await-in-loop */
|
|
391
|
+
this.pumping = false;
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Drops every pending write, for example on sign-out. Writes in flight resolve as failed now, and their responses,
|
|
396
|
+
* which carry the previous user's data, are never written.
|
|
397
|
+
*/
|
|
398
|
+
clear = () => {
|
|
399
|
+
this.outbox = [];
|
|
400
|
+
this.chains.clear();
|
|
401
|
+
const cleared = { success: false, data: null, error: new Error("Cleared") };
|
|
402
|
+
[...this.resolvers.values()].forEach((resolve) => resolve(cleared));
|
|
403
|
+
this.resolvers.clear();
|
|
404
|
+
this.sentAt.clear();
|
|
405
|
+
this.persistOutbox();
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
/** Stops the retry timer, for `destroy` */
|
|
409
|
+
destroy = () => {
|
|
410
|
+
clearTimeout(this.retryTimer);
|
|
411
|
+
this.cancelWait();
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
/** The generation each write was made or restored in, so `clear` ends the writes of the previous user */
|
|
415
|
+
private generations = new Map<string, number>();
|
|
416
|
+
|
|
417
|
+
/** Whether a write belongs to the current user, rather than to one `clear` ended */
|
|
418
|
+
private isActive = (record: TransactionRecord) => this.generations.get(record.id) === this.db.generation;
|
|
419
|
+
|
|
420
|
+
/** Resolves with whether a write succeeded. A write this db never saw, such as one from another session, is done. */
|
|
421
|
+
private waitForOutcome = (id: string): Promise<boolean> => {
|
|
422
|
+
if (this.outcomes.has(id)) {
|
|
423
|
+
return Promise.resolve(this.outcomes.get(id)!);
|
|
424
|
+
}
|
|
425
|
+
if (!this.resolvers.has(id)) {
|
|
426
|
+
return Promise.resolve(true);
|
|
427
|
+
}
|
|
428
|
+
return new Promise((resolve) => {
|
|
429
|
+
this.outcomeWaiters.set(id, [...(this.outcomeWaiters.get(id) ?? []), resolve]);
|
|
430
|
+
});
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
private enqueue = async (record: TransactionRecord) => {
|
|
434
|
+
const failed = record.dependsOn.find((id) => this.outcomes.get(id) === false);
|
|
435
|
+
if (failed) {
|
|
436
|
+
this.fail(record, new DependencyError(failed));
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
this.outbox.push(record);
|
|
440
|
+
if (!this.db.isLeader) {
|
|
441
|
+
// Only the leader writes the shared outbox, so two tabs never write over each other's writes
|
|
442
|
+
this.db.tabs?.post({ type: "enqueue", records: [record] });
|
|
443
|
+
this.db.notifyChange();
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
await this.persistOutbox();
|
|
447
|
+
this.pump();
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
private persistOutbox = () => {
|
|
451
|
+
this.db.notifyChange();
|
|
452
|
+
if (!this.db.isLeader) {
|
|
453
|
+
return Promise.resolve();
|
|
454
|
+
}
|
|
455
|
+
return this.db.persistence?.saveOutbox(this.outbox) ?? Promise.resolve();
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
private removeFromOutbox = (ids: string[]) => {
|
|
459
|
+
this.outbox = this.outbox.filter((record) => !ids.includes(record.id));
|
|
460
|
+
this.persistOutbox();
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
private runDirect = (record: TransactionRecord) => {
|
|
464
|
+
const chainKey = `${record.collection}:${String(record.key)}`;
|
|
465
|
+
// A write made after the previous one settled does not depend on it, even when it failed
|
|
466
|
+
const last = this.chains.get(chainKey);
|
|
467
|
+
const previous = last && !this.outcomes.has(last.id) ? last.run : Promise.resolve(true);
|
|
468
|
+
// Counted as in flight from now, so a refetch that starts while it waits is newer than it
|
|
469
|
+
this.begin(record);
|
|
470
|
+
const run = previous.then(async (previousSucceeded) => {
|
|
471
|
+
const dependencies = await Promise.all(record.dependsOn.map(this.waitForOutcome));
|
|
472
|
+
const failedDependency = record.dependsOn.find((_id, index) => !dependencies[index]);
|
|
473
|
+
if (!previousSucceeded || failedDependency) {
|
|
474
|
+
this.fail(record, new DependencyError(failedDependency ?? chainKey));
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
if (!this.isActive(record)) {
|
|
478
|
+
return false;
|
|
479
|
+
}
|
|
480
|
+
try {
|
|
481
|
+
const response = await this.send(record, false);
|
|
482
|
+
if (!response) {
|
|
483
|
+
return false;
|
|
484
|
+
}
|
|
485
|
+
if (response.success) {
|
|
486
|
+
await this.succeed(record, response);
|
|
487
|
+
return true;
|
|
488
|
+
}
|
|
489
|
+
this.fail(record, response.error ?? response);
|
|
490
|
+
return false;
|
|
491
|
+
} catch (error) {
|
|
492
|
+
this.fail(record, error);
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
});
|
|
496
|
+
this.chains.set(chainKey, { id: record.id, run });
|
|
497
|
+
run.then(() => {
|
|
498
|
+
this.end(record);
|
|
499
|
+
if (this.chains.get(chainKey)?.run === run) {
|
|
500
|
+
this.chains.delete(chainKey);
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
/** The client a record's request goes through, so replay waits while it is offline */
|
|
506
|
+
private getClient = (record: TransactionRecord): ClientInstance | undefined => {
|
|
507
|
+
if (record.transaction) {
|
|
508
|
+
const config = this.transactions[record.transaction.name];
|
|
509
|
+
return config?.mutationFn({ id: record.id, mutations: record.transaction.writes }).client;
|
|
510
|
+
}
|
|
511
|
+
return this.db.collections.get(record.collection)?.config.mutations[record.op]?.request.client;
|
|
512
|
+
};
|
|
513
|
+
|
|
514
|
+
private send = async (record: TransactionRecord, fromOutbox: boolean): Promise<AnyResponse | undefined> => {
|
|
515
|
+
if (record.transaction) {
|
|
516
|
+
return this.sendNamed(record, fromOutbox);
|
|
517
|
+
}
|
|
518
|
+
const collection = this.db.collections.get(record.collection)!;
|
|
519
|
+
const mutation = collection.config.mutations[record.op];
|
|
520
|
+
if (!mutation) {
|
|
521
|
+
this.fail(record, new Error(`"${record.collection}" declares no ${record.op} mutation`));
|
|
522
|
+
return undefined;
|
|
523
|
+
}
|
|
524
|
+
if (fromOutbox) {
|
|
525
|
+
this.begin(record);
|
|
526
|
+
}
|
|
527
|
+
const key = collection.resolveKey(record.key);
|
|
528
|
+
const context = { id: record.id };
|
|
529
|
+
// `map` is the collection's request mapping, not an array method
|
|
530
|
+
/* oxlint-disable no-array-method-this-argument */
|
|
531
|
+
let patch;
|
|
532
|
+
if (record.op === "insert") {
|
|
533
|
+
const keyField = collection.config.key;
|
|
534
|
+
const withoutKey = Object.fromEntries(Object.entries(record.values).filter(([field]) => field !== keyField));
|
|
535
|
+
patch = mutation.map(record.temporaryKey ? withoutKey : record.values, context);
|
|
536
|
+
} else if (record.op === "update") {
|
|
537
|
+
patch = mutation.map(key, record.values, context);
|
|
538
|
+
} else {
|
|
539
|
+
patch = mutation.map(key, context);
|
|
540
|
+
}
|
|
541
|
+
/* oxlint-enable no-array-method-this-argument */
|
|
542
|
+
let request = applyRequestPatches(mutation.request, [patch]);
|
|
543
|
+
if (fromOutbox) {
|
|
544
|
+
request = request.setOffline(false);
|
|
545
|
+
}
|
|
546
|
+
this.sentAt.set(record.id, this.db.tick());
|
|
547
|
+
return request.send();
|
|
548
|
+
};
|
|
549
|
+
|
|
550
|
+
private sendNamed = (record: TransactionRecord, fromOutbox: boolean): Promise<AnyResponse> => {
|
|
551
|
+
const { name, writes } = record.transaction!;
|
|
552
|
+
if (fromOutbox) {
|
|
553
|
+
this.begin(record);
|
|
554
|
+
}
|
|
555
|
+
let request = this.transactions[name].mutationFn({ id: record.id, mutations: writes });
|
|
556
|
+
if (fromOutbox) {
|
|
557
|
+
request = request.setOffline(false);
|
|
558
|
+
}
|
|
559
|
+
this.sentAt.set(record.id, this.db.tick());
|
|
560
|
+
return request.send();
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
/** A named transaction succeeded: its changes become the server state, or the subsets holding them reload */
|
|
564
|
+
private succeedNamed = async (record: TransactionRecord, response: AnyResponse) => {
|
|
565
|
+
const { onSuccess = "keep" } = this.transactions[record.transaction!.name];
|
|
566
|
+
if (onSuccess === "refetch") {
|
|
567
|
+
this.end(record);
|
|
568
|
+
const refetches: Promise<void>[] = [];
|
|
569
|
+
this.eachWrite(record, (write) => {
|
|
570
|
+
refetches.push(this.refetch(this.db.collections.get(write.collection)!, write));
|
|
571
|
+
});
|
|
572
|
+
await Promise.all(refetches);
|
|
573
|
+
this.removeTransactionLayers(record);
|
|
574
|
+
} else {
|
|
575
|
+
this.keep(record);
|
|
576
|
+
}
|
|
577
|
+
this.resolve(record, { success: true, data: response.data, error: null });
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
private removeTransactionLayers = (record: TransactionRecord) => {
|
|
581
|
+
this.db.batch(() => {
|
|
582
|
+
this.eachWrite(record, (write) => this.db.collections.get(write.collection)!.store.removeLayer(write.id));
|
|
583
|
+
});
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
private succeed = async (record: TransactionRecord, response: AnyResponse) => {
|
|
587
|
+
// After `clear`, the response belongs to the previous user and is never written
|
|
588
|
+
if (!this.isActive(record)) {
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
if (record.transaction) {
|
|
592
|
+
await this.succeedNamed(record, response);
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
const collection = this.db.collections.get(record.collection)!;
|
|
596
|
+
const mutation = collection.config.mutations[record.op]!;
|
|
597
|
+
const key = collection.resolveKey(record.key);
|
|
598
|
+
// The server assigned the key, but the response is not the row, so only the lists the row belongs to can tell it
|
|
599
|
+
if (record.op === "insert" && record.temporaryKey && mutation.onSuccess) {
|
|
600
|
+
this.end(record);
|
|
601
|
+
const lists = [...collection.listSubsets.values()].filter(
|
|
602
|
+
(subset) => subset.hasLoaded && subset.matchesSent(record.values),
|
|
603
|
+
);
|
|
604
|
+
await Promise.all(lists.map((subset) => subset.reload({ waitForWrites: false })));
|
|
605
|
+
this.db.batch(() => collection.store.removeLayer(record.id));
|
|
606
|
+
this.resolve(record, { success: true, data: response.data, error: null });
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
if (mutation.onSuccess === "refetch" || mutation.onSuccess === "sync") {
|
|
610
|
+
this.end(record);
|
|
611
|
+
let confirmed = false;
|
|
612
|
+
if (mutation.onSuccess === "sync") {
|
|
613
|
+
const since = this.sentAt.get(record.id)!;
|
|
614
|
+
confirmed = await this.db.waitForSync({
|
|
615
|
+
collection: record.collection,
|
|
616
|
+
key,
|
|
617
|
+
since,
|
|
618
|
+
timeout: this.db.syncTimeout,
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
if (!confirmed) {
|
|
622
|
+
await this.refetch(collection, record);
|
|
623
|
+
}
|
|
624
|
+
this.db.batch(() => collection.store.removeLayer(record.id));
|
|
625
|
+
this.resolve(record, { success: true, data: response.data, error: null });
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
this.db.batch(() => {
|
|
629
|
+
if (mutation.onSuccess === "keep") {
|
|
630
|
+
this.writeKept(collection, record);
|
|
631
|
+
} else {
|
|
632
|
+
this.writeResponse(collection, record, mutation.row ? mutation.row(response.data) : response.data);
|
|
633
|
+
}
|
|
634
|
+
collection.store.removeLayer(record.id);
|
|
635
|
+
});
|
|
636
|
+
this.resolve(record, { success: true, data: response.data, error: null });
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
/** A write confirmed by another tab: its values become the server state */
|
|
640
|
+
private keep = (record: TransactionRecord) => {
|
|
641
|
+
if (record.transaction) {
|
|
642
|
+
this.db.batch(() => this.eachWrite(record, this.keep));
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
const collection = this.db.collections.get(record.collection)!;
|
|
646
|
+
this.db.batch(() => {
|
|
647
|
+
this.writeKept(collection, record);
|
|
648
|
+
collection.store.removeLayer(record.id);
|
|
649
|
+
});
|
|
650
|
+
};
|
|
651
|
+
|
|
652
|
+
private writeKept = (collection: CollectionRuntime, record: TransactionRecord) => {
|
|
653
|
+
const key = collection.resolveKey(record.key);
|
|
654
|
+
const stamp = { kind: "now" as const, seq: this.db.tick(), wall: Date.now() };
|
|
655
|
+
if (record.op === "delete") {
|
|
656
|
+
collection.store.remove(key, stamp);
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
collection.store.write(
|
|
660
|
+
key,
|
|
661
|
+
{ ...record.values, [collection.config.key]: key },
|
|
662
|
+
{ complete: record.op === "insert", stamp },
|
|
663
|
+
);
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
private writeResponse = (collection: CollectionRuntime, record: TransactionRecord, data: unknown) => {
|
|
667
|
+
const key = collection.resolveKey(record.key);
|
|
668
|
+
const stamp = { kind: "now" as const, seq: this.db.tick(), wall: Date.now() };
|
|
669
|
+
if (record.op === "delete") {
|
|
670
|
+
collection.store.remove(key, stamp);
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
if (!isPlainObject(data)) {
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
const serverKey = (data[collection.config.key] as RowKey | undefined) ?? key;
|
|
677
|
+
collection.writeServerRows([{ ...data, [collection.config.key]: serverKey }], record.op === "insert", stamp);
|
|
678
|
+
if (record.op !== "insert") {
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
if (serverKey !== record.key) {
|
|
682
|
+
collection.aliases.set(record.key, serverKey);
|
|
683
|
+
collection.setRenderKey(serverKey, collection.getRenderKey(record.key));
|
|
684
|
+
collection.store.rekeyLayers(record.key, serverKey);
|
|
685
|
+
}
|
|
686
|
+
collection.noteInsert(serverKey);
|
|
687
|
+
};
|
|
688
|
+
|
|
689
|
+
/** Reloads the subsets that hold the row, after the loads already in flight */
|
|
690
|
+
private refetch = async (collection: CollectionRuntime, record: TransactionRecord) => {
|
|
691
|
+
const key = collection.resolveKey(record.key);
|
|
692
|
+
const subsets = collection.getSubsetsHolding(key);
|
|
693
|
+
if (subsets.length === 0) {
|
|
694
|
+
this.db.batch(() => this.writeKept(collection, record));
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
// The writes queued behind this one wait for it, so its refetch must not wait for them
|
|
698
|
+
await Promise.all(subsets.map((subset) => subset.reload({ waitForWrites: false })));
|
|
699
|
+
};
|
|
700
|
+
|
|
701
|
+
/** Drops a rejected outbox write and every later write that was built on it */
|
|
702
|
+
private drop = (record: TransactionRecord, error: unknown) => {
|
|
703
|
+
const droppedIds = new Set([record.id]);
|
|
704
|
+
const droppedRows = new Set(rowsOf(record));
|
|
705
|
+
const dropped = [record];
|
|
706
|
+
this.outbox.slice(1).forEach((later) => {
|
|
707
|
+
const rows = rowsOf(later);
|
|
708
|
+
if (rows.some((row) => droppedRows.has(row)) || later.dependsOn.some((id) => droppedIds.has(id))) {
|
|
709
|
+
droppedIds.add(later.id);
|
|
710
|
+
rows.forEach((row) => droppedRows.add(row));
|
|
711
|
+
dropped.push(later);
|
|
712
|
+
}
|
|
713
|
+
});
|
|
714
|
+
this.end(record);
|
|
715
|
+
this.removeFromOutbox([...droppedIds]);
|
|
716
|
+
dropped.forEach((item) => {
|
|
717
|
+
const reason = item === record ? error : new DependencyError(record.id);
|
|
718
|
+
this.fail(item, reason);
|
|
719
|
+
this.db.tabs?.post({ type: "outcome", id: item.id, success: false, error: String(reason) });
|
|
720
|
+
});
|
|
721
|
+
};
|
|
722
|
+
|
|
723
|
+
private fail = (record: TransactionRecord, error: unknown) => {
|
|
724
|
+
const active = this.isActive(record);
|
|
725
|
+
if (record.transaction) {
|
|
726
|
+
this.removeTransactionLayers(record);
|
|
727
|
+
} else {
|
|
728
|
+
const collection = this.db.collections.get(record.collection);
|
|
729
|
+
this.db.batch(() => collection?.store.removeLayer(record.id));
|
|
730
|
+
}
|
|
731
|
+
this.resolve(record, { success: false, data: null, error });
|
|
732
|
+
// A write `clear` already ended is not reported again
|
|
733
|
+
if (active) {
|
|
734
|
+
this.db.emitError({ type: "mutation", error, collection: record.collection, transaction: record });
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
private resolve = (record: TransactionRecord, result: MutationResult) => {
|
|
739
|
+
this.resolvers.get(record.id)?.(result);
|
|
740
|
+
this.resolvers.delete(record.id);
|
|
741
|
+
this.sentAt.delete(record.id);
|
|
742
|
+
this.outcomes.set(record.id, result.success);
|
|
743
|
+
this.outcomeWaiters.get(record.id)?.forEach((notify) => notify(result.success));
|
|
744
|
+
this.outcomeWaiters.delete(record.id);
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
/** The collections a write changes: one, or every collection a named transaction writes */
|
|
748
|
+
private collectionsOf = (record: TransactionRecord) => [
|
|
749
|
+
...new Set((record.transaction?.writes ?? [record]).map((write) => write.collection)),
|
|
750
|
+
];
|
|
751
|
+
|
|
752
|
+
/** Counts a sent write as in flight in every collection it changes, once per attempt */
|
|
753
|
+
private begin = (record: TransactionRecord) => {
|
|
754
|
+
this.begun.add(record.id);
|
|
755
|
+
this.collectionsOf(record).forEach((collection) => {
|
|
756
|
+
this.inFlight.set(collection, (this.inFlight.get(collection) ?? 0) + 1);
|
|
757
|
+
});
|
|
758
|
+
};
|
|
759
|
+
|
|
760
|
+
/** Ends a write's in-flight state once, even when its success handling ended it early */
|
|
761
|
+
private end = (record: TransactionRecord) => {
|
|
762
|
+
if (!this.begun.delete(record.id)) {
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
this.collectionsOf(record).forEach((collection) => {
|
|
766
|
+
const count = this.inFlight.get(collection)! - 1;
|
|
767
|
+
this.inFlight.set(collection, count);
|
|
768
|
+
if (count > 0) {
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
const waiters = this.settleWaiters.get(collection) ?? [];
|
|
772
|
+
this.settleWaiters.delete(collection);
|
|
773
|
+
waiters.forEach((resolve) => resolve());
|
|
774
|
+
});
|
|
775
|
+
};
|
|
776
|
+
}
|