@hyper-fetch/core 9.6.2 → 9.8.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 (55) hide show
  1. package/__tests__/features/adapter/adapter.typescript.spec.ts +34 -0
  2. package/__tests__/features/adapter/adapter.utils.spec.ts +10 -0
  3. package/__tests__/features/cache/cache.utils.spec.ts +18 -0
  4. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  5. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  6. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  7. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  8. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  9. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  10. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  11. package/__tests__/features/request/request.cloning.spec.ts +28 -0
  12. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  13. package/__tests__/features/request/request.sending.spec.ts +13 -10
  14. package/__tests__/type-stress/custom-adapter/custom-adapter.ts +20 -0
  15. package/__tests__/type-stress/custom-adapter/tsconfig.json +4 -0
  16. package/__tests__/utils/optimistic.utils.ts +124 -0
  17. package/dist/cache/cache.d.ts.map +1 -1
  18. package/dist/client/client.d.ts.map +1 -1
  19. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.mjs +578 -70
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/optimistic/index.d.ts +5 -0
  25. package/dist/optimistic/index.d.ts.map +1 -0
  26. package/dist/optimistic/optimistic.d.ts +67 -0
  27. package/dist/optimistic/optimistic.d.ts.map +1 -0
  28. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  29. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  30. package/dist/optimistic/optimistic.types.d.ts +109 -0
  31. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  32. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  33. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  34. package/dist/request/request.d.ts +13 -5
  35. package/dist/request/request.d.ts.map +1 -1
  36. package/dist/request/request.types.d.ts +40 -1
  37. package/dist/request/request.types.d.ts.map +1 -1
  38. package/dist/request/request.utils.d.ts.map +1 -1
  39. package/dist/types/adapter.types.d.ts +12 -1
  40. package/dist/types/adapter.types.d.ts.map +1 -1
  41. package/package.json +2 -2
  42. package/src/cache/cache.ts +2 -1
  43. package/src/client/client.ts +2 -0
  44. package/src/dispatcher/dispatcher.ts +13 -0
  45. package/src/index.ts +1 -0
  46. package/src/optimistic/index.ts +4 -0
  47. package/src/optimistic/optimistic.settlement.ts +406 -0
  48. package/src/optimistic/optimistic.ts +162 -0
  49. package/src/optimistic/optimistic.types.ts +175 -0
  50. package/src/optimistic/optimistic.utils.ts +112 -0
  51. package/src/request/request.ts +19 -6
  52. package/src/request/request.types.ts +41 -1
  53. package/src/request/request.utils.ts +30 -54
  54. package/src/types/adapter.types.ts +42 -25
  55. package/tsconfig.json +2 -0
