@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,537 @@
|
|
|
1
|
+
import type { ClientInstance } from "@hyper-fetch/core";
|
|
2
|
+
import type { SocketInstance } from "@hyper-fetch/sockets";
|
|
3
|
+
|
|
4
|
+
import type { CollectionInstance } from "../collection/collection";
|
|
5
|
+
import type { CollectionConfig, RowKey } from "../collection/collection.types";
|
|
6
|
+
import { MutationEngine } from "../mutation/mutation";
|
|
7
|
+
import { stableStringify } from "../operators/operators.utils";
|
|
8
|
+
import { Persistence } from "../persistence/persistence";
|
|
9
|
+
import type { Serializer } from "../persistence/serializer";
|
|
10
|
+
import { createSerializer } from "../persistence/serializer";
|
|
11
|
+
import type { CollectionSnapshot } from "../persistence/snapshot";
|
|
12
|
+
import { restoreSnapshot, snapshotCollection } from "../persistence/snapshot";
|
|
13
|
+
import type { TabsMessage } from "../persistence/tabs";
|
|
14
|
+
import { Tabs } from "../persistence/tabs";
|
|
15
|
+
import { LiveQuery } from "../query/live-query";
|
|
16
|
+
import type { QueryDefinition } from "../query/query.types";
|
|
17
|
+
import type { KeySubset } from "../subset/key-subset";
|
|
18
|
+
import { ListSubset } from "../subset/list-subset";
|
|
19
|
+
import { CollectionRuntime } from "./collection.runtime";
|
|
20
|
+
import type {
|
|
21
|
+
DbErrorEvent,
|
|
22
|
+
DbInspection,
|
|
23
|
+
DbNotation,
|
|
24
|
+
DbOptions,
|
|
25
|
+
DehydratedDb,
|
|
26
|
+
TransactionConfig,
|
|
27
|
+
TransactionRecord,
|
|
28
|
+
} from "./db.types";
|
|
29
|
+
|
|
30
|
+
const DEFAULT_GC_TIME = 5 * 60 * 1000;
|
|
31
|
+
const DEFAULT_SYNC_TIMEOUT = 5000;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The running db. It owns the collections, batches writes into transactions so every query updates once, revalidates
|
|
35
|
+
* stale subsets on focus and reconnect, and connects persistence, the outbox and other tabs.
|
|
36
|
+
*/
|
|
37
|
+
export class DbRuntime {
|
|
38
|
+
readonly collections = new Map<string, CollectionRuntime>();
|
|
39
|
+
readonly gcTime: number;
|
|
40
|
+
readonly syncTimeout: number;
|
|
41
|
+
readonly notation: DbNotation;
|
|
42
|
+
readonly mutations: MutationEngine;
|
|
43
|
+
readonly persistence: Persistence | undefined;
|
|
44
|
+
private readonly serializer: Serializer;
|
|
45
|
+
private changeListeners = new Set<() => void>();
|
|
46
|
+
/** Timers of sync waits, cleared on `destroy` */
|
|
47
|
+
private timers = new Set<ReturnType<typeof setTimeout>>();
|
|
48
|
+
private queryTimers = new Map<LiveQuery, ReturnType<typeof setTimeout>>();
|
|
49
|
+
readonly tabs: Tabs | undefined;
|
|
50
|
+
readonly ready: Promise<void>;
|
|
51
|
+
/** Changes on `clear`, so responses to requests sent before are never written */
|
|
52
|
+
generation = 0;
|
|
53
|
+
isReady = true;
|
|
54
|
+
isDestroyed = false;
|
|
55
|
+
private seq = 0;
|
|
56
|
+
private batchDepth = 0;
|
|
57
|
+
private changedRows = new Map<CollectionRuntime, Set<RowKey>>();
|
|
58
|
+
private dirtyQueries = new Set<LiveQuery>();
|
|
59
|
+
private liveQueries = new Map<string, LiveQuery>();
|
|
60
|
+
private inflight = new Set<number>();
|
|
61
|
+
private errorListeners = new Set<(event: DbErrorEvent) => void>();
|
|
62
|
+
private syncWaiters = new Map<string, Set<() => void>>();
|
|
63
|
+
private lastSyncWrite = new Map<string, number>();
|
|
64
|
+
private sockets = new Set<SocketInstance>();
|
|
65
|
+
private cleanups: (() => void)[] = [];
|
|
66
|
+
|
|
67
|
+
constructor(
|
|
68
|
+
collections: Record<string, CollectionInstance>,
|
|
69
|
+
options: DbOptions & {
|
|
70
|
+
links?: readonly (readonly [string, string])[];
|
|
71
|
+
transactions?: Record<string, TransactionConfig>;
|
|
72
|
+
} = {},
|
|
73
|
+
) {
|
|
74
|
+
this.gcTime = options.gcTime ?? DEFAULT_GC_TIME;
|
|
75
|
+
this.syncTimeout = options.syncTimeout ?? DEFAULT_SYNC_TIMEOUT;
|
|
76
|
+
this.notation = { where: options.where, orderBy: options.orderBy };
|
|
77
|
+
this.mutations = new MutationEngine(this, options.offline, options.transactions);
|
|
78
|
+
this.serializer = createSerializer(options.codecs);
|
|
79
|
+
|
|
80
|
+
Object.entries(collections).forEach(([name, definition]) => {
|
|
81
|
+
this.collections.set(name, new CollectionRuntime(this, name, definition.config));
|
|
82
|
+
});
|
|
83
|
+
// A reference to a collection the db does not hold is a setup mistake, so it fails here and not during a write
|
|
84
|
+
this.collections.forEach((collection) => {
|
|
85
|
+
(collection.config.normalize ?? []).forEach(({ target }) => {
|
|
86
|
+
if (!this.getCollectionByConfig(target)) {
|
|
87
|
+
throw new Error(`"${collection.name}" normalizes into a collection that was not passed to createDb`);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
(options.links ?? []).forEach(([first, second]) => {
|
|
92
|
+
const left = this.collections.get(first)!.store;
|
|
93
|
+
const right = this.collections.get(second)!.store;
|
|
94
|
+
left.link(right);
|
|
95
|
+
right.link(left);
|
|
96
|
+
});
|
|
97
|
+
this.collections.forEach((collection) => {
|
|
98
|
+
collection.config.loaders.forEach((loader) => this.watchClient(loader.request.client));
|
|
99
|
+
Object.values(collection.config.mutations).forEach((mutation) => this.watchClient(mutation!.request.client));
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
if (options.state) {
|
|
103
|
+
this.hydrate(options.state);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (options.persistence) {
|
|
107
|
+
const scope = options.persistence.scope ?? "default";
|
|
108
|
+
this.persistence = new Persistence(this, options.persistence, this.serializer);
|
|
109
|
+
if (options.tabs !== false) {
|
|
110
|
+
this.tabs = new Tabs(`hf-db:${scope}`, options.tabs, {
|
|
111
|
+
onLeader: this.takeLead,
|
|
112
|
+
onMessage: this.onTabsMessage,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
this.isReady = false;
|
|
116
|
+
this.ready = this.restore();
|
|
117
|
+
this.tabs?.start();
|
|
118
|
+
} else {
|
|
119
|
+
this.ready = Promise.resolve();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Listens to every change the db makes, once per batch of writes, load or outbox change. Returns the unsubscribe. */
|
|
124
|
+
onChange = (listener: () => void) => {
|
|
125
|
+
this.changeListeners.add(listener);
|
|
126
|
+
return () => {
|
|
127
|
+
this.changeListeners.delete(listener);
|
|
128
|
+
};
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
notifyChange = () => {
|
|
132
|
+
this.changeListeners.forEach((listener) => listener());
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/** What the db holds right now: collections with their layers and subsets, live queries and the outbox */
|
|
136
|
+
inspect = (): DbInspection => ({
|
|
137
|
+
collections: [...this.collections.values()].map((collection) => ({
|
|
138
|
+
name: collection.name,
|
|
139
|
+
rows: collection.store.keys().length,
|
|
140
|
+
layers: collection.store.getLayers().map(({ id, key, type }) => ({ id, key, type })),
|
|
141
|
+
subsets: collection.getSubsets().map((subset) => ({
|
|
142
|
+
id: subset instanceof ListSubset ? subset.id : String((subset as KeySubset).key),
|
|
143
|
+
kind: subset instanceof ListSubset ? ("list" as const) : ("key" as const),
|
|
144
|
+
loader: collection.config.loaders.indexOf(subset.loader),
|
|
145
|
+
rows:
|
|
146
|
+
subset instanceof ListSubset
|
|
147
|
+
? subset.owned.size
|
|
148
|
+
: Number(Boolean(collection.store.get((subset as KeySubset).key))),
|
|
149
|
+
fresh: subset.isFresh(),
|
|
150
|
+
live: subset.isLive(),
|
|
151
|
+
loading: subset.isLoading,
|
|
152
|
+
error: subset.error,
|
|
153
|
+
loadedAt: subset.loadedAt,
|
|
154
|
+
observers: subset.observerCount,
|
|
155
|
+
})),
|
|
156
|
+
})),
|
|
157
|
+
queries: [...this.liveQueries.values()].map((query) => {
|
|
158
|
+
const state = query.getState();
|
|
159
|
+
return {
|
|
160
|
+
key: query.key,
|
|
161
|
+
collection: query.collection.name,
|
|
162
|
+
subscribers: query.subscriberCount,
|
|
163
|
+
status: state.status,
|
|
164
|
+
rows: Array.isArray(state.data) ? state.data.length : undefined,
|
|
165
|
+
plan: query.explain(),
|
|
166
|
+
};
|
|
167
|
+
}),
|
|
168
|
+
outbox: [...this.mutations.outbox],
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
/** The server rows and loaded subsets of every collection that holds any, as type-tagged JSON */
|
|
172
|
+
dehydrate = (): DehydratedDb => {
|
|
173
|
+
const collections = Object.fromEntries(
|
|
174
|
+
[...this.collections.values()]
|
|
175
|
+
.map((collection) => [collection.name, snapshotCollection(collection)] as const)
|
|
176
|
+
.filter(([, snapshot]) => snapshot.rows.length > 0 || snapshot.subsets.length > 0),
|
|
177
|
+
);
|
|
178
|
+
return { __dehydrated: true, collections: this.serializer.encode(collections) };
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
/** Writes a server's rows and subsets, before anything renders, so the first render matches the server's */
|
|
182
|
+
private hydrate = (state: DehydratedDb) => {
|
|
183
|
+
const collections = this.serializer.decode(state.collections) as Record<string, CollectionSnapshot>;
|
|
184
|
+
Object.entries(collections).forEach(([name, snapshot]) => {
|
|
185
|
+
const collection = this.collections.get(name);
|
|
186
|
+
if (collection) {
|
|
187
|
+
restoreSnapshot(collection, snapshot);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
/** Whether this tab replays the outbox and writes persisted rows */
|
|
193
|
+
get isLeader() {
|
|
194
|
+
return this.tabs ? this.tabs.isLeader : true;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** The collection a config belongs to, for references between collections such as `normalize` */
|
|
198
|
+
getCollectionByConfig = (config: CollectionConfig): CollectionRuntime | undefined => {
|
|
199
|
+
return [...this.collections.values()].find((item) => item.config === config);
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
tick = () => {
|
|
203
|
+
this.seq += 1;
|
|
204
|
+
return this.seq;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/** Runs writes as one transaction: every query updates once, after the last write */
|
|
208
|
+
batch = <T>(callback: () => T): T => {
|
|
209
|
+
this.batchDepth += 1;
|
|
210
|
+
try {
|
|
211
|
+
return callback();
|
|
212
|
+
} finally {
|
|
213
|
+
this.batchDepth -= 1;
|
|
214
|
+
if (this.batchDepth === 0) {
|
|
215
|
+
this.flush();
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
/** Records a changed row. Every store write runs inside `batch`, which flushes the changes once it ends. */
|
|
221
|
+
markRowChanged = (collection: CollectionRuntime, key: RowKey) => {
|
|
222
|
+
const keys = this.changedRows.get(collection) ?? new Set<RowKey>();
|
|
223
|
+
keys.add(key);
|
|
224
|
+
this.changedRows.set(collection, keys);
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
markQueryDirty = (query: LiveQuery) => {
|
|
228
|
+
this.dirtyQueries.add(query);
|
|
229
|
+
if (this.batchDepth === 0) {
|
|
230
|
+
this.flush();
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/** The live query for a definition, shared by every query with the same structure */
|
|
235
|
+
getLiveQuery = (definition: QueryDefinition): LiveQuery => {
|
|
236
|
+
const key = stableStringify(definition);
|
|
237
|
+
const existing = this.liveQueries.get(key);
|
|
238
|
+
if (existing) {
|
|
239
|
+
return existing;
|
|
240
|
+
}
|
|
241
|
+
const collection = this.collections.get(definition.collection)!;
|
|
242
|
+
const query = new LiveQuery(collection, definition, key);
|
|
243
|
+
this.liveQueries.set(key, query);
|
|
244
|
+
this.releaseLater(query);
|
|
245
|
+
return query;
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Forgets a live query nobody subscribes to after `gcTime`, so queries made once, such as each search, do not pile
|
|
250
|
+
* up and slow every write. A query read again later is made again.
|
|
251
|
+
*/
|
|
252
|
+
releaseLater = (query: LiveQuery) => {
|
|
253
|
+
clearTimeout(this.queryTimers.get(query));
|
|
254
|
+
const timer = setTimeout(() => {
|
|
255
|
+
this.queryTimers.delete(query);
|
|
256
|
+
if (!query.isActive() && this.liveQueries.get(query.key) === query) {
|
|
257
|
+
this.liveQueries.delete(query.key);
|
|
258
|
+
}
|
|
259
|
+
}, this.gcTime);
|
|
260
|
+
this.queryTimers.set(query, timer);
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
trackRequest = (seq: number) => {
|
|
264
|
+
this.inflight.add(seq);
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
/** A request the db sent settled, so deletes made after every pending request no longer need remembering */
|
|
268
|
+
settleRequest = (seq: number) => {
|
|
269
|
+
this.inflight.delete(seq);
|
|
270
|
+
const oldest = this.inflight.size > 0 ? Math.min(...this.inflight) : Number.POSITIVE_INFINITY;
|
|
271
|
+
this.collections.forEach((collection) => collection.store.forgetTombstones(oldest));
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
onError = (listener: (event: DbErrorEvent) => void) => {
|
|
275
|
+
this.errorListeners.add(listener);
|
|
276
|
+
return () => {
|
|
277
|
+
this.errorListeners.delete(listener);
|
|
278
|
+
};
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
emitError = (event: DbErrorEvent) => {
|
|
282
|
+
this.errorListeners.forEach((listener) => listener(event));
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
/** A sync event touched a row, which writes with `onSuccess: "sync"` wait for */
|
|
286
|
+
notifySyncWrite = (collection: string, key: RowKey) => {
|
|
287
|
+
const id = `${collection}:${String(key)}`;
|
|
288
|
+
this.lastSyncWrite.set(id, this.tick());
|
|
289
|
+
const waiters = this.syncWaiters.get(id);
|
|
290
|
+
this.syncWaiters.delete(id);
|
|
291
|
+
waiters?.forEach((resolve) => resolve());
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Resolves with `true` when a sync event touched the row after `since`, also while the write was in flight, or with
|
|
296
|
+
* `false` after the timeout
|
|
297
|
+
*/
|
|
298
|
+
waitForSync = ({
|
|
299
|
+
collection,
|
|
300
|
+
key,
|
|
301
|
+
since,
|
|
302
|
+
timeout,
|
|
303
|
+
}: {
|
|
304
|
+
collection: string;
|
|
305
|
+
key: RowKey;
|
|
306
|
+
since: number;
|
|
307
|
+
timeout: number;
|
|
308
|
+
}): Promise<boolean> => {
|
|
309
|
+
const id = `${collection}:${String(key)}`;
|
|
310
|
+
if ((this.lastSyncWrite.get(id) ?? 0) > since) {
|
|
311
|
+
return Promise.resolve(true);
|
|
312
|
+
}
|
|
313
|
+
return new Promise((resolve) => {
|
|
314
|
+
const waiters = this.syncWaiters.get(id) ?? new Set<() => void>();
|
|
315
|
+
const timer = setTimeout(() => {
|
|
316
|
+
this.timers.delete(timer);
|
|
317
|
+
waiters.delete(onSync);
|
|
318
|
+
resolve(false);
|
|
319
|
+
}, timeout);
|
|
320
|
+
this.timers.add(timer);
|
|
321
|
+
const onSync = () => {
|
|
322
|
+
clearTimeout(timer);
|
|
323
|
+
this.timers.delete(timer);
|
|
324
|
+
resolve(true);
|
|
325
|
+
};
|
|
326
|
+
waiters.add(onSync);
|
|
327
|
+
this.syncWaiters.set(id, waiters);
|
|
328
|
+
});
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
/** Marks the subsets a socket's syncs covered stale after a reconnect, unless their subscriptions resume */
|
|
332
|
+
watchSocket = (socket: SocketInstance) => {
|
|
333
|
+
if (this.sockets.has(socket)) {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
this.sockets.add(socket);
|
|
337
|
+
// A connection after an earlier one is a reconnect, whether or not the disconnect was reported
|
|
338
|
+
let connectedBefore = socket.adapter.connected;
|
|
339
|
+
const notifyAll = () => {
|
|
340
|
+
this.collections.forEach((collection) => collection.getSubsets().forEach((subset) => subset.notify()));
|
|
341
|
+
};
|
|
342
|
+
this.cleanups.push(
|
|
343
|
+
socket.events.onDisconnected(notifyAll),
|
|
344
|
+
socket.events.onConnected(() => {
|
|
345
|
+
if (connectedBefore) {
|
|
346
|
+
this.collections.forEach((collection) => {
|
|
347
|
+
collection.subscriptions.forEach((subscription) => {
|
|
348
|
+
if (subscription.listener.socket !== socket || subscription.sync.resumes) {
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
subscription.getUsers().forEach((user) => {
|
|
352
|
+
const subset = user as ReturnType<CollectionRuntime["getSubsets"]>[number];
|
|
353
|
+
subset.invalidate();
|
|
354
|
+
if (subset.isUsed()) {
|
|
355
|
+
subset.revalidate();
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
connectedBefore = true;
|
|
362
|
+
notifyAll();
|
|
363
|
+
}),
|
|
364
|
+
);
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
/** Removes every row, loaded subset and pending write, and the persisted data of the scope */
|
|
368
|
+
clear = async () => {
|
|
369
|
+
this.tabs?.post({ type: "clear" });
|
|
370
|
+
this.clearLocal();
|
|
371
|
+
await this.persistence?.clear();
|
|
372
|
+
this.revalidateActive();
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
/** Refetches the stale subsets of every mounted query */
|
|
376
|
+
private revalidateActive = () => {
|
|
377
|
+
this.liveQueries.forEach((query) => {
|
|
378
|
+
if (query.isActive()) {
|
|
379
|
+
query.revalidate();
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Drops rows, subsets and pending writes in this tab. Responses to requests sent before belong to the previous user,
|
|
386
|
+
* so the generation changes and they are never written.
|
|
387
|
+
*/
|
|
388
|
+
private clearLocal = () => {
|
|
389
|
+
this.generation += 1;
|
|
390
|
+
this.mutations.clear();
|
|
391
|
+
this.batch(() => this.collections.forEach((collection) => collection.clear()));
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
/** This tab became the leader: it adopts the persisted outbox, so the previous leader's writes are replayed */
|
|
395
|
+
private takeLead = async () => {
|
|
396
|
+
// Tabs coordinate only a db that persists, so there is always a stored outbox to adopt
|
|
397
|
+
const stored = await this.persistence!.loadOutbox();
|
|
398
|
+
this.mutations.mergeOutbox(stored);
|
|
399
|
+
this.tabs?.post({ type: "leader" });
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
destroy = () => {
|
|
403
|
+
this.isDestroyed = true;
|
|
404
|
+
this.mutations.destroy();
|
|
405
|
+
this.timers.forEach((timer) => clearTimeout(timer));
|
|
406
|
+
this.timers.clear();
|
|
407
|
+
this.queryTimers.forEach((timer) => clearTimeout(timer));
|
|
408
|
+
this.queryTimers.clear();
|
|
409
|
+
this.liveQueries.clear();
|
|
410
|
+
this.cleanups.forEach((cleanup) => cleanup());
|
|
411
|
+
this.cleanups = [];
|
|
412
|
+
this.collections.forEach((collection) => collection.destroy());
|
|
413
|
+
this.persistence?.destroy();
|
|
414
|
+
this.tabs?.close();
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
private watchClients = new Set<ClientInstance>();
|
|
418
|
+
|
|
419
|
+
private watchClient = (client: ClientInstance) => {
|
|
420
|
+
if (this.watchClients.has(client)) {
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
this.watchClients.add(client);
|
|
424
|
+
const revalidate = () => {
|
|
425
|
+
this.liveQueries.forEach((query) => {
|
|
426
|
+
if (query.isActive()) {
|
|
427
|
+
query.revalidate();
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
};
|
|
431
|
+
this.cleanups.push(
|
|
432
|
+
client.appManager.events.onFocus(revalidate),
|
|
433
|
+
client.appManager.events.onOnline(() => {
|
|
434
|
+
revalidate();
|
|
435
|
+
this.mutations.pump();
|
|
436
|
+
}),
|
|
437
|
+
);
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
private flush = () => {
|
|
441
|
+
const changed = this.changedRows.size > 0 || this.dirtyQueries.size > 0;
|
|
442
|
+
this.flushPending();
|
|
443
|
+
if (changed) {
|
|
444
|
+
this.notifyChange();
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
private flushPending = () => {
|
|
449
|
+
while (this.changedRows.size > 0 || this.dirtyQueries.size > 0) {
|
|
450
|
+
const rows = this.changedRows;
|
|
451
|
+
const dirty = this.dirtyQueries;
|
|
452
|
+
this.changedRows = new Map();
|
|
453
|
+
this.dirtyQueries = new Set();
|
|
454
|
+
this.liveQueries.forEach((query) => {
|
|
455
|
+
const keys = rows.get(query.collection);
|
|
456
|
+
if (keys && !dirty.has(query)) {
|
|
457
|
+
query.onRowsChanged(keys);
|
|
458
|
+
}
|
|
459
|
+
if (
|
|
460
|
+
!dirty.has(query) &&
|
|
461
|
+
query.isActive() &&
|
|
462
|
+
[...rows.keys()].some((collection) => query.dependsOn(collection))
|
|
463
|
+
) {
|
|
464
|
+
query.onJoinedRowsChanged();
|
|
465
|
+
}
|
|
466
|
+
});
|
|
467
|
+
dirty.forEach((query) => query.rebuild());
|
|
468
|
+
rows.forEach((keys, collection) => collection.refreshKeySyncs(keys));
|
|
469
|
+
if (rows.size > 0) {
|
|
470
|
+
this.persistence?.scheduleSave(rows.keys());
|
|
471
|
+
this.forwardRows(rows);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
/** Tabs that do not persist send their server rows to the tab that does */
|
|
477
|
+
private forwardRows = (rows: Map<CollectionRuntime, Set<RowKey>>) => {
|
|
478
|
+
if (!this.tabs || this.isLeader || !this.isReady) {
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
rows.forEach((keys, collection) => {
|
|
482
|
+
const entries = [...keys]
|
|
483
|
+
.map((key) => [key, collection.store.getServerRow(key)] as const)
|
|
484
|
+
.filter((entry): entry is readonly [RowKey, Record<string, unknown>] => Boolean(entry[1]));
|
|
485
|
+
if (entries.length > 0) {
|
|
486
|
+
this.tabs!.post({ type: "rows", collection: collection.name, rows: entries.map(([key, row]) => [key, row]) });
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
private onTabsMessage = (message: TabsMessage) => {
|
|
492
|
+
if (message.type === "outcome") {
|
|
493
|
+
this.mutations.applyOutcome(message);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
if (message.type === "clear") {
|
|
497
|
+
this.clearLocal();
|
|
498
|
+
this.revalidateActive();
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
if (message.type === "leader") {
|
|
502
|
+
this.mutations.resendToLeader();
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
if (!this.isLeader) {
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
if (message.type === "enqueue") {
|
|
509
|
+
this.mutations.mergeOutbox(message.records);
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
const collection = this.collections.get(message.collection);
|
|
513
|
+
if (!collection) {
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
this.batch(() => {
|
|
517
|
+
message.rows.forEach(([key, row]) => {
|
|
518
|
+
if (!collection.store.hasServerRow(key)) {
|
|
519
|
+
collection.store.write(key, row, { complete: true, stamp: { kind: "sent", seq: 0, wall: 0 } });
|
|
520
|
+
}
|
|
521
|
+
});
|
|
522
|
+
});
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
private restore = async () => {
|
|
526
|
+
let outbox: TransactionRecord[] = [];
|
|
527
|
+
try {
|
|
528
|
+
outbox = await this.persistence!.restore();
|
|
529
|
+
} catch (error) {
|
|
530
|
+
// A broken store must not keep the db from starting: it starts with what the network brings
|
|
531
|
+
this.emitError({ type: "persistence", error });
|
|
532
|
+
}
|
|
533
|
+
this.isReady = true;
|
|
534
|
+
this.mutations.restore(outbox);
|
|
535
|
+
this.batch(() => this.liveQueries.forEach((query) => this.markQueryDirty(query)));
|
|
536
|
+
};
|
|
537
|
+
}
|