@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.
Files changed (141) hide show
  1. package/README.md +180 -2
  2. package/__tests__/e2e/db.e2e.spec.ts +269 -0
  3. package/__tests__/features/connection/connection.spec.ts +23 -0
  4. package/__tests__/features/model/live-query.model.spec.ts +320 -0
  5. package/__tests__/features/operators/operators.spec.ts +113 -0
  6. package/__tests__/features/runtime/runtime.spec.ts +185 -0
  7. package/__tests__/features/serializer/serializer.spec.ts +73 -0
  8. package/__tests__/features/store/store.spec.ts +147 -0
  9. package/__tests__/features/types/db.types.spec.ts +337 -0
  10. package/__tests__/integration/audit.spec.ts +639 -0
  11. package/__tests__/integration/competitors.spec.ts +393 -0
  12. package/__tests__/integration/convergence.model.spec.ts +162 -0
  13. package/__tests__/integration/edge-cases.spec.ts +465 -0
  14. package/__tests__/integration/errors.spec.ts +178 -0
  15. package/__tests__/integration/infinite.model.spec.ts +142 -0
  16. package/__tests__/integration/infinite.spec.ts +290 -0
  17. package/__tests__/integration/inspect.spec.ts +103 -0
  18. package/__tests__/integration/joins-many.spec.ts +177 -0
  19. package/__tests__/integration/joins.spec.ts +179 -0
  20. package/__tests__/integration/key-loaders.spec.ts +196 -0
  21. package/__tests__/integration/links.spec.ts +105 -0
  22. package/__tests__/integration/mutations.spec.ts +337 -0
  23. package/__tests__/integration/normalize.spec.ts +80 -0
  24. package/__tests__/integration/offline.spec.ts +479 -0
  25. package/__tests__/integration/queries.spec.ts +513 -0
  26. package/__tests__/integration/races.spec.ts +127 -0
  27. package/__tests__/integration/server-operators.spec.ts +123 -0
  28. package/__tests__/integration/ssr.spec.ts +111 -0
  29. package/__tests__/integration/syncs.spec.ts +564 -0
  30. package/__tests__/integration/transactions.spec.ts +344 -0
  31. package/__tests__/integration/windows.spec.ts +192 -0
  32. package/__tests__/tsconfig.json +11 -0
  33. package/__tests__/type-budget/budget.fixture.ts +2476 -0
  34. package/__tests__/type-budget/tsconfig.json +4 -0
  35. package/__tests__/utils/fixtures.ts +225 -0
  36. package/__tests__/utils/random.ts +19 -0
  37. package/__tests__/vitest.setup.ts +11 -0
  38. package/dist/collection/collection.d.ts +111 -0
  39. package/dist/collection/collection.d.ts.map +1 -0
  40. package/dist/collection/collection.types.d.ts +316 -0
  41. package/dist/collection/collection.types.d.ts.map +1 -0
  42. package/dist/collection/resource.types.d.ts +77 -0
  43. package/dist/collection/resource.types.d.ts.map +1 -0
  44. package/dist/db/collection.runtime.d.ts +98 -0
  45. package/dist/db/collection.runtime.d.ts.map +1 -0
  46. package/dist/db/db.d.ts +154 -0
  47. package/dist/db/db.d.ts.map +1 -0
  48. package/dist/db/db.runtime.d.ts +114 -0
  49. package/dist/db/db.runtime.d.ts.map +1 -0
  50. package/dist/db/db.types.d.ts +162 -0
  51. package/dist/db/db.types.d.ts.map +1 -0
  52. package/dist/graphql/connection.d.ts +25 -0
  53. package/dist/graphql/connection.d.ts.map +1 -0
  54. package/dist/index.d.ts +17 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.mjs +4220 -0
  57. package/dist/index.mjs.map +1 -0
  58. package/dist/mutation/mutation.d.ts +136 -0
  59. package/dist/mutation/mutation.d.ts.map +1 -0
  60. package/dist/mutation/mutation.errors.d.ts +6 -0
  61. package/dist/mutation/mutation.errors.d.ts.map +1 -0
  62. package/dist/mutation/mutation.utils.d.ts +35 -0
  63. package/dist/mutation/mutation.utils.d.ts.map +1 -0
  64. package/dist/operators/operators.d.ts +33 -0
  65. package/dist/operators/operators.d.ts.map +1 -0
  66. package/dist/operators/operators.types.d.ts +68 -0
  67. package/dist/operators/operators.types.d.ts.map +1 -0
  68. package/dist/operators/operators.utils.d.ts +19 -0
  69. package/dist/operators/operators.utils.d.ts.map +1 -0
  70. package/dist/persistence/persistence.d.ts +42 -0
  71. package/dist/persistence/persistence.d.ts.map +1 -0
  72. package/dist/persistence/serializer.d.ts +23 -0
  73. package/dist/persistence/serializer.d.ts.map +1 -0
  74. package/dist/persistence/snapshot.d.ts +29 -0
  75. package/dist/persistence/snapshot.d.ts.map +1 -0
  76. package/dist/persistence/tabs.d.ts +53 -0
  77. package/dist/persistence/tabs.d.ts.map +1 -0
  78. package/dist/query/infinite-query.d.ts +59 -0
  79. package/dist/query/infinite-query.d.ts.map +1 -0
  80. package/dist/query/live-query.d.ts +85 -0
  81. package/dist/query/live-query.d.ts.map +1 -0
  82. package/dist/query/planner.d.ts +57 -0
  83. package/dist/query/planner.d.ts.map +1 -0
  84. package/dist/query/query.d.ts +155 -0
  85. package/dist/query/query.d.ts.map +1 -0
  86. package/dist/query/query.types.d.ts +71 -0
  87. package/dist/query/query.types.d.ts.map +1 -0
  88. package/dist/schema/schema.types.d.ts +33 -0
  89. package/dist/schema/schema.types.d.ts.map +1 -0
  90. package/dist/store/store.d.ts +76 -0
  91. package/dist/store/store.d.ts.map +1 -0
  92. package/dist/store/store.types.d.ts +27 -0
  93. package/dist/store/store.types.d.ts.map +1 -0
  94. package/dist/subset/base-subset.d.ts +66 -0
  95. package/dist/subset/base-subset.d.ts.map +1 -0
  96. package/dist/subset/key-subset.d.ts +23 -0
  97. package/dist/subset/key-subset.d.ts.map +1 -0
  98. package/dist/subset/list-subset.d.ts +63 -0
  99. package/dist/subset/list-subset.d.ts.map +1 -0
  100. package/dist/sync/sync.d.ts +42 -0
  101. package/dist/sync/sync.d.ts.map +1 -0
  102. package/dist/utils/request.utils.d.ts +11 -0
  103. package/dist/utils/request.utils.d.ts.map +1 -0
  104. package/package.json +71 -4
  105. package/project.json +4 -0
  106. package/scripts/docs-typescript.mjs +24 -0
  107. package/scripts/type-budget.mjs +37 -0
  108. package/src/collection/collection.ts +330 -0
  109. package/src/collection/collection.types.ts +383 -0
  110. package/src/collection/resource.types.ts +114 -0
  111. package/src/db/collection.runtime.ts +572 -0
  112. package/src/db/db.runtime.ts +537 -0
  113. package/src/db/db.ts +451 -0
  114. package/src/db/db.types.ts +157 -0
  115. package/src/graphql/connection.ts +23 -0
  116. package/src/index.ts +16 -0
  117. package/src/mutation/mutation.errors.ts +7 -0
  118. package/src/mutation/mutation.ts +776 -0
  119. package/src/mutation/mutation.utils.ts +58 -0
  120. package/src/operators/operators.ts +90 -0
  121. package/src/operators/operators.types.ts +67 -0
  122. package/src/operators/operators.utils.ts +169 -0
  123. package/src/persistence/persistence.ts +168 -0
  124. package/src/persistence/serializer.ts +123 -0
  125. package/src/persistence/snapshot.ts +76 -0
  126. package/src/persistence/tabs.ts +86 -0
  127. package/src/query/infinite-query.ts +206 -0
  128. package/src/query/live-query.ts +552 -0
  129. package/src/query/planner.ts +199 -0
  130. package/src/query/query.ts +319 -0
  131. package/src/query/query.types.ts +90 -0
  132. package/src/schema/schema.types.ts +29 -0
  133. package/src/store/store.ts +300 -0
  134. package/src/store/store.types.ts +17 -0
  135. package/src/subset/base-subset.ts +169 -0
  136. package/src/subset/key-subset.ts +44 -0
  137. package/src/subset/list-subset.ts +328 -0
  138. package/src/sync/sync.ts +99 -0
  139. package/src/utils/request.utils.ts +67 -0
  140. package/tsconfig.json +12 -0
  141. package/vite.config.ts +71 -0
