@hyper-fetch/db 0.0.0-stage → 1.0.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,572 @@
|
|
|
1
|
+
import type { RequestInstance } from "@hyper-fetch/core";
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
CollectionConfig,
|
|
5
|
+
IngestConfig,
|
|
6
|
+
ListenerPatch,
|
|
7
|
+
LoaderConfig,
|
|
8
|
+
RowKey,
|
|
9
|
+
SortDirection,
|
|
10
|
+
SyncConfig,
|
|
11
|
+
} from "../collection/collection.types";
|
|
12
|
+
import type { ComparisonNode } from "../operators/operators.types";
|
|
13
|
+
import { compareValues, stableStringify } from "../operators/operators.utils";
|
|
14
|
+
import type { ListPlan } from "../query/planner";
|
|
15
|
+
import type { QueryDefinition } from "../query/query.types";
|
|
16
|
+
import { Store } from "../store/store";
|
|
17
|
+
import type { Row, Stamp } from "../store/store.types";
|
|
18
|
+
import type { BaseSubset } from "../subset/base-subset";
|
|
19
|
+
import { KeySubset } from "../subset/key-subset";
|
|
20
|
+
import { ListSubset } from "../subset/list-subset";
|
|
21
|
+
import { SyncSubscription } from "../sync/sync";
|
|
22
|
+
import { applyListenerPatches, applyRequestPatches, isPlainObject } from "../utils/request.utils";
|
|
23
|
+
import type { DbRuntime } from "./db.runtime";
|
|
24
|
+
|
|
25
|
+
type KeyRequest = { subset: KeySubset; resolve: () => void; waitForWrites: boolean };
|
|
26
|
+
|
|
27
|
+
/** Everything the db keeps for one collection: its rows, loaded subsets, sync subscriptions and ingested requests */
|
|
28
|
+
export class CollectionRuntime {
|
|
29
|
+
readonly store: Store;
|
|
30
|
+
readonly listSubsets = new Map<string, ListSubset>();
|
|
31
|
+
readonly keySubsets = new Map<RowKey, KeySubset>();
|
|
32
|
+
readonly subscriptions = new Map<string, SyncSubscription>();
|
|
33
|
+
/** Server keys that replaced temporary keys of inserts */
|
|
34
|
+
readonly aliases = new Map<RowKey, RowKey>();
|
|
35
|
+
private renderKeys = new Map<RowKey, string>();
|
|
36
|
+
private keyRequests: KeyRequest[] = [];
|
|
37
|
+
private cleanups: (() => void)[] = [];
|
|
38
|
+
|
|
39
|
+
constructor(
|
|
40
|
+
readonly db: DbRuntime,
|
|
41
|
+
readonly name: string,
|
|
42
|
+
readonly config: CollectionConfig,
|
|
43
|
+
) {
|
|
44
|
+
this.store = new Store({
|
|
45
|
+
keyField: config.key,
|
|
46
|
+
versionField: config.version,
|
|
47
|
+
onChange: (key) => db.markRowChanged(this, key),
|
|
48
|
+
});
|
|
49
|
+
config.ingests.forEach((ingest) => this.listenToIngest(ingest));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The stable key for rendering a row, which survives swapping a temporary key for the server's */
|
|
53
|
+
getRenderKey = (key: RowKey): string => this.renderKeys.get(key) ?? String(key);
|
|
54
|
+
|
|
55
|
+
setRenderKey = (key: RowKey, renderKey: string) => {
|
|
56
|
+
this.renderKeys.set(key, renderKey);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** Resolves a temporary insert key to the key the server assigned, when it has */
|
|
60
|
+
resolveKey = (key: RowKey): RowKey => this.aliases.get(key) ?? key;
|
|
61
|
+
|
|
62
|
+
getListSubset = (plan: ListPlan, definition: QueryDefinition): ListSubset => {
|
|
63
|
+
const existing = this.listSubsets.get(plan.subsetId);
|
|
64
|
+
if (existing) {
|
|
65
|
+
return existing;
|
|
66
|
+
}
|
|
67
|
+
const loader = this.config.loaders[plan.loaderIndex];
|
|
68
|
+
const subset = new ListSubset(this, {
|
|
69
|
+
loader,
|
|
70
|
+
plan,
|
|
71
|
+
definition: { orderBy: definition.orderBy, limit: definition.limit },
|
|
72
|
+
});
|
|
73
|
+
this.listSubsets.set(plan.subsetId, subset);
|
|
74
|
+
return subset;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
getKeySubset = (key: RowKey, loaderIndex: number): KeySubset => {
|
|
78
|
+
const existing = this.keySubsets.get(key);
|
|
79
|
+
if (existing) {
|
|
80
|
+
return existing;
|
|
81
|
+
}
|
|
82
|
+
const subset = new KeySubset(this, this.config.loaders[loaderIndex], key);
|
|
83
|
+
this.keySubsets.set(key, subset);
|
|
84
|
+
return subset;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Finds a fresh subset whose rows contain every row a query can return, so the query is answered locally. The
|
|
89
|
+
* subset must not be paginated, its sent conditions must all be part of the query's, and its loader's fixed filters
|
|
90
|
+
* must be part of the query loader's.
|
|
91
|
+
*/
|
|
92
|
+
findContainingSubset = (plan: ListPlan): ListSubset | undefined => {
|
|
93
|
+
if (plan.paginated || plan.serverOnly) {
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
const queryLoader = this.config.loaders[plan.loaderIndex];
|
|
97
|
+
const sent = new Set(plan.sent.map((node) => stableStringify(node)));
|
|
98
|
+
return [...this.listSubsets.values()].find((subset) => {
|
|
99
|
+
// A subset of a server-only operator holds what the server matched, which says nothing about other queries
|
|
100
|
+
if (subset.plan.paginated || subset.plan.serverOnly || !subset.isFresh()) {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
const fixed = subset.listLoader.fixed ?? {};
|
|
104
|
+
const fixedContained = Object.keys(fixed).every(
|
|
105
|
+
(field) => stableStringify(queryLoader.fixed?.[field]) === stableStringify(fixed[field]),
|
|
106
|
+
);
|
|
107
|
+
return fixedContained && subset.plan.sent.every((node) => sent.has(stableStringify(node)));
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
removeSubset = (subset: BaseSubset) => {
|
|
112
|
+
if (subset instanceof ListSubset) {
|
|
113
|
+
this.listSubsets.delete(subset.id);
|
|
114
|
+
} else {
|
|
115
|
+
this.keySubsets.delete((subset as KeySubset).key);
|
|
116
|
+
}
|
|
117
|
+
this.sweep();
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/** Every subset, list and key */
|
|
121
|
+
getSubsets = (): BaseSubset[] => [...this.listSubsets.values(), ...this.keySubsets.values()];
|
|
122
|
+
|
|
123
|
+
/** Whether a subset other than `except`, or a pending write, holds the row */
|
|
124
|
+
isHeldByOthers = (key: RowKey, except?: BaseSubset) => {
|
|
125
|
+
return this.store.hasLayer(key) || this.getSubsets().some((subset) => subset !== except && subset.holds(key));
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/** The subsets whose rows include the key, which a refetch after a write reloads */
|
|
129
|
+
getSubsetsHolding = (key: RowKey) => this.getSubsets().filter((subset) => subset.holds(key));
|
|
130
|
+
|
|
131
|
+
/** Removes rows that no subset and no pending write holds */
|
|
132
|
+
sweep = () => {
|
|
133
|
+
this.db.batch(() => {
|
|
134
|
+
this.store.getServerKeys().forEach((key) => {
|
|
135
|
+
if (!this.isHeldByOthers(key)) {
|
|
136
|
+
this.store.drop(key);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/** Tells the queries of a subset that its rows or status changed */
|
|
143
|
+
markSubsetChanged = (subset: BaseSubset) => {
|
|
144
|
+
subset.notify();
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
/** Orders keys by the query's orders, then by the order the loader returned, then by arrival and key */
|
|
148
|
+
createComparator = (
|
|
149
|
+
orderBy: readonly { field: string; direction: SortDirection }[],
|
|
150
|
+
source: ListSubset | undefined,
|
|
151
|
+
) => {
|
|
152
|
+
return (left: RowKey, right: RowKey): number => {
|
|
153
|
+
const leftRow = this.store.get(left);
|
|
154
|
+
const rightRow = this.store.get(right);
|
|
155
|
+
for (const { field, direction } of orderBy) {
|
|
156
|
+
const result = compareValues(leftRow?.[field], rightRow?.[field]);
|
|
157
|
+
if (result !== 0) {
|
|
158
|
+
return direction === "desc" ? -result : result;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (orderBy.length === 0) {
|
|
162
|
+
const leftIndex = source?.orderIndex.get(left) ?? Number.MAX_SAFE_INTEGER;
|
|
163
|
+
const rightIndex = source?.orderIndex.get(right) ?? Number.MAX_SAFE_INTEGER;
|
|
164
|
+
if (leftIndex !== rightIndex) {
|
|
165
|
+
return leftIndex - rightIndex;
|
|
166
|
+
}
|
|
167
|
+
// Every row the db holds has a distinct arrival, so this settles the order
|
|
168
|
+
return this.store.getArrival(left) - this.store.getArrival(right);
|
|
169
|
+
}
|
|
170
|
+
return compareValues(left, right);
|
|
171
|
+
};
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
/** Reads the items of a response: the `rows` mapping, or the response itself */
|
|
175
|
+
readItems = (source: Pick<LoaderConfig, "rows">, data: unknown): unknown[] => {
|
|
176
|
+
if (source.rows) {
|
|
177
|
+
return [...source.rows(data)];
|
|
178
|
+
}
|
|
179
|
+
return Array.isArray(data) ? data : [data];
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/** Validates rows when the collection validates server data */
|
|
183
|
+
prepareServerRows = (items: unknown[]): Row[] | Promise<Row[]> => {
|
|
184
|
+
const mapped = items as Row[];
|
|
185
|
+
const { schema } = this.config;
|
|
186
|
+
if (!schema || this.config.validate !== "all") {
|
|
187
|
+
return mapped;
|
|
188
|
+
}
|
|
189
|
+
const results = mapped.map((row) => schema["~standard"].validate(row));
|
|
190
|
+
const collect = (settled: Awaited<(typeof results)[number]>[]) => {
|
|
191
|
+
const rows: Row[] = [];
|
|
192
|
+
settled.forEach((result) => {
|
|
193
|
+
if (result.issues) {
|
|
194
|
+
this.db.emitError({ type: "validation", error: result.issues, collection: this.name });
|
|
195
|
+
} else {
|
|
196
|
+
rows.push(result.value as Row);
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
return rows;
|
|
200
|
+
};
|
|
201
|
+
if (results.some((result) => result instanceof Promise)) {
|
|
202
|
+
return Promise.all(results).then(collect);
|
|
203
|
+
}
|
|
204
|
+
return collect(results as Awaited<(typeof results)[number]>[]);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/** Writes server rows and returns their keys in order */
|
|
208
|
+
writeServerRows = (rows: Row[], complete: boolean, stamp: Stamp): RowKey[] => {
|
|
209
|
+
return rows.map((row) => {
|
|
210
|
+
const key = row[this.config.key] as RowKey;
|
|
211
|
+
this.store.write(key, row, { complete, stamp });
|
|
212
|
+
if (complete) {
|
|
213
|
+
this.normalize(row, stamp);
|
|
214
|
+
}
|
|
215
|
+
return key;
|
|
216
|
+
});
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
/** Writes the rows nested in a complete row into the collections that hold them */
|
|
220
|
+
normalize = (row: Row, stamp: Stamp) => {
|
|
221
|
+
(this.config.normalize ?? []).forEach(({ target, extract }) => {
|
|
222
|
+
const collection = this.db.getCollectionByConfig(target)!;
|
|
223
|
+
const rows = collection.prepareServerRows([...extract(row)]);
|
|
224
|
+
const write = (nested: Row[]) => {
|
|
225
|
+
this.db.batch(() => {
|
|
226
|
+
collection.writeServerRows(nested, true, stamp).forEach((key) => collection.noteInsert(key));
|
|
227
|
+
});
|
|
228
|
+
};
|
|
229
|
+
if (rows instanceof Promise) {
|
|
230
|
+
rows.then(write);
|
|
231
|
+
} else {
|
|
232
|
+
write(rows);
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
/** Rows of this collection were written: key subsets move to the sync subscriptions their rows' values pick */
|
|
238
|
+
refreshKeySyncs = (keys: Iterable<RowKey>) => {
|
|
239
|
+
[...keys].forEach((key) => this.keySubsets.get(key)?.refreshSyncs());
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
/** Tells paginated subsets about an inserted row, so it can join their loaded range */
|
|
243
|
+
noteInsert = (key: RowKey) => {
|
|
244
|
+
this.listSubsets.forEach((subset) => {
|
|
245
|
+
subset.noteInsert(key);
|
|
246
|
+
});
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
/** Starts or joins the sync subscriptions that cover a subset */
|
|
250
|
+
subscribeSyncs = (subset: BaseSubset): SyncSubscription[] => {
|
|
251
|
+
const eqValues = subset.getEqValues();
|
|
252
|
+
const subscriptions: SyncSubscription[] = [];
|
|
253
|
+
this.config.syncs.forEach((sync, index) => {
|
|
254
|
+
const target = this.getSyncTarget({ sync, index, subset, eqValues });
|
|
255
|
+
if (!target) {
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const { id, patches } = target;
|
|
259
|
+
let subscription = this.subscriptions.get(id);
|
|
260
|
+
if (!subscription) {
|
|
261
|
+
const listener = applyListenerPatches(sync.listener, patches);
|
|
262
|
+
subscription = new SyncSubscription({
|
|
263
|
+
id,
|
|
264
|
+
sync,
|
|
265
|
+
listener,
|
|
266
|
+
host: {
|
|
267
|
+
tick: this.db.tick,
|
|
268
|
+
applySyncMessage: this.applySyncMessage,
|
|
269
|
+
onLiveChange: () => this.getSubsets().forEach((item) => item.notify()),
|
|
270
|
+
onRemove: (removed) => this.subscriptions.delete(removed.id),
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
this.subscriptions.set(id, subscription);
|
|
274
|
+
this.db.watchSocket(listener.socket);
|
|
275
|
+
}
|
|
276
|
+
subscription.addUser(subset);
|
|
277
|
+
subscriptions.push(subscription);
|
|
278
|
+
});
|
|
279
|
+
return subscriptions;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Which subscription of a sync covers a subset, and the listener params it needs.
|
|
284
|
+
*
|
|
285
|
+
* - A sync with `byKey` covers a row read by key with a listener of its own, and with a notation it also covers every
|
|
286
|
+
* list subset with its sent conditions. Without `byKey`, a sync with a notation covers list subsets only, because
|
|
287
|
+
* a listener on the whole collection for one row is wasteful and, on Firestore, billed.
|
|
288
|
+
* - A sync with `where` covers subsets whose values fill every field it declares: the sent `eq` conditions of a list,
|
|
289
|
+
* or the fields of the row a key subset holds, so a post read by key joins its team's subscription.
|
|
290
|
+
*/
|
|
291
|
+
private getSyncTarget = ({
|
|
292
|
+
sync,
|
|
293
|
+
index,
|
|
294
|
+
subset,
|
|
295
|
+
eqValues,
|
|
296
|
+
}: {
|
|
297
|
+
sync: SyncConfig;
|
|
298
|
+
index: number;
|
|
299
|
+
subset: BaseSubset;
|
|
300
|
+
eqValues: Record<string, unknown>;
|
|
301
|
+
}): { id: string; patches: ListenerPatch[] } | undefined => {
|
|
302
|
+
if (subset instanceof KeySubset && sync.byKey) {
|
|
303
|
+
return { id: stableStringify([index, "key", subset.key]), patches: [sync.byKey(subset.key)] };
|
|
304
|
+
}
|
|
305
|
+
if (sync.notation) {
|
|
306
|
+
if (subset instanceof KeySubset) {
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
// A server-only operator has no notation, and a loader that sends one needs no listener notation either
|
|
310
|
+
const conditions = (subset as ListSubset).plan.sent.filter(
|
|
311
|
+
(node): node is ComparisonNode => node.op !== "server",
|
|
312
|
+
);
|
|
313
|
+
return { id: stableStringify([index, conditions]), patches: [sync.notation(conditions)] };
|
|
314
|
+
}
|
|
315
|
+
if (sync.byKey && subset instanceof ListSubset) {
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
318
|
+
const fields = Object.keys(sync.where ?? {});
|
|
319
|
+
if (!fields.every((field) => field in eqValues)) {
|
|
320
|
+
return undefined;
|
|
321
|
+
}
|
|
322
|
+
const values = Object.fromEntries(fields.map((field) => [field, eqValues[field]]));
|
|
323
|
+
return {
|
|
324
|
+
id: stableStringify([index, values]),
|
|
325
|
+
patches: fields.map((field) => sync.where![field].eq(values[field])),
|
|
326
|
+
};
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
/** Applies a `changes` event: complete rows to write and keys to delete */
|
|
330
|
+
private applyChanges = (sync: SyncConfig, message: unknown, stamp: Stamp) => {
|
|
331
|
+
const { upsert, delete: deleted, refetch = [] } = sync.changes!(message);
|
|
332
|
+
refetch.forEach((key) => this.fetchByKey(key));
|
|
333
|
+
const apply = (rows: Row[]) => {
|
|
334
|
+
this.db.batch(() => {
|
|
335
|
+
rows.forEach((row) => {
|
|
336
|
+
const key = row[this.config.key] as RowKey;
|
|
337
|
+
this.writeServerRows([row], true, stamp);
|
|
338
|
+
this.noteInsert(key);
|
|
339
|
+
this.db.notifySyncWrite(this.name, key);
|
|
340
|
+
});
|
|
341
|
+
deleted.forEach((key) => {
|
|
342
|
+
this.store.remove(key, stamp);
|
|
343
|
+
this.db.notifySyncWrite(this.name, key);
|
|
344
|
+
});
|
|
345
|
+
});
|
|
346
|
+
};
|
|
347
|
+
const rows = this.prepareServerRows([...upsert]);
|
|
348
|
+
if (rows instanceof Promise) {
|
|
349
|
+
rows.then(apply);
|
|
350
|
+
} else {
|
|
351
|
+
apply(rows);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
/** Applies one sync event */
|
|
356
|
+
/** Applies a sync event. A mapping that throws on one event is reported, and the next events still apply. */
|
|
357
|
+
applySyncMessage = (sync: SyncConfig, message: unknown, stamp: Stamp) => {
|
|
358
|
+
try {
|
|
359
|
+
this.applySyncEvent(sync, message, stamp);
|
|
360
|
+
} catch (error) {
|
|
361
|
+
this.db.emitError({ type: "sync", error, collection: this.name });
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
private applySyncEvent = (sync: SyncConfig, message: unknown, stamp: Stamp) => {
|
|
366
|
+
const keyField = this.config.key;
|
|
367
|
+
if (sync.type === "changes") {
|
|
368
|
+
this.applyChanges(sync, message, stamp);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (sync.type === "delete") {
|
|
372
|
+
const key = sync.key ? sync.key(message) : ((message as Row)[keyField] as RowKey);
|
|
373
|
+
this.db.batch(() => {
|
|
374
|
+
this.store.remove(key, stamp);
|
|
375
|
+
this.db.notifySyncWrite(this.name, key);
|
|
376
|
+
});
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
const apply = (rows: Row[]) => {
|
|
380
|
+
this.db.batch(() => {
|
|
381
|
+
rows.forEach((row) => {
|
|
382
|
+
const key = row[keyField] as RowKey;
|
|
383
|
+
if (sync.type === "insert") {
|
|
384
|
+
this.writeServerRows([row], true, stamp);
|
|
385
|
+
this.noteInsert(key);
|
|
386
|
+
} else if (this.store.hasServerRow(key)) {
|
|
387
|
+
this.store.write(key, row, { complete: false, stamp });
|
|
388
|
+
this.listSubsets.forEach((subset) => subset.excluded.delete(key));
|
|
389
|
+
} else if (sync.incomplete === "refetch") {
|
|
390
|
+
this.fetchByKey(key);
|
|
391
|
+
}
|
|
392
|
+
this.db.notifySyncWrite(this.name, key);
|
|
393
|
+
});
|
|
394
|
+
});
|
|
395
|
+
};
|
|
396
|
+
const rows = this.prepareServerRows([sync.row ? sync.row(message) : message]);
|
|
397
|
+
if (rows instanceof Promise) {
|
|
398
|
+
rows.then(apply);
|
|
399
|
+
} else {
|
|
400
|
+
apply(rows);
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
/** Loads one row by key without a query, for example for an incomplete sync event */
|
|
405
|
+
fetchByKey = (key: RowKey) => {
|
|
406
|
+
const loaderIndex = this.config.loaders.findIndex((loader) => loader.kind !== "list");
|
|
407
|
+
if (loaderIndex === -1) {
|
|
408
|
+
return Promise.resolve();
|
|
409
|
+
}
|
|
410
|
+
const subset = this.getKeySubset(key, loaderIndex);
|
|
411
|
+
const observer = { onSubsetChange: () => {} };
|
|
412
|
+
subset.attach(observer);
|
|
413
|
+
return subset.load().then(() => subset.detach(observer));
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
/** Loads a key subset's row, batched with the other keys requested in the same tick */
|
|
417
|
+
loadKey = (subset: KeySubset, waitForWrites = true): Promise<void> => {
|
|
418
|
+
return new Promise((resolve) => {
|
|
419
|
+
this.keyRequests.push({ subset, resolve, waitForWrites });
|
|
420
|
+
if (this.keyRequests.length === 1) {
|
|
421
|
+
queueMicrotask(() => this.flushKeyRequests());
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
/** Resolves once no write of this collection is in flight */
|
|
427
|
+
mutationsSettled = () => this.db.mutations.settled(this.name);
|
|
428
|
+
|
|
429
|
+
/** Removes every row and resets the loaded subsets, for example on sign-out */
|
|
430
|
+
clear = () => {
|
|
431
|
+
this.store.clear();
|
|
432
|
+
this.listSubsets.forEach((subset) => {
|
|
433
|
+
subset.owned.clear();
|
|
434
|
+
subset.inserted.clear();
|
|
435
|
+
subset.excluded.clear();
|
|
436
|
+
subset.orderIndex.clear();
|
|
437
|
+
subset.pages = 0;
|
|
438
|
+
subset.hasLoaded = false;
|
|
439
|
+
subset.loadedAt = 0;
|
|
440
|
+
});
|
|
441
|
+
this.keySubsets.forEach((subset) => {
|
|
442
|
+
subset.hasLoaded = false;
|
|
443
|
+
subset.loadedAt = 0;
|
|
444
|
+
});
|
|
445
|
+
this.getSubsets().forEach((subset) => subset.notify());
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
destroy = () => {
|
|
449
|
+
this.cleanups.forEach((cleanup) => cleanup());
|
|
450
|
+
this.cleanups = [];
|
|
451
|
+
this.getSubsets().forEach((subset) => subset.cancelGc());
|
|
452
|
+
this.subscriptions.forEach((subscription) => {
|
|
453
|
+
subscription.getUsers().forEach((user) => subscription.removeUser(user));
|
|
454
|
+
});
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
private flushKeyRequests = async () => {
|
|
458
|
+
const requests = this.keyRequests;
|
|
459
|
+
this.keyRequests = [];
|
|
460
|
+
await this.db.ready;
|
|
461
|
+
if (requests.some((request) => request.waitForWrites)) {
|
|
462
|
+
await this.mutationsSettled();
|
|
463
|
+
}
|
|
464
|
+
const groups = new Map<LoaderConfig, KeyRequest[]>();
|
|
465
|
+
requests.forEach((request) => {
|
|
466
|
+
const { loader } = request.subset;
|
|
467
|
+
groups.set(loader, [...(groups.get(loader) ?? []), request]);
|
|
468
|
+
});
|
|
469
|
+
await Promise.all(
|
|
470
|
+
[...groups.entries()].map(([loader, group]) => {
|
|
471
|
+
if (loader.kind === "byKeys") {
|
|
472
|
+
return this.sendKeyRequest(loader, group, loader.byKeys!(group.map(({ subset }) => subset.key)));
|
|
473
|
+
}
|
|
474
|
+
return Promise.all(
|
|
475
|
+
group.map((request) => this.sendKeyRequest(loader, [request], loader.byKey!(request.subset.key))),
|
|
476
|
+
);
|
|
477
|
+
}),
|
|
478
|
+
);
|
|
479
|
+
};
|
|
480
|
+
|
|
481
|
+
private sendKeyRequest = async (
|
|
482
|
+
loader: LoaderConfig,
|
|
483
|
+
group: KeyRequest[],
|
|
484
|
+
patch: ReturnType<NonNullable<LoaderConfig["byKey"]>>,
|
|
485
|
+
) => {
|
|
486
|
+
const seq = this.db.tick();
|
|
487
|
+
const wall = Date.now();
|
|
488
|
+
const { generation } = this.db;
|
|
489
|
+
this.db.trackRequest(seq);
|
|
490
|
+
try {
|
|
491
|
+
const request: RequestInstance = applyRequestPatches(loader.request.setCache(false), [patch]);
|
|
492
|
+
const response = await request.send();
|
|
493
|
+
const items = response.success ? this.readItems(loader, response.data) : [];
|
|
494
|
+
const rows = await this.prepareServerRows(items);
|
|
495
|
+
if (this.db.generation !== generation) {
|
|
496
|
+
group.forEach(({ subset }) => subset.complete({ success: false, error: new Error("Cleared") }));
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
// A row the response returned but the schema rejected exists on the server, so it is not removed as missing
|
|
500
|
+
const returnedKeys = new Set(items.filter(isPlainObject).map((item) => item[this.config.key] as RowKey));
|
|
501
|
+
this.db.batch(() => {
|
|
502
|
+
if (response.success) {
|
|
503
|
+
const keys = new Set(this.writeServerRows(rows, true, { kind: "sent", seq, wall }));
|
|
504
|
+
const stamp = { kind: "sent" as const, seq, wall };
|
|
505
|
+
group.forEach(({ subset }) => {
|
|
506
|
+
subset.complete({ success: true, found: keys.has(subset.key) || returnedKeys.has(subset.key), stamp });
|
|
507
|
+
});
|
|
508
|
+
} else {
|
|
509
|
+
group.forEach(({ subset }) => subset.complete({ success: false, error: response.error ?? response }));
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
} catch (error) {
|
|
513
|
+
this.db.emitError({ type: "load", error, collection: this.name });
|
|
514
|
+
this.db.batch(() => group.forEach(({ subset }) => subset.complete({ success: false, error })));
|
|
515
|
+
} finally {
|
|
516
|
+
this.db.settleRequest(seq);
|
|
517
|
+
group.forEach(({ resolve }) => resolve());
|
|
518
|
+
}
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
private listenToIngest = (ingest: IngestConfig) => {
|
|
522
|
+
const { request: ingested } = ingest;
|
|
523
|
+
const { events } = ingested.client.requestManager;
|
|
524
|
+
const matches = (request: RequestInstance) =>
|
|
525
|
+
request.requestOptions.endpoint === ingested.requestOptions.endpoint && request.method === ingested.method;
|
|
526
|
+
// A response is ordered by when its request was sent, so it never beats a write made after it went out
|
|
527
|
+
const sentAt = new Map<string, number>();
|
|
528
|
+
const generations = new Map<string, number>();
|
|
529
|
+
const unsubscribeStart = events.onRequestStart(({ request, requestId }) => {
|
|
530
|
+
if (matches(request)) {
|
|
531
|
+
const seq = this.db.tick();
|
|
532
|
+
sentAt.set(requestId, seq);
|
|
533
|
+
generations.set(requestId, this.db.generation);
|
|
534
|
+
this.db.trackRequest(seq);
|
|
535
|
+
}
|
|
536
|
+
});
|
|
537
|
+
const unsubscribe = events.onResponse(({ request, requestId, response }) => {
|
|
538
|
+
if (!matches(request)) {
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
const seq = sentAt.get(requestId);
|
|
542
|
+
const generation = generations.get(requestId) ?? this.db.generation;
|
|
543
|
+
sentAt.delete(requestId);
|
|
544
|
+
generations.delete(requestId);
|
|
545
|
+
if (seq !== undefined) {
|
|
546
|
+
this.db.settleRequest(seq);
|
|
547
|
+
}
|
|
548
|
+
// A response to a request sent before `clear` belongs to the previous user
|
|
549
|
+
if (!response.success || generation !== this.db.generation) {
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const items = this.readItems(ingest, response.data).filter(isPlainObject);
|
|
553
|
+
const write = (rows: Row[]) => {
|
|
554
|
+
// A request that started before the db existed counts from now
|
|
555
|
+
const stamp: Stamp = { kind: "sent", seq: seq ?? this.db.tick(), wall: response.requestTimestamp };
|
|
556
|
+
this.db.batch(() => {
|
|
557
|
+
const keys = this.writeServerRows(rows, ingest.type === "insert", stamp);
|
|
558
|
+
if (ingest.type === "insert") {
|
|
559
|
+
keys.forEach((key) => this.noteInsert(key));
|
|
560
|
+
}
|
|
561
|
+
});
|
|
562
|
+
};
|
|
563
|
+
const rows = this.prepareServerRows(items);
|
|
564
|
+
if (rows instanceof Promise) {
|
|
565
|
+
rows.then(write);
|
|
566
|
+
} else {
|
|
567
|
+
write(rows);
|
|
568
|
+
}
|
|
569
|
+
});
|
|
570
|
+
this.cleanups.push(unsubscribe, unsubscribeStart);
|
|
571
|
+
};
|
|
572
|
+
}
|