@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,393 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Behaviour cases ported from the suites of Apollo Client, urql Graphcache, Relay, Replicache, RxDB, Dexie, PowerSync
|
|
3
|
+
* and Electric: pending writes rebased over server changes, concurrent optimistic layers, one emission per batch,
|
|
4
|
+
* unusual keys, and offline refreshes.
|
|
5
|
+
*/
|
|
6
|
+
import { collection, createDb, eq, rowType } from "@hyper-fetch/db";
|
|
7
|
+
import type { DbErrorEvent, DbOptions } from "@hyper-fetch/db";
|
|
8
|
+
import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
9
|
+
|
|
10
|
+
import type { Post } from "../utils/fixtures";
|
|
11
|
+
import { createApi, createHttpClient, createPost, createRequests, deferred, flush } from "../utils/fixtures";
|
|
12
|
+
|
|
13
|
+
const { server, startServer, stopServer, resetMocks } = createHttpMockingServer();
|
|
14
|
+
|
|
15
|
+
const byTeam = { teamId: { eq: (teamId: number) => ({ params: { teamId } }), required: true as const } };
|
|
16
|
+
|
|
17
|
+
type Author = { id: number; name: string };
|
|
18
|
+
|
|
19
|
+
const setup = (options: DbOptions = {}) => {
|
|
20
|
+
const client = createHttpClient();
|
|
21
|
+
const requests = createRequests(client);
|
|
22
|
+
const saveAuthor = client.createRequest<{ response: Author }>()({ endpoint: "/authors/:id", method: "PUT" });
|
|
23
|
+
const removeAuthor = client.createRequest<{ response: null }>()({ endpoint: "/authors/:id", method: "DELETE" });
|
|
24
|
+
const post = collection(rowType<Post>(), { key: "id" })
|
|
25
|
+
.load(requests.getTeamFullPosts, { rows: (response) => response.items, where: byTeam })
|
|
26
|
+
// Stands in for a sync event: a response of another request, written as the server's newest state
|
|
27
|
+
.ingest(requests.searchPosts, { type: "update", rows: (response) => response.results })
|
|
28
|
+
.mutate({
|
|
29
|
+
insert: { request: requests.createPostRequest, map: (row) => ({ payload: row }) },
|
|
30
|
+
update: {
|
|
31
|
+
request: requests.updatePostRequest,
|
|
32
|
+
map: (key, changes) => ({ params: { postId: key }, payload: changes }),
|
|
33
|
+
},
|
|
34
|
+
delete: { request: requests.deletePostRequest, map: (key) => ({ params: { postId: key } }), onSuccess: "keep" },
|
|
35
|
+
});
|
|
36
|
+
const author = collection(rowType<Author>(), { key: "id" })
|
|
37
|
+
.ingest(saveAuthor)
|
|
38
|
+
.mutate({ delete: { request: removeAuthor, map: (id) => ({ params: { id } }), onSuccess: "keep" } });
|
|
39
|
+
const db = createDb({ post, author }, options);
|
|
40
|
+
const errors: DbErrorEvent[] = [];
|
|
41
|
+
db.onError((event) => errors.push(event));
|
|
42
|
+
const pushServerChange = (rows: Partial<Post>[]) => {
|
|
43
|
+
createApi(server).get("/search", () => ({ data: { results: rows } }));
|
|
44
|
+
return requests.searchPosts.send();
|
|
45
|
+
};
|
|
46
|
+
return { api: createApi(server), client, db, errors, pushServerChange, saveAuthor };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const titles = (posts: Post[] | undefined) => posts?.map((post) => post.title);
|
|
50
|
+
|
|
51
|
+
describe("db [ Cases from other client data libraries ]", () => {
|
|
52
|
+
beforeAll(() => startServer());
|
|
53
|
+
beforeEach(() => resetMocks());
|
|
54
|
+
afterAll(() => stopServer());
|
|
55
|
+
|
|
56
|
+
const loadTeam = async (context: ReturnType<typeof setup>, posts = [createPost(1), createPost(2)]) => {
|
|
57
|
+
context.api.get("/teams/:teamId/full-posts", () => ({ data: { items: posts } }));
|
|
58
|
+
const query = context.db.post.where((post) => eq(post.teamId, 1)).orderBy((post) => post.id);
|
|
59
|
+
const unsubscribe = query.subscribe(() => {});
|
|
60
|
+
await vi.waitFor(() => expect(query.getSnapshot().status).toBe("ready"));
|
|
61
|
+
return { query, unsubscribe };
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
describe("pending writes over server changes", () => {
|
|
65
|
+
it("shows the server's newer value when a pending update to the same field fails (Dexie #1823)", async () => {
|
|
66
|
+
const context = setup();
|
|
67
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
68
|
+
const release = deferred();
|
|
69
|
+
context.api.patch("/posts/:postId", async () => {
|
|
70
|
+
await release.promise;
|
|
71
|
+
return { status: 400, data: { message: "No" } };
|
|
72
|
+
});
|
|
73
|
+
const write = context.db.post.update(1, { title: "Mine" });
|
|
74
|
+
await context.pushServerChange([{ id: 1, title: "Theirs" }]);
|
|
75
|
+
expect(titles(query.getSnapshot().data)?.[0]).toBe("Mine");
|
|
76
|
+
release.resolve();
|
|
77
|
+
await write;
|
|
78
|
+
expect(titles(query.getSnapshot().data)?.[0]).toBe("Theirs");
|
|
79
|
+
unsubscribe();
|
|
80
|
+
context.db.destroy();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("shows both a pending field and a server change to another field (RxDB)", async () => {
|
|
84
|
+
const context = setup();
|
|
85
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
86
|
+
const release = deferred();
|
|
87
|
+
context.api.patch("/posts/:postId", async ({ params, body }) => {
|
|
88
|
+
await release.promise;
|
|
89
|
+
return { data: createPost(Number(params.postId), { ...(body as Partial<Post>), likes: 99 }) };
|
|
90
|
+
});
|
|
91
|
+
const write = context.db.post.update(1, { title: "Mine" });
|
|
92
|
+
await context.pushServerChange([{ id: 1, likes: 50 }]);
|
|
93
|
+
expect(query.getSnapshot().data?.[0]).toMatchObject({ title: "Mine", likes: 50 });
|
|
94
|
+
release.resolve();
|
|
95
|
+
await write;
|
|
96
|
+
expect(query.getSnapshot().data?.[0]).toMatchObject({ title: "Mine", likes: 99 });
|
|
97
|
+
unsubscribe();
|
|
98
|
+
context.db.destroy();
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("brings a row back with the server's change when a pending delete fails", async () => {
|
|
102
|
+
const context = setup();
|
|
103
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
104
|
+
const release = deferred();
|
|
105
|
+
context.api.delete("/posts/:postId", async () => {
|
|
106
|
+
await release.promise;
|
|
107
|
+
return { status: 409, data: { message: "Locked" } };
|
|
108
|
+
});
|
|
109
|
+
const write = context.db.post.delete(1);
|
|
110
|
+
await context.pushServerChange([{ id: 1, title: "Edited meanwhile" }]);
|
|
111
|
+
expect(query.getSnapshot().data?.map((post) => post.id)).toStrictEqual([2]);
|
|
112
|
+
release.resolve();
|
|
113
|
+
await write;
|
|
114
|
+
expect(titles(query.getSnapshot().data)).toStrictEqual(["Edited meanwhile", "Post 2"]);
|
|
115
|
+
unsubscribe();
|
|
116
|
+
context.db.destroy();
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("keeps a second pending write on top when the first write's response lands (Apollo, RxDB)", async () => {
|
|
120
|
+
const context = setup();
|
|
121
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
122
|
+
const releases = [deferred(), deferred()];
|
|
123
|
+
let call = 0;
|
|
124
|
+
context.api.patch("/posts/:postId", async ({ params, body }) => {
|
|
125
|
+
const release = releases[call];
|
|
126
|
+
call += 1;
|
|
127
|
+
await release.promise;
|
|
128
|
+
return { data: createPost(Number(params.postId), body as Partial<Post>) };
|
|
129
|
+
});
|
|
130
|
+
const first = context.db.post.update(1, { title: "First" });
|
|
131
|
+
const second = context.db.post.update(1, { title: "Second" });
|
|
132
|
+
releases[0].resolve();
|
|
133
|
+
await first;
|
|
134
|
+
expect(titles(query.getSnapshot().data)?.[0]).toBe("Second");
|
|
135
|
+
releases[1].resolve();
|
|
136
|
+
await second;
|
|
137
|
+
expect(titles(query.getSnapshot().data)?.[0]).toBe("Second");
|
|
138
|
+
unsubscribe();
|
|
139
|
+
context.db.destroy();
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it("keeps a row a pending update touches when a delete event removes it, and does not bring it back (Apollo)", async () => {
|
|
143
|
+
const context = setup();
|
|
144
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
145
|
+
const release = deferred();
|
|
146
|
+
context.api.patch("/posts/:postId", async () => {
|
|
147
|
+
await release.promise;
|
|
148
|
+
return { data: null };
|
|
149
|
+
});
|
|
150
|
+
context.api.delete("/posts/:postId", () => ({ data: null }));
|
|
151
|
+
const update = context.db.post.update(1, { title: "Mine" });
|
|
152
|
+
// The delete waits behind the update on the same row, so it lands after it
|
|
153
|
+
const remove = context.db.post.delete(1);
|
|
154
|
+
release.resolve();
|
|
155
|
+
await Promise.all([update, remove]);
|
|
156
|
+
expect(query.getSnapshot().data?.map((post) => post.id)).toStrictEqual([2]);
|
|
157
|
+
unsubscribe();
|
|
158
|
+
context.db.destroy();
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
describe("concurrent optimistic writes", () => {
|
|
163
|
+
it("removes only the insert that failed, out of two in one list (Apollo)", async () => {
|
|
164
|
+
const context = setup();
|
|
165
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
166
|
+
context.api.post("/posts", ({ body }) =>
|
|
167
|
+
(body as Post).id === 3 ? { status: 400, data: { message: "No" } } : { data: body },
|
|
168
|
+
);
|
|
169
|
+
const [failed, kept] = await Promise.all([
|
|
170
|
+
context.db.post.insert(createPost(3)),
|
|
171
|
+
context.db.post.insert(createPost(4)),
|
|
172
|
+
]);
|
|
173
|
+
expect([failed.success, kept.success]).toStrictEqual([false, true]);
|
|
174
|
+
expect(query.getSnapshot().data?.map((post) => post.id)).toStrictEqual([1, 2, 4]);
|
|
175
|
+
unsubscribe();
|
|
176
|
+
context.db.destroy();
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it("shows every intermediate state when responses come back in reverse order (Apollo)", async () => {
|
|
180
|
+
const context = setup();
|
|
181
|
+
const { query, unsubscribe } = await loadTeam(context, [createPost(1), createPost(2), createPost(3)]);
|
|
182
|
+
const releases = new Map<string, { resolve: () => void }>();
|
|
183
|
+
context.api.patch("/posts/:postId", async ({ params, body }) => {
|
|
184
|
+
const release = deferred();
|
|
185
|
+
releases.set(params.postId, release);
|
|
186
|
+
await release.promise;
|
|
187
|
+
return { data: createPost(Number(params.postId), body as Partial<Post>) };
|
|
188
|
+
});
|
|
189
|
+
const frames: (string[] | undefined)[] = [];
|
|
190
|
+
const stop = query.subscribe(() => frames.push(titles(query.getSnapshot().data)));
|
|
191
|
+
const writes = [1, 2, 3].map((id) => context.db.post.update(id, { title: `T${id}` }));
|
|
192
|
+
await vi.waitFor(() => expect(releases.size).toBe(3));
|
|
193
|
+
frames.length = 0;
|
|
194
|
+
for (const id of ["3", "2", "1"]) {
|
|
195
|
+
releases.get(id)!.resolve();
|
|
196
|
+
// oxlint-disable-next-line no-await-in-loop -- each response lands before the next is released
|
|
197
|
+
await writes[Number(id) - 1];
|
|
198
|
+
}
|
|
199
|
+
expect(frames.every((frame) => frame?.join(",") === "T1,T2,T3")).toBeTrue();
|
|
200
|
+
stop();
|
|
201
|
+
unsubscribe();
|
|
202
|
+
context.db.destroy();
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("gives the same write made twice two layers that revert on their own (urql)", async () => {
|
|
206
|
+
const context = setup();
|
|
207
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
208
|
+
let call = 0;
|
|
209
|
+
context.api.patch("/posts/:postId", ({ params, body }) => {
|
|
210
|
+
call += 1;
|
|
211
|
+
return call === 1
|
|
212
|
+
? { status: 400, data: { message: "No" } }
|
|
213
|
+
: { data: createPost(Number(params.postId), body as Partial<Post>) };
|
|
214
|
+
});
|
|
215
|
+
const results = await Promise.all([
|
|
216
|
+
context.db.post.update(1, { title: "Same" }),
|
|
217
|
+
context.db.post.update(1, { title: "Same" }),
|
|
218
|
+
]);
|
|
219
|
+
expect(results.map((result) => result.success)).toStrictEqual([false, false]);
|
|
220
|
+
expect(titles(query.getSnapshot().data)?.[0]).toBe("Post 1");
|
|
221
|
+
expect(await context.db.post.update(1, { title: "Same" })).toMatchObject({ success: true });
|
|
222
|
+
expect(titles(query.getSnapshot().data)?.[0]).toBe("Same");
|
|
223
|
+
unsubscribe();
|
|
224
|
+
context.db.destroy();
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
describe("emissions", () => {
|
|
229
|
+
it("emits once for a transaction of several writes and once for its revert (Dexie)", async () => {
|
|
230
|
+
const context = setup();
|
|
231
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
232
|
+
context.api.patch("/posts/:postId", () => ({ status: 400, data: { message: "No" } }));
|
|
233
|
+
const listener = vi.fn();
|
|
234
|
+
const stop = query.subscribe(listener);
|
|
235
|
+
const write = context.db.transaction((tx) => {
|
|
236
|
+
tx.post.update(1, { title: "A" });
|
|
237
|
+
tx.post.update(2, { title: "B" });
|
|
238
|
+
});
|
|
239
|
+
expect(listener).toHaveBeenCalledTimes(1);
|
|
240
|
+
await write;
|
|
241
|
+
await flush();
|
|
242
|
+
expect(titles(query.getSnapshot().data)).toStrictEqual(["Post 1", "Post 2"]);
|
|
243
|
+
expect(listener.mock.calls.length).toBeLessThanOrEqual(3);
|
|
244
|
+
stop();
|
|
245
|
+
unsubscribe();
|
|
246
|
+
context.db.destroy();
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("does not emit when a row is inserted and removed within one batch (RxDB)", async () => {
|
|
250
|
+
const context = setup();
|
|
251
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
252
|
+
context.api.post("/posts", async () => {
|
|
253
|
+
await new Promise(() => {});
|
|
254
|
+
return { data: null };
|
|
255
|
+
});
|
|
256
|
+
const listener = vi.fn();
|
|
257
|
+
const stop = query.subscribe(listener);
|
|
258
|
+
const before = query.getSnapshot().data;
|
|
259
|
+
await context.db.transaction((tx) => {
|
|
260
|
+
tx.post.update(2, { title: "Post 2" });
|
|
261
|
+
});
|
|
262
|
+
expect(query.getSnapshot().data).toEqual(before);
|
|
263
|
+
stop();
|
|
264
|
+
unsubscribe();
|
|
265
|
+
context.db.destroy();
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
it("lets listeners subscribe and unsubscribe while they are notified (Electric)", async () => {
|
|
269
|
+
const context = setup();
|
|
270
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
271
|
+
context.api.patch("/posts/:postId", ({ params, body }) => ({
|
|
272
|
+
data: createPost(Number(params.postId), body as Partial<Post>),
|
|
273
|
+
}));
|
|
274
|
+
const late = vi.fn();
|
|
275
|
+
let stopLate: (() => void) | undefined;
|
|
276
|
+
const stopFirst = query.subscribe(() => {
|
|
277
|
+
stopFirst();
|
|
278
|
+
stopLate = query.subscribe(late);
|
|
279
|
+
});
|
|
280
|
+
await context.db.post.update(1, { title: "Changed" });
|
|
281
|
+
await context.db.post.update(1, { title: "Again" });
|
|
282
|
+
expect(late).toHaveBeenCalled();
|
|
283
|
+
stopLate?.();
|
|
284
|
+
unsubscribe();
|
|
285
|
+
context.db.destroy();
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it("keeps updating after a write that failed validation (Dexie #2085)", async () => {
|
|
289
|
+
const context = setup();
|
|
290
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
291
|
+
context.api.post("/posts", ({ body }) => ({ data: body }));
|
|
292
|
+
expect(await context.db.post.insert(createPost(1))).toMatchObject({ success: false });
|
|
293
|
+
await context.db.post.insert(createPost(3));
|
|
294
|
+
expect(query.getSnapshot().data?.map((post) => post.id)).toStrictEqual([1, 2, 3]);
|
|
295
|
+
unsubscribe();
|
|
296
|
+
context.db.destroy();
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it("never notifies a listener that left while the load was in flight (Dexie)", async () => {
|
|
300
|
+
const context = setup();
|
|
301
|
+
const release = deferred();
|
|
302
|
+
context.api.get("/teams/:teamId/full-posts", async () => {
|
|
303
|
+
await release.promise;
|
|
304
|
+
return { status: 500, data: { message: "Down" } };
|
|
305
|
+
});
|
|
306
|
+
const listener = vi.fn();
|
|
307
|
+
const query = context.db.post.where((post) => eq(post.teamId, 1));
|
|
308
|
+
const stop = query.subscribe(listener);
|
|
309
|
+
await flush();
|
|
310
|
+
stop();
|
|
311
|
+
listener.mockClear();
|
|
312
|
+
release.resolve();
|
|
313
|
+
await flush();
|
|
314
|
+
expect(listener).not.toHaveBeenCalled();
|
|
315
|
+
context.db.destroy();
|
|
316
|
+
});
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
describe("keys and rows", () => {
|
|
320
|
+
it("handles the keys 0 and empty string like any other (Dexie)", async () => {
|
|
321
|
+
const context = setup();
|
|
322
|
+
context.api.get("/teams/:teamId/full-posts", () => ({ data: { items: [createPost(0)] } }));
|
|
323
|
+
context.api.patch("/posts/:postId", ({ body }) => ({ data: createPost(0, body as Partial<Post>) }));
|
|
324
|
+
context.api.delete("/posts/:postId", () => ({ data: null }));
|
|
325
|
+
const zero = context.db.post.findOne(0);
|
|
326
|
+
const list = context.db.post.where((post) => eq(post.teamId, 1));
|
|
327
|
+
const unsubscribe = list.subscribe(() => {});
|
|
328
|
+
await vi.waitFor(() => expect(list.getSnapshot().data).toHaveLength(1));
|
|
329
|
+
expect(zero.getSnapshot().data?.id).toBe(0);
|
|
330
|
+
await context.db.post.update(0, { title: "Zero" });
|
|
331
|
+
expect(context.db.post.findOne(0).local().getSnapshot().data?.title).toBe("Zero");
|
|
332
|
+
await context.db.post.delete(0);
|
|
333
|
+
expect(list.getSnapshot().data).toStrictEqual([]);
|
|
334
|
+
const authors = context.db.author.findOne("" as unknown as number).local();
|
|
335
|
+
expect(authors.getSnapshot().data).toBeUndefined();
|
|
336
|
+
unsubscribe();
|
|
337
|
+
context.db.destroy();
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
it("is not corrupted by a caller that changes a returned row in place (Dexie, Relay)", async () => {
|
|
341
|
+
const context = setup();
|
|
342
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
343
|
+
const row = query.getSnapshot().data![0];
|
|
344
|
+
try {
|
|
345
|
+
(row as { title: string }).title = "Changed in place";
|
|
346
|
+
} catch {
|
|
347
|
+
// Frozen rows throw in strict mode, which is fine too
|
|
348
|
+
}
|
|
349
|
+
const fresh = context.db.post.where((post) => eq(post.teamId, 2)).local();
|
|
350
|
+
expect(fresh.getSnapshot().data).toStrictEqual([]);
|
|
351
|
+
expect(context.db.post.findOne(1).local().getSnapshot().data?.title).toBe("Post 1");
|
|
352
|
+
unsubscribe();
|
|
353
|
+
context.db.destroy();
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
it("shows undefined for a joined row that is deleted, and drops the result of an inner join (Apollo)", async () => {
|
|
357
|
+
const context = setup();
|
|
358
|
+
const { unsubscribe } = await loadTeam(context, [createPost(1, { likes: 7 })]);
|
|
359
|
+
context.api.put("/authors/:id", ({ params }) => ({ data: { id: Number(params.id), name: "Ada" } }));
|
|
360
|
+
context.api.delete("/authors/:id", () => ({ data: null }));
|
|
361
|
+
await context.saveAuthor.setParams({ id: 7 }).send();
|
|
362
|
+
const left = context.db.post
|
|
363
|
+
.where((post) => eq(post.teamId, 1))
|
|
364
|
+
.join("author", context.db.author, (post) => post.likes);
|
|
365
|
+
const inner = context.db.post
|
|
366
|
+
.where((post) => eq(post.teamId, 1))
|
|
367
|
+
.join("author", context.db.author, { by: (post) => post.likes, type: "inner" });
|
|
368
|
+
const stops = [left.subscribe(() => {}), inner.subscribe(() => {})];
|
|
369
|
+
expect(left.getSnapshot().data?.[0].author?.name).toBe("Ada");
|
|
370
|
+
expect(inner.getSnapshot().data).toHaveLength(1);
|
|
371
|
+
await context.db.author.delete(7);
|
|
372
|
+
expect(left.getSnapshot().data?.[0].author).toBeUndefined();
|
|
373
|
+
expect(inner.getSnapshot().data).toStrictEqual([]);
|
|
374
|
+
stops.forEach((stop) => stop());
|
|
375
|
+
unsubscribe();
|
|
376
|
+
context.db.destroy();
|
|
377
|
+
});
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
describe("offline", () => {
|
|
381
|
+
it("keeps the rows and shows them stale when a refresh fails while offline (urql)", async () => {
|
|
382
|
+
const context = setup();
|
|
383
|
+
const { query, unsubscribe } = await loadTeam(context);
|
|
384
|
+
context.api.get("/teams/:teamId/full-posts", () => ({ status: 0, data: null, networkError: true }));
|
|
385
|
+
await query.refetch();
|
|
386
|
+
expect(query.getSnapshot()).toMatchObject({ status: "ready" });
|
|
387
|
+
expect(query.getSnapshot().data).toHaveLength(2);
|
|
388
|
+
expect(query.getSnapshot().error).toBeTruthy();
|
|
389
|
+
unsubscribe();
|
|
390
|
+
context.db.destroy();
|
|
391
|
+
});
|
|
392
|
+
});
|
|
393
|
+
});
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/* oxlint-disable no-await-in-loop -- the steps of a model run one after another by design */
|
|
2
|
+
/**
|
|
3
|
+
* A model test for races: random optimistic writes, changes made on the server by someone else and refetches, with
|
|
4
|
+
* every response held and released in a random order. Whatever the order, once everything settles the client shows
|
|
5
|
+
* exactly the server's rows, holds no pending layers, and every write resolved. Seeds are fixed, so failures replay.
|
|
6
|
+
*/
|
|
7
|
+
import { collection, createDb, eq, rowType } from "@hyper-fetch/db";
|
|
8
|
+
import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
9
|
+
|
|
10
|
+
import { createApi, createHttpClient, flush } from "../utils/fixtures";
|
|
11
|
+
import { createRandom } from "../utils/random";
|
|
12
|
+
|
|
13
|
+
const { server, startServer, stopServer, resetMocks } = createHttpMockingServer();
|
|
14
|
+
|
|
15
|
+
type Item = { id: number; group: number; title: string; version: number };
|
|
16
|
+
|
|
17
|
+
const setup = (useVersion: boolean) => {
|
|
18
|
+
const client = createHttpClient();
|
|
19
|
+
const api = createApi(server);
|
|
20
|
+
const getItems = client.createRequest<{ response: Item[] }>()({ endpoint: "/groups/:group/items" });
|
|
21
|
+
const createItem = client.createRequest<{ response: Item; payload: Item }>()({ endpoint: "/items", method: "POST" });
|
|
22
|
+
const updateItem = client.createRequest<{ response: Item; payload: Partial<Item> }>()({
|
|
23
|
+
endpoint: "/items/:id",
|
|
24
|
+
method: "PATCH",
|
|
25
|
+
});
|
|
26
|
+
const deleteItem = client.createRequest<{ response: null }>()({ endpoint: "/items/:id", method: "DELETE" });
|
|
27
|
+
const Items = collection(rowType<Item>(), { key: "id", ...(useVersion ? { version: "version" as const } : {}) })
|
|
28
|
+
.load(getItems, { where: { group: { eq: (group) => ({ params: { group } }), required: true } } })
|
|
29
|
+
.mutate({
|
|
30
|
+
insert: { request: createItem, map: (row) => ({ payload: row }) },
|
|
31
|
+
update: { request: updateItem, map: (id, changes) => ({ params: { id }, payload: changes }) },
|
|
32
|
+
delete: { request: deleteItem, map: (id) => ({ params: { id } }), onSuccess: "keep" },
|
|
33
|
+
});
|
|
34
|
+
const db = createDb({ item: Items });
|
|
35
|
+
return { api, db };
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const runSeed = async (seed: number, useVersion: boolean) => {
|
|
39
|
+
const random = createRandom(seed);
|
|
40
|
+
const { api, db } = setup(useVersion);
|
|
41
|
+
const table = new Map<number, Item>();
|
|
42
|
+
[1, 2, 3].forEach((id) => table.set(id, { id, group: 1, title: `t${id}`, version: 1 }));
|
|
43
|
+
const held: { release: () => void }[] = [];
|
|
44
|
+
let holding = true;
|
|
45
|
+
/** Holds a response until the test releases it, then answers from the table as it is at that moment */
|
|
46
|
+
const hold = <T>(answer: () => T) =>
|
|
47
|
+
holding
|
|
48
|
+
? new Promise<T>((resolve) => {
|
|
49
|
+
held.push({ release: () => resolve(answer()) });
|
|
50
|
+
})
|
|
51
|
+
: Promise.resolve(answer());
|
|
52
|
+
|
|
53
|
+
api.get("/groups/:group/items", ({ params }) =>
|
|
54
|
+
hold(() => ({ data: [...table.values()].filter((row) => row.group === Number(params.group)) })),
|
|
55
|
+
);
|
|
56
|
+
api.post("/items", ({ body }) =>
|
|
57
|
+
hold(() => {
|
|
58
|
+
const row = body as Item;
|
|
59
|
+
if (table.has(row.id)) {
|
|
60
|
+
return { status: 409, data: { message: "Exists" } };
|
|
61
|
+
}
|
|
62
|
+
const created = { ...row, version: 1 };
|
|
63
|
+
table.set(row.id, created);
|
|
64
|
+
return { data: created };
|
|
65
|
+
}),
|
|
66
|
+
);
|
|
67
|
+
api.patch("/items/:id", ({ params, body }) =>
|
|
68
|
+
hold(() => {
|
|
69
|
+
const current = table.get(Number(params.id));
|
|
70
|
+
if (!current) {
|
|
71
|
+
return { status: 404, data: { message: "Gone" } };
|
|
72
|
+
}
|
|
73
|
+
const next = { ...current, ...(body as Partial<Item>), version: current.version + 1 };
|
|
74
|
+
table.set(next.id, next);
|
|
75
|
+
return { data: next };
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
api.delete("/items/:id", ({ params }) =>
|
|
79
|
+
hold(() => {
|
|
80
|
+
table.delete(Number(params.id));
|
|
81
|
+
return { data: null };
|
|
82
|
+
}),
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
const query = db.item.where((row) => eq(row.group, 1)).orderBy((row) => row.id);
|
|
86
|
+
const unsubscribe = query.subscribe(() => {});
|
|
87
|
+
const writes: Promise<unknown>[] = [];
|
|
88
|
+
const log: string[] = [];
|
|
89
|
+
|
|
90
|
+
for (let step = 0; step < 40; step += 1) {
|
|
91
|
+
const id = random.int(1, 6);
|
|
92
|
+
const action = random.int(0, 9);
|
|
93
|
+
if (action <= 1) {
|
|
94
|
+
const title = `c${step}`;
|
|
95
|
+
log.push(`client update ${id} ${title}`);
|
|
96
|
+
if (db.item.findOne(id).local().getSnapshot().data) {
|
|
97
|
+
writes.push(db.item.update(id, { title }));
|
|
98
|
+
}
|
|
99
|
+
} else if (action === 2) {
|
|
100
|
+
log.push(`client insert ${id}`);
|
|
101
|
+
if (!db.item.findOne(id).local().getSnapshot().data) {
|
|
102
|
+
writes.push(db.item.insert({ id, group: 1, title: `n${step}`, version: 0 }));
|
|
103
|
+
}
|
|
104
|
+
} else if (action === 3) {
|
|
105
|
+
log.push(`client delete ${id}`);
|
|
106
|
+
if (db.item.findOne(id).local().getSnapshot().data) {
|
|
107
|
+
writes.push(db.item.delete(id));
|
|
108
|
+
}
|
|
109
|
+
} else if (action === 4) {
|
|
110
|
+
log.push(`server change ${id}`);
|
|
111
|
+
const current = table.get(id);
|
|
112
|
+
if (current) {
|
|
113
|
+
table.set(id, { ...current, title: `s${step}`, group: random.pick([1, 1, 2]), version: current.version + 1 });
|
|
114
|
+
} else {
|
|
115
|
+
table.set(id, { id, group: 1, title: `s${step}`, version: 1 });
|
|
116
|
+
}
|
|
117
|
+
} else if (action === 5) {
|
|
118
|
+
log.push(`refetch`);
|
|
119
|
+
writes.push(query.refetch());
|
|
120
|
+
} else if (held.length > 0) {
|
|
121
|
+
log.push(`release one of ${held.length}`);
|
|
122
|
+
held.splice(random.int(0, held.length - 1), 1)[0].release();
|
|
123
|
+
}
|
|
124
|
+
await flush(2);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Release everything in a random order, then stop holding and load once more
|
|
128
|
+
while (held.length > 0) {
|
|
129
|
+
held.splice(random.int(0, held.length - 1), 1)[0].release();
|
|
130
|
+
await flush(2);
|
|
131
|
+
}
|
|
132
|
+
holding = false;
|
|
133
|
+
await vi.waitFor(async () => {
|
|
134
|
+
while (held.length > 0) {
|
|
135
|
+
held.shift()!.release();
|
|
136
|
+
}
|
|
137
|
+
await Promise.all(writes);
|
|
138
|
+
});
|
|
139
|
+
await query.refetch();
|
|
140
|
+
await flush();
|
|
141
|
+
|
|
142
|
+
const want = [...table.values()].filter((row) => row.group === 1).toSorted((left, right) => left.id - right.id);
|
|
143
|
+
const context = `seed ${seed}${useVersion ? " with version" : ""}, steps:\n${log.join("\n")}`;
|
|
144
|
+
expect(query.getSnapshot().data, context).toStrictEqual(want);
|
|
145
|
+
expect(db.inspect().collections[0].layers, context).toStrictEqual([]);
|
|
146
|
+
unsubscribe();
|
|
147
|
+
db.destroy();
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
describe("db [ Model ] convergence under random races", () => {
|
|
151
|
+
beforeAll(() => startServer());
|
|
152
|
+
beforeEach(() => resetMocks());
|
|
153
|
+
afterAll(() => stopServer());
|
|
154
|
+
|
|
155
|
+
it.each(Array.from({ length: 60 }, (_, index) => index + 1))("seed %i", async (seed) => {
|
|
156
|
+
await runSeed(seed, false);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it.each(Array.from({ length: 30 }, (_, index) => index + 101))("seed %i with a version field", async (seed) => {
|
|
160
|
+
await runSeed(seed, true);
|
|
161
|
+
});
|
|
162
|
+
});
|