@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,328 @@
|
|
|
1
|
+
import type { AnyRequestPatch, LoaderConfig, RowKey } from "../collection/collection.types";
|
|
2
|
+
import type { CollectionRuntime } from "../db/collection.runtime";
|
|
3
|
+
import { evaluate } from "../operators/operators.utils";
|
|
4
|
+
import type { ListPlan } from "../query/planner";
|
|
5
|
+
import { getOrderMapping, getWhereMapping } from "../query/planner";
|
|
6
|
+
import type { QueryDefinition } from "../query/query.types";
|
|
7
|
+
import type { Row } from "../store/store.types";
|
|
8
|
+
import { applyRequestPatches } from "../utils/request.utils";
|
|
9
|
+
import type { LoadOptions } from "./base-subset";
|
|
10
|
+
import { BaseSubset } from "./base-subset";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The rows one list loader returned for one set of sent conditions, order and range. It owns those rows until it is
|
|
14
|
+
* released, and records which rows a refetch no longer returned.
|
|
15
|
+
*/
|
|
16
|
+
export class ListSubset extends BaseSubset {
|
|
17
|
+
owned = new Set<RowKey>();
|
|
18
|
+
/** Rows that inserts added inside a paginated subset's range */
|
|
19
|
+
inserted = new Set<RowKey>();
|
|
20
|
+
/** Rows a refetch no longer returned, which another subset still holds */
|
|
21
|
+
excluded = new Set<RowKey>();
|
|
22
|
+
orderIndex = new Map<RowKey, number>();
|
|
23
|
+
cursor: unknown = undefined;
|
|
24
|
+
hasMore = false;
|
|
25
|
+
/** How many pages a paginated subset has loaded, so a refetch reloads all of them */
|
|
26
|
+
pages = 0;
|
|
27
|
+
|
|
28
|
+
readonly listLoader: LoaderConfig;
|
|
29
|
+
readonly plan: ListPlan;
|
|
30
|
+
readonly definition: Pick<QueryDefinition, "orderBy" | "limit">;
|
|
31
|
+
|
|
32
|
+
constructor(
|
|
33
|
+
collection: CollectionRuntime,
|
|
34
|
+
options: { loader: LoaderConfig; plan: ListPlan; definition: Pick<QueryDefinition, "orderBy" | "limit"> },
|
|
35
|
+
) {
|
|
36
|
+
super(collection, options.loader);
|
|
37
|
+
this.listLoader = options.loader;
|
|
38
|
+
this.plan = options.plan;
|
|
39
|
+
this.definition = options.definition;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
get id() {
|
|
43
|
+
return this.plan.subsetId;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The values of the subset's sent `eq` conditions, which syncs use to pick their subscription */
|
|
47
|
+
getEqValues = (): Record<string, unknown> => {
|
|
48
|
+
return Object.fromEntries(
|
|
49
|
+
this.plan.sent.filter((node) => node.op === "eq").map((node) => [node.field, node.value]),
|
|
50
|
+
);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Whether a row matches what the backend was asked for, including the loader's fixed filters */
|
|
54
|
+
matchesSent = (row: Row) => {
|
|
55
|
+
const fixed = this.listLoader.fixed ?? {};
|
|
56
|
+
const fixedMatch = Object.keys(fixed).every((field) => evaluate({ op: "eq", field, value: fixed[field] }, row));
|
|
57
|
+
return fixedMatch && this.plan.sent.every((node) => evaluate(node, row));
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** Whether the backend decides membership alone: pages, or a server-only operator the client cannot evaluate */
|
|
61
|
+
get ownsOnly() {
|
|
62
|
+
return this.plan.paginated || this.plan.sent.some((node) => node.op === "server");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
holds = (key: RowKey) => {
|
|
66
|
+
if (this.ownsOnly) {
|
|
67
|
+
return this.owned.has(key) || this.inserted.has(key);
|
|
68
|
+
}
|
|
69
|
+
if (this.excluded.has(key)) {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
const row = this.collection.store.getServerRow(key);
|
|
73
|
+
return this.owned.has(key) || Boolean(row && this.matchesSent(row));
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/** Adds an inserted row to a paginated subset when it sorts inside the loaded range */
|
|
77
|
+
noteInsert = (key: RowKey) => {
|
|
78
|
+
this.excluded.delete(key);
|
|
79
|
+
if (!this.plan.paginated) {
|
|
80
|
+
// A new row may match a server-only operator, which only a refetch can tell
|
|
81
|
+
if (this.ownsOnly && this.hasLoaded) {
|
|
82
|
+
this.invalidate();
|
|
83
|
+
}
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const row = this.collection.store.get(key);
|
|
87
|
+
if (!row || !this.matchesSent(row)) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (!this.hasMore) {
|
|
91
|
+
this.inserted.add(key);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const compare = this.collection.createComparator(this.definition.orderBy, this);
|
|
95
|
+
const last = [...this.owned].toSorted(compare).pop();
|
|
96
|
+
if (last !== undefined && compare(key, last) < 0) {
|
|
97
|
+
this.inserted.add(key);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** Loads the page after the last loaded one */
|
|
102
|
+
loadNext = (): Promise<void> => {
|
|
103
|
+
if (!this.hasMore || this.isLoading) {
|
|
104
|
+
return this.pending ?? Promise.resolve();
|
|
105
|
+
}
|
|
106
|
+
this.pendingIsFull = false;
|
|
107
|
+
const pending: Promise<void> = this.loadPages(false).finally(() => {
|
|
108
|
+
if (this.pending === pending) {
|
|
109
|
+
this.pending = undefined;
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
this.pending = pending;
|
|
113
|
+
return pending;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
protected run = (options: LoadOptions) => this.loadPages(true, options.waitForWrites !== false);
|
|
117
|
+
|
|
118
|
+
private buildRequest = (cursor: { value: unknown } | undefined) => {
|
|
119
|
+
const loader = this.listLoader;
|
|
120
|
+
const { notation } = this.collection.db;
|
|
121
|
+
// The planner only sends conditions and orders that have a mapping
|
|
122
|
+
const patches: AnyRequestPatch[] = this.plan.sent.map((node) =>
|
|
123
|
+
getWhereMapping(loader, node, notation)!(node.value),
|
|
124
|
+
);
|
|
125
|
+
if (this.plan.sendOrder) {
|
|
126
|
+
this.definition.orderBy.forEach(({ field, direction }) => {
|
|
127
|
+
patches.push(getOrderMapping(loader, field, notation)!(direction));
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
if (this.plan.sendLimit) {
|
|
131
|
+
patches.push(loader.limit!(this.definition.limit!));
|
|
132
|
+
}
|
|
133
|
+
if (cursor && loader.page) {
|
|
134
|
+
patches.push(loader.page(cursor.value));
|
|
135
|
+
}
|
|
136
|
+
return applyRequestPatches(loader.request.setCache(false), patches);
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Loads from the first page, or the page after the last loaded one. A paginated subset is a prefix of its result, so
|
|
141
|
+
* loading from the first page reloads every page loaded so far, in order, and then releases the rows none of them
|
|
142
|
+
* returned. The rows stay until the last page is back, so the list does not jump while it reloads.
|
|
143
|
+
*/
|
|
144
|
+
private loadPages = async (fromStart: boolean, waitForWrites = true) => {
|
|
145
|
+
const { db } = this.collection;
|
|
146
|
+
const { generation } = db;
|
|
147
|
+
this.beginLoad();
|
|
148
|
+
const timeout = this.startNetworkTimeout();
|
|
149
|
+
const returned: RowKey[] = fromStart ? [] : [...this.orderIndex.keys()];
|
|
150
|
+
let loadSeq = 0;
|
|
151
|
+
let result: Awaited<ReturnType<typeof this.fetchPages>>;
|
|
152
|
+
try {
|
|
153
|
+
await db.ready;
|
|
154
|
+
if (waitForWrites) {
|
|
155
|
+
await this.collection.mutationsSettled();
|
|
156
|
+
}
|
|
157
|
+
// Rows written after this point are newer than what the load can return, so a reload never releases them
|
|
158
|
+
loadSeq = db.tick();
|
|
159
|
+
result = await this.fetchPages({
|
|
160
|
+
cursor: fromStart ? undefined : { value: this.cursor },
|
|
161
|
+
remaining: fromStart ? Math.max(1, this.pages) : 1,
|
|
162
|
+
returned,
|
|
163
|
+
timeout,
|
|
164
|
+
generation,
|
|
165
|
+
});
|
|
166
|
+
} catch (error) {
|
|
167
|
+
// A mapping that throws, such as `rows` on an unexpected response, fails the load instead of leaving it pending
|
|
168
|
+
clearTimeout(timeout);
|
|
169
|
+
result = { success: false, error };
|
|
170
|
+
db.emitError({ type: "load", error, collection: this.collection.name });
|
|
171
|
+
}
|
|
172
|
+
// After `clear`, the response belongs to the previous user
|
|
173
|
+
if (db.generation !== generation) {
|
|
174
|
+
db.batch(() => {
|
|
175
|
+
this.endLoad();
|
|
176
|
+
this.collection.markSubsetChanged(this);
|
|
177
|
+
});
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (!result.success) {
|
|
181
|
+
// Read before the callback: TypeScript before 5.4 drops the narrowing of a `let` inside closures
|
|
182
|
+
const { error } = result;
|
|
183
|
+
db.batch(() => {
|
|
184
|
+
this.error = error;
|
|
185
|
+
this.endLoad();
|
|
186
|
+
this.collection.markSubsetChanged(this);
|
|
187
|
+
});
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const { cursor, loaded } = result;
|
|
191
|
+
db.batch(() => {
|
|
192
|
+
if (fromStart) {
|
|
193
|
+
this.release(returned, loadSeq);
|
|
194
|
+
}
|
|
195
|
+
this.orderIndex.clear();
|
|
196
|
+
returned.forEach((key, index) => this.orderIndex.set(key, index));
|
|
197
|
+
this.cursor = cursor;
|
|
198
|
+
this.hasMore = cursor !== undefined && cursor !== null;
|
|
199
|
+
this.pages = (fromStart ? 0 : this.pages) + loaded;
|
|
200
|
+
this.hasLoaded = true;
|
|
201
|
+
this.loadedAt = Date.now();
|
|
202
|
+
this.invalidated = false;
|
|
203
|
+
this.error = null;
|
|
204
|
+
this.endLoad();
|
|
205
|
+
this.collection.markSubsetChanged(this);
|
|
206
|
+
});
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/** Loads pages one after another, each with the cursor the previous one returned, until `remaining` are loaded */
|
|
210
|
+
private fetchPages = async (options: {
|
|
211
|
+
cursor: { value: unknown } | undefined;
|
|
212
|
+
remaining: number;
|
|
213
|
+
returned: RowKey[];
|
|
214
|
+
timeout: ReturnType<typeof setTimeout> | undefined;
|
|
215
|
+
generation: number;
|
|
216
|
+
}): Promise<{ success: true; cursor: unknown; loaded: number } | { success: false; error: unknown }> => {
|
|
217
|
+
const result = await this.fetchPage(options.cursor, options.returned, options.generation);
|
|
218
|
+
clearTimeout(options.timeout);
|
|
219
|
+
if (!result.success) {
|
|
220
|
+
return result;
|
|
221
|
+
}
|
|
222
|
+
const more = result.next !== undefined && result.next !== null;
|
|
223
|
+
if (!more || options.remaining <= 1) {
|
|
224
|
+
return { success: true, cursor: result.next, loaded: 1 };
|
|
225
|
+
}
|
|
226
|
+
const rest = await this.fetchPages({
|
|
227
|
+
...options,
|
|
228
|
+
cursor: { value: result.next },
|
|
229
|
+
remaining: options.remaining - 1,
|
|
230
|
+
});
|
|
231
|
+
return rest.success ? { ...rest, loaded: rest.loaded + 1 } : rest;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/** Sends one page's request and writes its rows, adding their keys to `returned` in order */
|
|
235
|
+
private fetchPage = async (
|
|
236
|
+
cursor: { value: unknown } | undefined,
|
|
237
|
+
returned: RowKey[],
|
|
238
|
+
generation: number,
|
|
239
|
+
): Promise<{ success: true; next: unknown } | { success: false; error: unknown }> => {
|
|
240
|
+
const { db } = this.collection;
|
|
241
|
+
const seq = db.tick();
|
|
242
|
+
const wall = Date.now();
|
|
243
|
+
db.trackRequest(seq);
|
|
244
|
+
try {
|
|
245
|
+
const response = await this.buildRequest(cursor).send();
|
|
246
|
+
if (!response.success) {
|
|
247
|
+
return { success: false, error: response.error ?? response };
|
|
248
|
+
}
|
|
249
|
+
const items = this.collection.readItems(this.listLoader, response.data);
|
|
250
|
+
const next = this.listLoader.cursor?.(response.data);
|
|
251
|
+
const rows = await this.collection.prepareServerRows(items);
|
|
252
|
+
if (db.generation !== generation) {
|
|
253
|
+
return { success: false, error: new Error("Cleared") };
|
|
254
|
+
}
|
|
255
|
+
db.batch(() => {
|
|
256
|
+
const keys = this.collection.writeServerRows(rows, true, { kind: "sent", seq, wall });
|
|
257
|
+
keys.forEach((key) => {
|
|
258
|
+
this.owned.add(key);
|
|
259
|
+
this.excluded.delete(key);
|
|
260
|
+
if (!this.orderIndex.has(key)) {
|
|
261
|
+
this.orderIndex.set(key, this.orderIndex.size);
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
returned.push(...keys);
|
|
265
|
+
this.collection.markSubsetChanged(this);
|
|
266
|
+
});
|
|
267
|
+
return { success: true, next };
|
|
268
|
+
} finally {
|
|
269
|
+
db.settleRequest(seq);
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Releases rows a complete reload no longer returned: rows it owned, rows inserts had added to its pages, and rows
|
|
275
|
+
* nothing else holds that match what it sent, such as a confirmed insert someone else deleted since. The server
|
|
276
|
+
* answered for its conditions, so such a row is not in them.
|
|
277
|
+
*/
|
|
278
|
+
private release = (returned: RowKey[], loadSeq: number) => {
|
|
279
|
+
const returnedKeys = new Set(returned);
|
|
280
|
+
const { store } = this.collection;
|
|
281
|
+
// A row written after the load was sent, by a write, an event or another response, is newer than the load knows
|
|
282
|
+
const isNewer = (key: RowKey) => store.getLastSeq(key) > loadSeq;
|
|
283
|
+
this.inserted.forEach((key) => {
|
|
284
|
+
this.inserted.delete(key);
|
|
285
|
+
if (!returnedKeys.has(key)) {
|
|
286
|
+
this.owned.add(key);
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
if (!this.ownsOnly) {
|
|
290
|
+
// Rows another subset or a pending write holds still show, as every matching row the db holds does
|
|
291
|
+
this.collection.store.getServerKeys().forEach((key) => {
|
|
292
|
+
const row = this.collection.store.getServerRow(key)!;
|
|
293
|
+
const unheld = !this.collection.isHeldByOthers(key, this);
|
|
294
|
+
if (!returnedKeys.has(key) && !isNewer(key) && this.matchesSent(row) && unheld) {
|
|
295
|
+
this.collection.store.drop(key);
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
this.owned.forEach((key) => {
|
|
300
|
+
if (returnedKeys.has(key) || isNewer(key)) {
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
this.owned.delete(key);
|
|
304
|
+
if (this.collection.isHeldByOthers(key, this)) {
|
|
305
|
+
this.excluded.add(key);
|
|
306
|
+
} else {
|
|
307
|
+
this.collection.store.drop(key);
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
/** With persistence, a subset that restored no rows shows an empty result once the network took too long */
|
|
313
|
+
private startNetworkTimeout = () => {
|
|
314
|
+
const { persistence } = this.collection.db;
|
|
315
|
+
if (!persistence || this.hasLoaded) {
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
return setTimeout(() => {
|
|
319
|
+
if (this.hasLoaded) {
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
this.hasLoaded = true;
|
|
323
|
+
this.loadedAt = 0;
|
|
324
|
+
this.invalidated = true;
|
|
325
|
+
this.notify();
|
|
326
|
+
}, persistence.networkTimeout);
|
|
327
|
+
};
|
|
328
|
+
}
|
package/src/sync/sync.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { ListenerInstance } from "@hyper-fetch/sockets";
|
|
2
|
+
|
|
3
|
+
import type { SyncConfig } from "../collection/collection.types";
|
|
4
|
+
import type { Stamp } from "../store/store.types";
|
|
5
|
+
|
|
6
|
+
export type SyncHost = {
|
|
7
|
+
tick: () => number;
|
|
8
|
+
applySyncMessage: (sync: SyncConfig, message: unknown, stamp: Stamp) => void;
|
|
9
|
+
onLiveChange: () => void;
|
|
10
|
+
onRemove: (subscription: SyncSubscription) => void;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* One server-side subscription of a sync, for one set of filter values. Subsets that need the same subscription
|
|
15
|
+
* share it, and it stops when the last one releases it.
|
|
16
|
+
*
|
|
17
|
+
* While a subset that uses it is loading, events are buffered and applied after the response, so an `update` for a row
|
|
18
|
+
* that only the response brings is not lost.
|
|
19
|
+
*/
|
|
20
|
+
export class SyncSubscription {
|
|
21
|
+
started = false;
|
|
22
|
+
private users = new Set<object>();
|
|
23
|
+
private loading = new Set<object>();
|
|
24
|
+
private buffer: { message: unknown; stamp: Stamp }[] = [];
|
|
25
|
+
private unsubscribe: (() => void) | undefined;
|
|
26
|
+
|
|
27
|
+
readonly id: string;
|
|
28
|
+
readonly sync: SyncConfig;
|
|
29
|
+
readonly listener: ListenerInstance;
|
|
30
|
+
private readonly host: SyncHost;
|
|
31
|
+
|
|
32
|
+
constructor(options: { id: string; sync: SyncConfig; listener: ListenerInstance; host: SyncHost }) {
|
|
33
|
+
this.id = options.id;
|
|
34
|
+
this.sync = options.sync;
|
|
35
|
+
this.listener = options.listener;
|
|
36
|
+
this.host = options.host;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Whether the server has started the subscription and the socket is connected */
|
|
40
|
+
isLive = () => this.started && this.listener.socket.adapter.connected;
|
|
41
|
+
|
|
42
|
+
addUser = (user: object) => {
|
|
43
|
+
this.users.add(user);
|
|
44
|
+
if (this.unsubscribe) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
// A `changes` sync reads the whole event, such as a Firestore snapshot with its grouped changes
|
|
48
|
+
const toMessage = (event: { data: unknown }) => (this.sync.type === "changes" ? event : event.data);
|
|
49
|
+
this.unsubscribe = this.listener.listen((event: { data: unknown }) => this.receive(toMessage(event)), {
|
|
50
|
+
onStart: () => {
|
|
51
|
+
this.started = true;
|
|
52
|
+
this.host.onLiveChange();
|
|
53
|
+
},
|
|
54
|
+
onEnd: () => {
|
|
55
|
+
this.started = false;
|
|
56
|
+
this.unsubscribe = undefined;
|
|
57
|
+
this.host.onLiveChange();
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
removeUser = (user: object) => {
|
|
63
|
+
this.users.delete(user);
|
|
64
|
+
this.endLoad(user);
|
|
65
|
+
if (this.users.size > 0) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
this.unsubscribe?.();
|
|
69
|
+
this.unsubscribe = undefined;
|
|
70
|
+
this.started = false;
|
|
71
|
+
this.host.onRemove(this);
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
getUsers = () => [...this.users];
|
|
75
|
+
|
|
76
|
+
beginLoad = (user: object) => {
|
|
77
|
+
this.loading.add(user);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
endLoad = (user: object) => {
|
|
81
|
+
this.loading.delete(user);
|
|
82
|
+
if (this.loading.size > 0) {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const buffered = this.buffer;
|
|
86
|
+
this.buffer = [];
|
|
87
|
+
buffered.forEach(({ message, stamp }) => this.host.applySyncMessage(this.sync, message, stamp));
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
private receive = (message: unknown) => {
|
|
91
|
+
const seq = this.host.tick();
|
|
92
|
+
const stamp: Stamp = { kind: "now", seq, wall: Date.now() };
|
|
93
|
+
if (this.loading.size > 0) {
|
|
94
|
+
this.buffer.push({ message, stamp });
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
this.host.applySyncMessage(this.sync, message, stamp);
|
|
98
|
+
};
|
|
99
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { RequestInstance } from "@hyper-fetch/core";
|
|
2
|
+
import type { ListenerInstance } from "@hyper-fetch/sockets";
|
|
3
|
+
|
|
4
|
+
import type { AnyRequestPatch, ListenerPatch } from "../collection/collection.types";
|
|
5
|
+
|
|
6
|
+
export const isPlainObject = (value: unknown): value is Record<string, unknown> => {
|
|
7
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
/** Objects merge and arrays, such as Firestore constraints, add up. Anything else replaces the current value. */
|
|
11
|
+
const mergeValue = (current: unknown, next: unknown) => {
|
|
12
|
+
if (isPlainObject(current) && isPlainObject(next)) {
|
|
13
|
+
return { ...current, ...next };
|
|
14
|
+
}
|
|
15
|
+
if (Array.isArray(current) && Array.isArray(next)) {
|
|
16
|
+
return [...current, ...next];
|
|
17
|
+
}
|
|
18
|
+
return next;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** Applies patches to a request, merging params, query params and object payloads into what it already has */
|
|
22
|
+
export const applyRequestPatches = <Req extends RequestInstance>(
|
|
23
|
+
request: Req,
|
|
24
|
+
patches: readonly AnyRequestPatch[],
|
|
25
|
+
): Req => {
|
|
26
|
+
let next: RequestInstance = request;
|
|
27
|
+
patches.forEach((patch) => {
|
|
28
|
+
if (patch.params) {
|
|
29
|
+
next = next.setParams({ ...(next.params as Record<string, unknown> | undefined), ...patch.params } as never);
|
|
30
|
+
}
|
|
31
|
+
if (patch.queryParams !== undefined) {
|
|
32
|
+
next = next.setQueryParams(mergeValue(next.queryParams, patch.queryParams) as never);
|
|
33
|
+
}
|
|
34
|
+
if ("payload" in patch) {
|
|
35
|
+
next = next.setPayload(mergeValue(next.payload, patch.payload));
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
return next as Req;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** Applies patches to a listener, merging topic params, payloads and query params into what it already has */
|
|
42
|
+
export const applyListenerPatches = (listener: ListenerInstance, patches: readonly ListenerPatch[]) => {
|
|
43
|
+
let next = listener;
|
|
44
|
+
patches.forEach((patch) => {
|
|
45
|
+
if (patch.params) {
|
|
46
|
+
next = next.setParams({ ...next.params, ...patch.params } as never);
|
|
47
|
+
}
|
|
48
|
+
if ("payload" in patch) {
|
|
49
|
+
next = next.setPayload(mergeValue(next.payload, patch.payload));
|
|
50
|
+
}
|
|
51
|
+
if (patch.queryParams !== undefined) {
|
|
52
|
+
next = next.setQueryParams(mergeValue(next.queryParams, patch.queryParams) as never);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
return next;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
let idCounter = 0;
|
|
59
|
+
|
|
60
|
+
/** A unique id for transactions and temporary keys */
|
|
61
|
+
export const createId = (): string => {
|
|
62
|
+
if (typeof globalThis.crypto?.randomUUID === "function") {
|
|
63
|
+
return globalThis.crypto.randomUUID();
|
|
64
|
+
}
|
|
65
|
+
idCounter += 1;
|
|
66
|
+
return `${Date.now().toString(36)}-${idCounter.toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
67
|
+
};
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"rootDir": ".",
|
|
5
|
+
"outDir": "./dist",
|
|
6
|
+
"paths": {
|
|
7
|
+
"@hyper-fetch/db": ["./src"]
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
"include": ["src/**/*.ts", "../../global.d.ts"],
|
|
11
|
+
"exclude": ["node_modules", "dist", "vite.config.ts", "__tests__"]
|
|
12
|
+
}
|
package/vite.config.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
/// <reference types="vitest/config" />
|
|
3
|
+
import { defineConfig } from "vite";
|
|
4
|
+
import dts from "vite-plugin-dts";
|
|
5
|
+
import tsconfigPaths from "vite-tsconfig-paths";
|
|
6
|
+
|
|
7
|
+
import { getRollupExternalsFromPackageJson } from "../../scripts/vite-lib-externals-from-package";
|
|
8
|
+
|
|
9
|
+
export default defineConfig({
|
|
10
|
+
build: {
|
|
11
|
+
lib: {
|
|
12
|
+
entry: "src/index.ts",
|
|
13
|
+
fileName: "index",
|
|
14
|
+
formats: ["es"],
|
|
15
|
+
},
|
|
16
|
+
minify: false,
|
|
17
|
+
rollupOptions: {
|
|
18
|
+
external: getRollupExternalsFromPackageJson(__dirname),
|
|
19
|
+
},
|
|
20
|
+
sourcemap: true,
|
|
21
|
+
},
|
|
22
|
+
plugins: [tsconfigPaths(), dts({ entryRoot: "src" })],
|
|
23
|
+
test: {
|
|
24
|
+
alias: {
|
|
25
|
+
"@hyper-fetch/core": path.resolve(__dirname, "../core/src/index.ts"),
|
|
26
|
+
"@hyper-fetch/sockets": path.resolve(__dirname, "../sockets/src/index.ts"),
|
|
27
|
+
"@hyper-fetch/testing": path.resolve(__dirname, "../testing/src/index.ts"),
|
|
28
|
+
"@hyper-fetch/db": path.resolve(__dirname, "./src/index.ts"),
|
|
29
|
+
},
|
|
30
|
+
coverage: {
|
|
31
|
+
exclude: ["**/*.spec.*", "**/*.types.ts", "**/index.ts"],
|
|
32
|
+
include: ["src/**/*.ts"],
|
|
33
|
+
provider: "v8",
|
|
34
|
+
thresholds: { lines: 100, branches: 100, functions: 100, statements: 100 },
|
|
35
|
+
},
|
|
36
|
+
globals: true,
|
|
37
|
+
setupFiles: ["./__tests__/vitest.setup.ts"],
|
|
38
|
+
typecheck: {
|
|
39
|
+
enabled: true,
|
|
40
|
+
include: ["__tests__/**/*.types.spec.ts"],
|
|
41
|
+
tsconfig: "./__tests__/tsconfig.json",
|
|
42
|
+
},
|
|
43
|
+
projects: [
|
|
44
|
+
{
|
|
45
|
+
extends: true,
|
|
46
|
+
test: {
|
|
47
|
+
name: "unit",
|
|
48
|
+
environment: "node",
|
|
49
|
+
include: ["__tests__/features/**/*.spec.ts"],
|
|
50
|
+
exclude: ["__tests__/**/*.types.spec.ts"],
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
extends: true,
|
|
55
|
+
test: {
|
|
56
|
+
name: "integration",
|
|
57
|
+
environment: "node",
|
|
58
|
+
include: ["__tests__/integration/**/*.spec.ts"],
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
extends: true,
|
|
63
|
+
test: {
|
|
64
|
+
name: "e2e",
|
|
65
|
+
environment: "node",
|
|
66
|
+
include: ["__tests__/e2e/**/*.spec.ts"],
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
],
|
|
70
|
+
},
|
|
71
|
+
});
|