@@ -0,0 +1,300 @@
1
+ import type { RowKey } from "../collection/collection.types";
2
+ import { compareValues, isEqualValue } from "../operators/operators.utils";
3
+ import type { FieldMeta, Layer, Row, Stamp } from "./store.types";
4
+
5
+ /**
6
+ * Holds one collection's rows. Server rows and optimistic layers are kept apart: queries read the server row with
7
+ * every pending layer applied on top, and dropping a layer reverts exactly what it changed.
8
+ *
9
+ * Writes are ordered per field. A field keeps its value when the write is older than the one that set it: an older
10
+ * `version`, or a response to a request sent before the field was written.
11
+ */
12
+ export class Store {
13
+ private rows = new Map<RowKey, Row>();
14
+ private meta = new Map<RowKey, Map<string, FieldMeta>>();
15
+ private tombstones = new Map<RowKey, { seq: number; wall: number }>();
16
+ private layers: Layer[] = [];
17
+ private visible = new Map<RowKey, Row | undefined>();
18
+ private arrival = new Map<RowKey, number>();
19
+ private arrivalCounter = 0;
20
+ /** Stores of linked collections, which hold some of this store's fields for the same keys */
21
+ private links: Store[] = [];
22
+
23
+ constructor(
24
+ private readonly options: {
25
+ keyField: string;
26
+ versionField?: string;
27
+ onChange: (key: RowKey) => void;
28
+ },
29
+ ) {}
30
+
31
+ /** Whether the server state holds the row */
32
+ hasServerRow = (key: RowKey) => this.rows.has(key);
33
+
34
+ /** The pending optimistic layers, oldest first */
35
+ getLayers = (): readonly Layer[] => this.layers;
36
+
37
+ /** The server row, without optimistic layers */
38
+ getServerRow = (key: RowKey) => this.rows.get(key);
39
+
40
+ /** The newest `seq` that wrote any field of a server row, or 0 */
41
+ getLastSeq = (key: RowKey): number => {
42
+ const fields = this.meta.get(key);
43
+ return fields ? Math.max(0, ...[...fields.values()].map((meta) => meta.seq)) : 0;
44
+ };
45
+
46
+ /** Every key with a server row */
47
+ getServerKeys = () => [...this.rows.keys()];
48
+
49
+ /** The row as queries see it: the server row with every pending layer applied */
50
+ get = (key: RowKey): Row | undefined => {
51
+ if (this.visible.has(key)) {
52
+ return this.visible.get(key);
53
+ }
54
+ let row = this.rows.get(key);
55
+ for (const layer of this.layers) {
56
+ if (layer.key !== key) {
57
+ continue;
58
+ }
59
+ if (layer.type === "insert") {
60
+ row = { ...layer.values };
61
+ } else if (layer.type === "update") {
62
+ row = row ? { ...row, ...layer.values } : undefined;
63
+ } else {
64
+ row = undefined;
65
+ }
66
+ }
67
+ const visible = row && row !== this.rows.get(key) ? Object.freeze(row) : row;
68
+ this.visible.set(key, visible);
69
+ return visible;
70
+ };
71
+
72
+ /** Every key queries can see */
73
+ keys = (): RowKey[] => {
74
+ const keys = new Set<RowKey>(this.rows.keys());
75
+ this.layers.forEach((layer) => keys.add(layer.key));
76
+ return [...keys].filter((key) => this.get(key) !== undefined);
77
+ };
78
+
79
+ /** The order in which the db first saw a row, used when a query has no `orderBy` */
80
+ getArrival = (key: RowKey) => this.arrival.get(key)!;
81
+
82
+ /** Whether a pending write touches the row */
83
+ hasLayer = (key: RowKey) => this.layers.some((layer) => layer.key === key);
84
+
85
+ /**
86
+ * Writes server fields. A complete write creates the row or replaces its fields, a partial write changes only the
87
+ * fields it carries and is ignored for a row the store does not hold. Returns whether the row changed.
88
+ */
89
+ /** Links another store: writes, deletes and layers on one change the fields the other has, for the same key */
90
+ link = (store: Store) => {
91
+ this.links.push(store);
92
+ };
93
+
94
+ write = (
95
+ key: RowKey,
96
+ written: Row,
97
+ { complete, stamp, linked = true }: { complete: boolean; stamp: Stamp; linked?: boolean },
98
+ ): boolean => {
99
+ // `undefined` is not a value: an update leaves the field as it is, and a complete row leaves it out, which drops it
100
+ const values = Object.fromEntries(Object.entries(written).filter(([, value]) => value !== undefined));
101
+ const tombstone = this.tombstones.get(key);
102
+ if (tombstone) {
103
+ if (stamp.seq < tombstone.seq) {
104
+ return false;
105
+ }
106
+ this.tombstones.delete(key);
107
+ }
108
+
109
+ const current = this.rows.get(key);
110
+ if (!current && !complete) {
111
+ return false;
112
+ }
113
+
114
+ const fieldsMeta = this.meta.get(key) ?? new Map<string, FieldMeta>();
115
+ const { versionField } = this.options;
116
+ const incomingVersion = versionField ? values[versionField] : undefined;
117
+ const hasVersion = incomingVersion !== undefined;
118
+ const next: Row = current ? { ...current } : {};
119
+ const accepted: Row = {};
120
+ let changed = !current;
121
+
122
+ Object.keys(values).forEach((field) => {
123
+ const meta = fieldsMeta.get(field);
124
+ if (!this.accepts(meta, stamp, hasVersion ? incomingVersion : undefined)) {
125
+ return;
126
+ }
127
+ fieldsMeta.set(field, {
128
+ seq: stamp.seq,
129
+ wall: stamp.wall,
130
+ version: hasVersion ? incomingVersion : meta?.version,
131
+ });
132
+ accepted[field] = values[field];
133
+ if (!current || !isEqualValue(current[field], values[field])) {
134
+ next[field] = values[field];
135
+ changed = true;
136
+ }
137
+ });
138
+
139
+ // A complete row replaces the stored one, so a field it leaves out is gone, unless a newer write set it
140
+ if (complete && current) {
141
+ Object.keys(current).forEach((field) => {
142
+ if (field in values || !this.accepts(fieldsMeta.get(field), stamp, hasVersion ? incomingVersion : undefined)) {
143
+ return;
144
+ }
145
+ fieldsMeta.set(field, { seq: stamp.seq, wall: stamp.wall, version: hasVersion ? incomingVersion : undefined });
146
+ delete next[field];
147
+ changed = true;
148
+ });
149
+ }
150
+
151
+ this.meta.set(key, fieldsMeta);
152
+ if (!this.arrival.has(key)) {
153
+ this.arrivalCounter += 1;
154
+ this.arrival.set(key, this.arrivalCounter);
155
+ }
156
+ if (changed) {
157
+ // Rows are shared with every query and component, so changing one in place must fail rather than corrupt them
158
+ this.rows.set(key, Object.freeze(next));
159
+ this.invalidate(key);
160
+ }
161
+ if (linked) {
162
+ this.links.forEach((store) => store.mirrorWrite(key, accepted, stamp));
163
+ }
164
+ return changed;
165
+ };
166
+
167
+ /** Removes a row the server deleted, and remembers the key so an older response cannot bring it back */
168
+ remove = (key: RowKey, stamp: Stamp, linked = true): boolean => {
169
+ // The newest delete wins, so an older "not found" never lets a response sent before a newer delete bring it back
170
+ const tombstone = this.tombstones.get(key);
171
+ if (!tombstone || tombstone.seq < stamp.seq) {
172
+ this.tombstones.set(key, { seq: stamp.seq, wall: stamp.wall });
173
+ }
174
+ if (linked) {
175
+ this.links.forEach((store) => store.remove(key, stamp, false));
176
+ }
177
+ // A row written after the delete, such as an insert event after an older "not found", stays
178
+ if (this.getLastSeq(key) > stamp.seq) {
179
+ return false;
180
+ }
181
+ return this.drop(key);
182
+ };
183
+
184
+ /** Removes a row without remembering it, for rows no subset holds any more */
185
+ drop = (key: RowKey): boolean => {
186
+ if (!this.rows.has(key)) {
187
+ return false;
188
+ }
189
+ this.rows.delete(key);
190
+ this.meta.delete(key);
191
+ this.invalidate(key);
192
+ return true;
193
+ };
194
+
195
+ /** Forgets deleted keys once every request sent before the delete has settled */
196
+ forgetTombstones = (oldestPendingSeq: number) => {
197
+ this.tombstones.forEach((tombstone, key) => {
198
+ if (tombstone.seq < oldestPendingSeq) {
199
+ this.tombstones.delete(key);
200
+ }
201
+ });
202
+ };
203
+
204
+ addLayer = (layer: Layer, linked = true) => {
205
+ if (linked) {
206
+ this.links.forEach((store) => store.mirrorLayer(layer));
207
+ }
208
+ this.layers.push(layer);
209
+ if (!this.arrival.has(layer.key)) {
210
+ this.arrivalCounter += 1;
211
+ this.arrival.set(layer.key, this.arrivalCounter);
212
+ }
213
+ this.invalidate(layer.key);
214
+ };
215
+
216
+ removeLayer = (id: string, linked = true) => {
217
+ if (linked) {
218
+ this.links.forEach((store) => store.removeLayer(`${id}@link`, false));
219
+ }
220
+ const layer = this.layers.find((item) => item.id === id);
221
+ if (!layer) {
222
+ return;
223
+ }
224
+ this.layers = this.layers.filter((item) => item.id !== id);
225
+ this.invalidate(layer.key);
226
+ };
227
+
228
+ /** Moves the pending layers of a temporary key to the key the server assigned */
229
+ rekeyLayers = (from: RowKey, to: RowKey) => {
230
+ // The row keeps its place in lists without an order, when it had one
231
+ if (this.arrival.has(from)) {
232
+ this.arrival.set(to, this.arrival.get(from)!);
233
+ }
234
+ this.layers = this.layers.map((layer) => {
235
+ if (layer.key !== from) {
236
+ return layer;
237
+ }
238
+ return { ...layer, key: to, values: { ...layer.values, [this.options.keyField]: to } };
239
+ });
240
+ this.invalidate(from);
241
+ this.invalidate(to);
242
+ };
243
+
244
+ /** Removes every row, layer and tombstone */
245
+ clear = () => {
246
+ const keys = new Set<RowKey>([...this.rows.keys(), ...this.layers.map((layer) => layer.key)]);
247
+ this.rows.clear();
248
+ this.meta.clear();
249
+ this.tombstones.clear();
250
+ this.layers = [];
251
+ keys.forEach((key) => this.invalidate(key));
252
+ };
253
+
254
+ /** The fields a linked store wrote, limited to the fields this store's row has. Rows it does not hold stay away. */
255
+ /** The fields of a row this store also has, by its server row, which a pending delete layer does not hide */
256
+ private pickLinked = (key: RowKey, values: Row): Row | undefined => {
257
+ const row = this.rows.get(key) ?? this.get(key);
258
+ if (!row) {
259
+ return undefined;
260
+ }
261
+ return Object.fromEntries(Object.entries(values).filter(([field]) => field in row));
262
+ };
263
+
264
+ private mirrorWrite = (key: RowKey, values: Row, stamp: Stamp) => {
265
+ if (!this.rows.has(key)) {
266
+ return;
267
+ }
268
+ this.write(key, this.pickLinked(key, values)!, { complete: false, stamp, linked: false });
269
+ };
270
+
271
+ /** Mirrors an update or delete layer. An insert cannot make a complete row of another shape, so it stays away. */
272
+ private mirrorLayer = (layer: Layer) => {
273
+ const values = this.pickLinked(layer.key, layer.values);
274
+ if (!values || layer.type === "insert") {
275
+ return;
276
+ }
277
+ this.addLayer({ ...layer, id: `${layer.id}@link`, values }, false);
278
+ };
279
+
280
+ private accepts = (meta: FieldMeta | undefined, stamp: Stamp, version: unknown): boolean => {
281
+ if (version !== undefined) {
282
+ if (meta?.version === undefined) {
283
+ return true;
284
+ }
285
+ const order = compareValues(meta.version, version);
286
+ // An equal version says nothing about which write is newer, so the one made later wins
287
+ return order < 0 || (order === 0 && meta.seq <= stamp.seq);
288
+ }
289
+ // Events count from when they arrived, so one applied late, after a buffer, never beats a newer write
290
+ if (!meta) {
291
+ return true;
292
+ }
293
+ return meta.seq < stamp.seq;
294
+ };
295
+
296
+ private invalidate = (key: RowKey) => {
297
+ this.visible.delete(key);
298
+ this.options.onChange(key);
299
+ };
300
+ }
@@ -0,0 +1,17 @@
1
+ import type { RowKey } from "../collection/collection.types";
2
+
3
+ export type Row = Record<string, unknown>;
4
+
5
+ /**
6
+ * When a write happened, for ordering:
7
+ * - `sent`: a response to a request; `seq` and `wall` are when it was sent, also for ingested requests sent elsewhere
8
+ * - `now`: a socket event or a mutation result that is newer than anything before it
9
+ *
10
+ * Every stamp's `seq` comes from one counter, so writes are ordered exactly, even within one millisecond.
11
+ */
12
+ export type Stamp = { kind: "sent" | "now"; seq: number; wall: number };
13
+
14
+ export type FieldMeta = { seq: number; wall: number; version?: unknown };
15
+
16
+ /** One pending optimistic write */
17
+ export type Layer = { id: string; key: RowKey; type: "insert" | "update" | "delete"; values: Row };
@@ -0,0 +1,169 @@
1
+ import type { LoaderConfig, RowKey } from "../collection/collection.types";
2
+ import type { CollectionRuntime } from "../db/collection.runtime";
3
+ import type { SyncSubscription } from "../sync/sync";
4
+
5
+ /** A query attached to a subset, told when the subset's status or rows change */
6
+ export type SubsetObserver = { onSubsetChange: () => void };
7
+
8
+ const getStaleTime = (loader: LoaderConfig) => loader.request.staleTime;
9
+
10
+ /** What every loaded subset shares: who uses it, its load status, freshness and garbage collection */
11
+ export type LoadOptions = {
12
+ /**
13
+ * Whether the load waits for the collection's writes in flight, so its response is never older than them. A write's
14
+ * own `onSuccess: "refetch"` does not wait, because the writes queued behind it wait for that refetch.
15
+ */
16
+ waitForWrites?: boolean;
17
+ };
18
+
19
+ export abstract class BaseSubset {
20
+ hasLoaded = false;
21
+ isLoading = false;
22
+ error: unknown = null;
23
+ loadedAt = 0;
24
+ /** Set when events may have been missed, so only a load makes the subset fresh again */
25
+ invalidated = false;
26
+ subscriptions: SyncSubscription[] = [];
27
+ protected observers = new Set<SubsetObserver>();
28
+ protected pending: Promise<void> | undefined;
29
+ private gcTimer: ReturnType<typeof setTimeout> | undefined;
30
+
31
+ constructor(
32
+ readonly collection: CollectionRuntime,
33
+ readonly loader: LoaderConfig,
34
+ ) {}
35
+
36
+ /** Whether a query is attached */
37
+ isUsed = () => this.observers.size > 0;
38
+
39
+ /** How many queries read the subset */
40
+ get observerCount() {
41
+ return this.observers.size;
42
+ }
43
+
44
+ attach = (observer: SubsetObserver) => {
45
+ if (this.gcTimer) {
46
+ clearTimeout(this.gcTimer);
47
+ this.gcTimer = undefined;
48
+ }
49
+ this.observers.add(observer);
50
+ if (this.observers.size === 1 && this.subscriptions.length === 0) {
51
+ this.subscriptions = this.collection.subscribeSyncs(this);
52
+ }
53
+ };
54
+
55
+ detach = (observer: SubsetObserver) => {
56
+ this.observers.delete(observer);
57
+ if (this.observers.size > 0) {
58
+ return;
59
+ }
60
+ this.gcTimer = setTimeout(() => this.dispose(), this.collection.db.gcTime);
61
+ };
62
+
63
+ /** The values that pick a sync's subscription for the subset, by field */
64
+ abstract getEqValues: () => Record<string, unknown>;
65
+
66
+ /**
67
+ * Moves the subset to the sync subscriptions its values pick now, for example when the row a key subset holds moved
68
+ * to another team, and leaves the ones it no longer needs.
69
+ */
70
+ refreshSyncs = () => {
71
+ if (!this.isUsed()) {
72
+ return;
73
+ }
74
+ const next = this.collection.subscribeSyncs(this);
75
+ this.subscriptions.filter((subscription) => !next.includes(subscription)).forEach((item) => item.removeUser(this));
76
+ this.subscriptions = next;
77
+ };
78
+
79
+ /** Stops the garbage collection timer, for `destroy` */
80
+ cancelGc = () => {
81
+ clearTimeout(this.gcTimer);
82
+ this.gcTimer = undefined;
83
+ };
84
+
85
+ /** Releases the subset: stops its syncs and removes the rows nothing else holds */
86
+ dispose = () => {
87
+ this.gcTimer = undefined;
88
+ this.subscriptions.forEach((subscription) => subscription.removeUser(this));
89
+ this.subscriptions = [];
90
+ this.collection.removeSubset(this);
91
+ };
92
+
93
+ /** Whether syncs deliver every insert, update and delete for the subset */
94
+ isLive = (): boolean => {
95
+ const types = new Set(
96
+ this.subscriptions.filter((subscription) => subscription.isLive()).map((item) => item.sync.type),
97
+ );
98
+ return types.has("changes") || (types.has("insert") && types.has("update") && types.has("delete"));
99
+ };
100
+
101
+ isFresh = (): boolean => {
102
+ if (!this.hasLoaded || this.invalidated) {
103
+ return false;
104
+ }
105
+ if (this.isLive()) {
106
+ return true;
107
+ }
108
+ return this.loadedAt > 0 && Date.now() - this.loadedAt < getStaleTime(this.loader);
109
+ };
110
+
111
+ /** Marks the subset stale, for example after a reconnect that may have missed events */
112
+ invalidate = () => {
113
+ this.invalidated = true;
114
+ this.notify();
115
+ };
116
+
117
+ notify = () => {
118
+ this.observers.forEach((observer) => observer.onSubsetChange());
119
+ };
120
+
121
+ /** Whether the load in flight loads the whole subset, rather than its next page */
122
+ protected pendingIsFull = true;
123
+
124
+ /** Loads the subset unless a load of the whole subset is in flight. One asked during a next page runs after it. */
125
+ load = (options: LoadOptions = {}): Promise<void> => {
126
+ if (this.pending && !this.pendingIsFull) {
127
+ return this.pending.then(() => this.load(options));
128
+ }
129
+ if (!this.pending) {
130
+ this.pendingIsFull = true;
131
+ const pending: Promise<void> = this.run(options).finally(() => {
132
+ // A next page may have started meanwhile, and it is the load in flight now
133
+ if (this.pending === pending) {
134
+ this.pending = undefined;
135
+ }
136
+ });
137
+ this.pending = pending;
138
+ }
139
+ return this.pending;
140
+ };
141
+
142
+ /** Loads again after the load in flight, so the result is newer than anything sent before */
143
+ reload = async (options: LoadOptions = {}): Promise<void> => {
144
+ await this.pending;
145
+ return this.load(options);
146
+ };
147
+
148
+ /** Refetches when the subset is stale and no load is in flight */
149
+ revalidate = () => {
150
+ if (!this.isLoading && !this.isFresh()) {
151
+ this.load();
152
+ }
153
+ };
154
+
155
+ abstract holds: (key: RowKey) => boolean;
156
+
157
+ protected abstract run: (options: LoadOptions) => Promise<void>;
158
+
159
+ protected beginLoad = () => {
160
+ this.isLoading = true;
161
+ this.subscriptions.forEach((subscription) => subscription.beginLoad(this));
162
+ this.notify();
163
+ };
164
+
165
+ protected endLoad = () => {
166
+ this.isLoading = false;
167
+ this.subscriptions.forEach((subscription) => subscription.endLoad(this));
168
+ };
169
+ }
@@ -0,0 +1,44 @@
1
+ import type { LoaderConfig, RowKey } from "../collection/collection.types";
2
+ import type { CollectionRuntime } from "../db/collection.runtime";
3
+ import type { Stamp } from "../store/store.types";
4
+ import type { LoadOptions } from "./base-subset";
5
+ import { BaseSubset } from "./base-subset";
6
+
7
+ /** One row read by key, for `findOne`. Keys read in the same tick are batched when the loader has `byKeys`. */
8
+ export class KeySubset extends BaseSubset {
9
+ constructor(
10
+ collection: CollectionRuntime,
11
+ loader: LoaderConfig,
12
+ readonly key: RowKey,
13
+ ) {
14
+ super(collection, loader);
15
+ }
16
+
17
+ holds = (key: RowKey) => key === this.key;
18
+
19
+ /** The fields of the row the server sent, so syncs scoped by those fields keep it live */
20
+ getEqValues = (): Record<string, unknown> => this.collection.store.getServerRow(this.key) ?? {};
21
+
22
+ /** Called by the collection when the batched request for this key settled */
23
+ complete = (result: { success: true; found: boolean; stamp: Stamp } | { success: false; error: unknown }) => {
24
+ if (result.success) {
25
+ // The server answered for this key, so a row it did not return is gone, and older events cannot bring it back
26
+ if (!result.found) {
27
+ this.collection.store.remove(this.key, result.stamp);
28
+ }
29
+ this.hasLoaded = true;
30
+ this.loadedAt = Date.now();
31
+ this.invalidated = false;
32
+ this.error = null;
33
+ } else {
34
+ this.error = result.error;
35
+ }
36
+ this.endLoad();
37
+ this.collection.markSubsetChanged(this);
38
+ };
39
+
40
+ protected run = async (options: LoadOptions) => {
41
+ this.beginLoad();
42
+ await this.collection.loadKey(this, options.waitForWrites !== false);
43
+ };
44
+ }