@@ -0,0 +1,191 @@
1
+ import { waitFor } from "@testing-library/dom";
2
+
3
+ import { optimistic } from "optimistic";
4
+ import type { OptimisticOperation } from "optimistic";
5
+ import type { ControlledCall } from "../../utils/optimistic.utils";
6
+ import { createControlledClient, createRandom, readCache, seedCache } from "../../utils/optimistic.utils";
7
+
8
+ /** `version` grows with every change the server accepts for the item */
9
+ type Item = { id: number; value: number; version: number };
10
+
11
+ type Pending = { call: ControlledCall; promise: Promise<unknown> };
12
+ type PendingMutation = Pending & { commitOnServer: () => void };
13
+ type PendingFetch = Pending & { snapshot: Item[] };
14
+
15
+ const SEEDS = Array.from({ length: 40 }, (_, index) => index + 1);
16
+ const STEPS = 60;
17
+
18
+ const sortById = (items: Item[] | undefined) => (items ?? []).toSorted((a, b) => a.id - b.id);
19
+ const copy = (items: Item[]) => items.map((item) => ({ ...item }));
20
+
21
+ /**
22
+ * Random sequences of mutations, their outcomes, fetches answered with the server data of the moment they were
23
+ * handled, and deleted entries - against a simulated server. Every rollback uses a documented pattern.
24
+ */
25
+ const run = async (seed: number) => {
26
+ const random = createRandom(seed);
27
+ const { client, calls } = createControlledClient();
28
+ const getItems = client.createRequest<{ response: Item[] }>()({ endpoint: "/items" });
29
+ const mutation = client.createRequest<{ response: null }>()({ endpoint: "/items/:id", method: "POST" });
30
+
31
+ let server: Item[] = [1, 2, 3, 4].map((id) => ({ id, value: 0, version: 0 }));
32
+ let nextId = 5;
33
+ seedCache(client, getItems, copy(server));
34
+
35
+ /** Lowest version of every item the cache may hold, raised by every fetch response written to the cache */
36
+ const floor = new Map<number, number>();
37
+ const mutations: PendingMutation[] = [];
38
+ const fetches: PendingFetch[] = [];
39
+ const read = () => readCache<Item[]>(client, getItems);
40
+
41
+ const checkInvariants = (step: string) => {
42
+ const items = read() ?? [];
43
+ const ids = items.map((item) => item.id);
44
+ expect(new Set(ids).size, `${step}: duplicated items ${ids}`).toBe(ids.length);
45
+ items.forEach((item) => {
46
+ const minimum = floor.get(item.id) ?? 0;
47
+ expect(item.version, `${step}: item ${item.id} went back to an older server version`).toBeGreaterThanOrEqual(
48
+ minimum,
49
+ );
50
+ });
51
+ };
52
+
53
+ const waitForCall = async (getRequestId: () => string) => {
54
+ await waitFor(() => expect(calls.some((call) => call.requestId === getRequestId())).toBeTrue(), {
55
+ interval: 1,
56
+ });
57
+ return calls.find((call) => call.requestId === getRequestId())!;
58
+ };
59
+
60
+ const startMutation = async () => {
61
+ const kind = random.pick(["patch", "remove", "insert"] as const);
62
+ const id = kind === "insert" ? nextId++ : random.pick([1, 2, 3, 4, 5, 6]);
63
+ const value = random.int(100);
64
+ let operation: OptimisticOperation<Item[], any>;
65
+ let commitOnServer: () => void;
66
+
67
+ if (kind === "patch") {
68
+ operation = optimistic(getItems)
69
+ .patch(id, { value })
70
+ .rollback(({ data, previous }) => {
71
+ const before = previous.find((item) => item.id === id);
72
+ return data.map((item) => (item.id === id && before ? before : item));
73
+ });
74
+ commitOnServer = () => {
75
+ server = server.map((item) => (item.id === id ? { ...item, value, version: item.version + 1 } : item));
76
+ };
77
+ } else if (kind === "remove") {
78
+ operation = optimistic(getItems)
79
+ .remove(id)
80
+ .rollback(({ data, previous }) => {
81
+ const removed = previous.find((item) => item.id === id);
82
+ return removed ? [...data, removed] : data;
83
+ });
84
+ commitOnServer = () => {
85
+ server = server.filter((item) => item.id !== id);
86
+ };
87
+ } else {
88
+ operation = optimistic(getItems)
89
+ .insert({ id, value, version: 0 })
90
+ .rollback(({ data }) => data.filter((item) => item.id !== id));
91
+ commitOnServer = () => {
92
+ server = [...server, { id, value, version: 0 }];
93
+ };
94
+ }
95
+
96
+ let requestId = "";
97
+ const promise = mutation.send({
98
+ params: { id },
99
+ optimistic: [operation],
100
+ onBeforeSent: (data) => {
101
+ requestId = data.requestId;
102
+ },
103
+ });
104
+ const call = await waitForCall(() => requestId);
105
+ mutations.push({ call, promise, commitOnServer });
106
+ };
107
+
108
+ const settleMutation = async (index: number, success: boolean) => {
109
+ const [settled] = mutations.splice(index, 1);
110
+ if (success) {
111
+ settled.commitOnServer();
112
+ settled.call.respond({ data: null });
113
+ } else {
114
+ settled.call.respond({ error: new Error("Rejected") });
115
+ }
116
+ await settled.promise;
117
+ };
118
+
119
+ const startFetch = async () => {
120
+ let requestId = "";
121
+ const promise = getItems.send({
122
+ onBeforeSent: (data) => {
123
+ requestId = data.requestId;
124
+ },
125
+ });
126
+ const call = await waitForCall(() => requestId);
127
+ // The server reads its data when it handles the request
128
+ fetches.push({ call, promise, snapshot: copy(server) });
129
+ };
130
+
131
+ const answerFetch = async (index: number) => {
132
+ const [answered] = fetches.splice(index, 1);
133
+ let written = false;
134
+ const unmount = client.cache.events.onDataByKey(getItems.cacheKey, () => {
135
+ written = true;
136
+ });
137
+ answered.call.respond({ data: answered.snapshot });
138
+ await answered.promise;
139
+ unmount();
140
+ if (written) {
141
+ expect(sortById(read())).toStrictEqual(sortById(answered.snapshot));
142
+ answered.snapshot.forEach((item) => floor.set(item.id, Math.max(floor.get(item.id) ?? 0, item.version)));
143
+ }
144
+ };
145
+
146
+ for (let step = 0; step < STEPS; step += 1) {
147
+ const action = random.int(10);
148
+ const label = `seed ${seed}, step ${step}`;
149
+
150
+ if (action < 3 || (mutations.length === 0 && action < 6)) {
151
+ // eslint-disable-next-line no-await-in-loop
152
+ await startMutation();
153
+ } else if (action < 6) {
154
+ // eslint-disable-next-line no-await-in-loop
155
+ await settleMutation(random.int(mutations.length), random.next() < 0.6);
156
+ } else if (action < 8 || fetches.length === 0) {
157
+ // eslint-disable-next-line no-await-in-loop
158
+ await startFetch();
159
+ } else if (action < 9) {
160
+ // eslint-disable-next-line no-await-in-loop
161
+ await answerFetch(random.int(fetches.length));
162
+ } else {
163
+ client.cache.delete(getItems.cacheKey);
164
+ }
165
+
166
+ checkInvariants(label);
167
+ }
168
+
169
+ // Everything settles in a random order
170
+ while (mutations.length > 0 || fetches.length > 0) {
171
+ if (mutations.length > 0 && (random.next() < 0.5 || fetches.length === 0)) {
172
+ // eslint-disable-next-line no-await-in-loop
173
+ await settleMutation(random.int(mutations.length), random.next() < 0.6);
174
+ } else {
175
+ // eslint-disable-next-line no-await-in-loop
176
+ await answerFetch(random.int(fetches.length));
177
+ }
178
+ checkInvariants(`seed ${seed}, settling`);
179
+ }
180
+
181
+ // Nothing is pending anymore, so the refresh is written and the cache matches the server
182
+ await startFetch();
183
+ await answerFetch(0);
184
+ expect(sortById(read())).toStrictEqual(sortById(server));
185
+ };
186
+
187
+ describe("Optimistic [ Randomized invariants ]", () => {
188
+ it.each(SEEDS)("should converge to the server data and never go back in time (seed %i)", async (seed) => {
189
+ await run(seed);
190
+ });
191
+ });