@hyper-fetch/graphql 10.0.0 → 10.1.1

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 (57) hide show
  1. package/README.md +152 -84
  2. package/__tests__/e2e/e2e.conformance.spec.ts +206 -0
  3. package/__tests__/e2e/e2e.graphql-ws-server.ts +187 -0
  4. package/__tests__/e2e/e2e.graphql-ws.spec.ts +306 -0
  5. package/__tests__/e2e/e2e.react-subscriptions.spec.tsx +208 -0
  6. package/__tests__/features/adapter/adapter.browser.spec.ts +23 -5
  7. package/__tests__/features/adapter/adapter.document.spec.ts +17 -13
  8. package/__tests__/features/adapter/adapter.headers.spec.ts +65 -0
  9. package/__tests__/features/adapter/adapter.keys.spec.ts +235 -0
  10. package/__tests__/features/adapter/adapter.persisted-queries.spec.ts +207 -0
  11. package/__tests__/features/adapter/adapter.progress.spec.ts +39 -0
  12. package/__tests__/features/adapter/adapter.responses.spec.ts +162 -1
  13. package/__tests__/features/adapter/adapter.server.spec.ts +6 -6
  14. package/__tests__/features/adapter/adapter.types.spec.ts +121 -2
  15. package/__tests__/features/adapter/adapter.utils.spec.ts +4 -2
  16. package/__tests__/features/adapter/adapter.variables.spec.ts +3 -3
  17. package/__tests__/features/socket/socket.connection.spec.ts +892 -0
  18. package/__tests__/features/socket/socket.fuzz.spec.ts +329 -0
  19. package/__tests__/features/socket/socket.subscriptions.spec.ts +515 -0
  20. package/__tests__/features/socket/socket.types.spec.ts +160 -0
  21. package/__tests__/utils/controlled-websocket.ts +238 -0
  22. package/dist/adapter/adapter.constants.d.ts +5 -0
  23. package/dist/adapter/adapter.constants.d.ts.map +1 -1
  24. package/dist/adapter/adapter.types.d.ts +55 -2
  25. package/dist/adapter/adapter.types.d.ts.map +1 -1
  26. package/dist/adapter/adapter.utils.d.ts +51 -4
  27. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  28. package/dist/adapter/http-adapter.fetch.d.ts.map +1 -1
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.mjs +958 -128
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/socket/index.d.ts +5 -0
  34. package/dist/socket/index.d.ts.map +1 -0
  35. package/dist/socket/socket.constants.d.ts +44 -0
  36. package/dist/socket/socket.constants.d.ts.map +1 -0
  37. package/dist/socket/socket.subscriptions.d.ts +74 -0
  38. package/dist/socket/socket.subscriptions.d.ts.map +1 -0
  39. package/dist/socket/socket.types.d.ts +102 -0
  40. package/dist/socket/socket.types.d.ts.map +1 -0
  41. package/dist/socket/socket.utils.d.ts +80 -0
  42. package/dist/socket/socket.utils.d.ts.map +1 -0
  43. package/dist/socket/socket.websocket.d.ts +30 -0
  44. package/dist/socket/socket.websocket.d.ts.map +1 -0
  45. package/package.json +17 -18
  46. package/src/adapter/adapter.constants.ts +6 -0
  47. package/src/adapter/adapter.types.ts +69 -3
  48. package/src/adapter/adapter.utils.ts +196 -25
  49. package/src/adapter/http-adapter.fetch.ts +93 -43
  50. package/src/index.ts +1 -0
  51. package/src/socket/index.ts +4 -0
  52. package/src/socket/socket.constants.ts +59 -0
  53. package/src/socket/socket.subscriptions.ts +160 -0
  54. package/src/socket/socket.types.ts +118 -0
  55. package/src/socket/socket.utils.ts +150 -0
  56. package/src/socket/socket.websocket.ts +555 -0
  57. package/vite.config.ts +4 -0
@@ -0,0 +1,329 @@
1
+ import { AppManager } from "@hyper-fetch/core";
2
+ import { Socket } from "@hyper-fetch/sockets";
3
+
4
+ import { GraphqlWsAdapter } from "../../../src";
5
+ import {
6
+ ControlledWebSocket,
7
+ flushPromises,
8
+ installControlledWebSocket,
9
+ uninstallControlledWebSocket,
10
+ } from "../../utils/controlled-websocket";
11
+
12
+ /** Deterministic random numbers, so a failing seed can be replayed */
13
+ const createRandom = (seed: number) => {
14
+ let state = seed;
15
+ return () => {
16
+ // mulberry32 - the increment is 0x6D2B79F5
17
+ state = Math.trunc(state + 1_831_565_813);
18
+ let value = Math.imul(state ^ (state >>> 15), 1 | state);
19
+ value ^= value + Math.imul(value ^ (value >>> 7), 61 | value);
20
+ // `>>> 0` reads the 32 bits as unsigned, `Math.trunc` would keep the sign
21
+ // eslint-disable-next-line unicorn/prefer-math-trunc
22
+ return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
23
+ };
24
+ };
25
+
26
+ const documents = ["subscription A($v: Int) { a(v: $v) }", "subscription B($v: Int) { b(v: $v) }"];
27
+ const variables = [undefined, { v: 1 }, { v: 2 }];
28
+ const closeCodes = [1000, 1001, 1006, 1011, 4400, 4401, 4403, 4408, 4499, 4500];
29
+
30
+ type ListenerEntryType = {
31
+ key: string;
32
+ stop: () => void;
33
+ received: string[];
34
+ ended: boolean;
35
+ };
36
+
37
+ /** What the server knows about one transport - built from the frames, the way a server would see them */
38
+ type TransportModelType = {
39
+ acknowledged: boolean;
40
+ /** Ids the client subscribed and neither side completed yet, with the key of their subscription */
41
+ live: Map<string, string>;
42
+ /** Ids that are over - completed by the client or ended by the server */
43
+ done: Set<string>;
44
+ };
45
+
46
+ const SEEDS = 300;
47
+ const STEPS = 80;
48
+
49
+ describe("Graphql Ws Adapter [ Fuzz ]", () => {
50
+ let random = vi.spyOn(Math, "random");
51
+
52
+ beforeEach(() => {
53
+ random = vi.spyOn(Math, "random").mockReturnValue(0.5);
54
+ installControlledWebSocket();
55
+ vi.useFakeTimers();
56
+ });
57
+
58
+ afterEach(() => {
59
+ vi.useRealTimers();
60
+ uninstallControlledWebSocket();
61
+ random.mockRestore();
62
+ });
63
+
64
+ it(`should keep the protocol invariants in ${SEEDS} random runs of ${STEPS} steps`, async () => {
65
+ // Proves the runs reach the interesting states - a fuzz that never acknowledges a connection proves nothing
66
+ const reached = { transports: 0, subscribes: 0, events: 0, resubscribes: 0 };
67
+ for (let seed = 1; seed <= SEEDS; seed += 1) {
68
+ ControlledWebSocket.reset();
69
+ const next = createRandom(seed);
70
+ const pick = <T>(items: readonly T[]): T => items[Math.floor(next() * items.length)];
71
+ const steps: string[] = [];
72
+ const fail = (message: string) => {
73
+ throw new Error(`Seed ${seed}: ${message}\nSteps: ${steps.join(" > ")}`);
74
+ };
75
+
76
+ const lazy = next() < 0.3;
77
+ const socket = new Socket({
78
+ url: "ws://localhost/graphql",
79
+ adapter: GraphqlWsAdapter(),
80
+ adapterOptions: { autoConnect: false, lazy, lazyCloseTimeout: lazy && next() < 0.5 ? 50 : 0 },
81
+ reconnectTime: 20,
82
+ maxReconnectTime: 80,
83
+ connectionTimeout: 400,
84
+ appManager: () => new AppManager(),
85
+ });
86
+ socket.onError(() => null);
87
+
88
+ const listeners: ListenerEntryType[] = [];
89
+ const models = new Map<ControlledWebSocket, TransportModelType>();
90
+ const usedIds = new Set<string>();
91
+ const modelOf = (ws: ControlledWebSocket) => {
92
+ const model = models.get(ws) ?? { acknowledged: false, live: new Map(), done: new Set() };
93
+ models.set(ws, model);
94
+ return model;
95
+ };
96
+ // Frames of every transport that were checked already
97
+ const checkedFrames = new Map<ControlledWebSocket, number>();
98
+
99
+ /** Reads the new client frames of every transport and checks them against what the server would accept */
100
+ const checkClientFrames = () => {
101
+ ControlledWebSocket.instances.forEach((ws) => {
102
+ const model = modelOf(ws);
103
+ const from = checkedFrames.get(ws) ?? 0;
104
+ ws.messages.slice(from).forEach((message) => {
105
+ if (message.type === "subscribe") {
106
+ if (!model.acknowledged) {
107
+ fail(`subscribe ${message.id} before the acknowledgement`);
108
+ }
109
+ if (usedIds.has(message.id)) {
110
+ fail(`id ${message.id} reused`);
111
+ }
112
+ usedIds.add(message.id);
113
+ const key = `${message.payload.query}|${JSON.stringify(message.payload.variables)}`;
114
+ if ([...model.live.values()].includes(key)) {
115
+ fail(`duplicate live subscription ${key}`);
116
+ }
117
+ model.live.set(message.id, key);
118
+ }
119
+ if (message.type === "complete") {
120
+ if (!model.live.has(message.id)) {
121
+ fail(`complete for ${message.id} that is not live`);
122
+ }
123
+ model.live.delete(message.id);
124
+ model.done.add(message.id);
125
+ }
126
+ });
127
+ checkedFrames.set(ws, ws.messages.length);
128
+ });
129
+ if (ControlledWebSocket.active.length > 1) {
130
+ fail("more than one live transport");
131
+ }
132
+ };
133
+
134
+ const current = () => ControlledWebSocket.active.at(-1);
135
+
136
+ const actions: Record<string, () => void> = {
137
+ listen: () => {
138
+ const query = pick(documents);
139
+ const payload = pick(variables);
140
+ const entry: ListenerEntryType = {
141
+ key: `${query}|${JSON.stringify(payload)}`,
142
+ stop: () => null,
143
+ received: [],
144
+ ended: false,
145
+ };
146
+ const listener = socket.createListener<string, typeof payload>()({ topic: query });
147
+ entry.stop = listener.setPayload(payload).listen(
148
+ ({ data }) => {
149
+ entry.received.push(data);
150
+ },
151
+ {
152
+ onEnd: () => {
153
+ entry.ended = true;
154
+ },
155
+ },
156
+ );
157
+ listeners.push(entry);
158
+ },
159
+ stop: () => {
160
+ const entry = pick(listeners.filter(({ ended }) => !ended));
161
+ if (entry) {
162
+ entry.ended = true;
163
+ entry.stop();
164
+ }
165
+ },
166
+ connect: () => {
167
+ socket.connect();
168
+ },
169
+ disconnect: () => {
170
+ socket.disconnect();
171
+ },
172
+ reconnect: () => {
173
+ socket.reconnect();
174
+ },
175
+ open: () => {
176
+ const ws = current();
177
+ if (ws?.readyState === ControlledWebSocket.CONNECTING) {
178
+ ws.serverOpen();
179
+ }
180
+ },
181
+ ack: () => {
182
+ const ws = current();
183
+ if (ws?.readyState === ControlledWebSocket.OPEN && !modelOf(ws).acknowledged) {
184
+ modelOf(ws).acknowledged = true;
185
+ ws.serverAck();
186
+ }
187
+ },
188
+ close: () => {
189
+ current()?.serverClose({ code: pick(closeCodes) });
190
+ },
191
+ next: () => {
192
+ const ws = current();
193
+ const model = ws && modelOf(ws);
194
+ const id = model && pick([...model.live.keys()]);
195
+ if (ws && model && id) {
196
+ const key = model.live.get(id) as string;
197
+ ws.serverNext(id, { data: `${key}#${id}` });
198
+ }
199
+ },
200
+ complete: () => {
201
+ const ws = current();
202
+ const model = ws && modelOf(ws);
203
+ const id = model && pick([...model.live.keys()]);
204
+ if (ws && model && id) {
205
+ model.live.delete(id);
206
+ model.done.add(id);
207
+ if (next() < 0.5) {
208
+ ws.serverComplete(id);
209
+ } else {
210
+ ws.serverError(id, [{ message: "Failed" }]);
211
+ }
212
+ }
213
+ },
214
+ /** A message of a subscription that is over races with its end - the client must ignore it */
215
+ late: () => {
216
+ const ws = current();
217
+ const model = ws && modelOf(ws);
218
+ const id = model && pick([...model.done]);
219
+ if (ws?.readyState === ControlledWebSocket.OPEN && id) {
220
+ if (next() < 0.5) {
221
+ ws.serverNext(id, { data: "late" });
222
+ } else {
223
+ ws.serverComplete(id);
224
+ }
225
+ }
226
+ },
227
+ ping: () => {
228
+ const ws = current();
229
+ if (ws?.readyState === ControlledWebSocket.OPEN) {
230
+ ws.serverMessage({ type: "ping" });
231
+ }
232
+ },
233
+ malformed: () => {
234
+ const ws = current();
235
+ if (ws?.readyState === ControlledWebSocket.OPEN && next() < 0.2) {
236
+ ws.serverSend("{");
237
+ }
238
+ },
239
+ /** The server accepts the connection and acknowledges it in one go */
240
+ serve: () => {
241
+ actions.open();
242
+ actions.ack();
243
+ },
244
+ wait: () => {
245
+ vi.advanceTimersByTime(Math.floor(next() * 150));
246
+ },
247
+ };
248
+ // A server that mostly answers, so the runs spend their steps on acknowledged connections
249
+ const weights: Record<string, number> = {
250
+ listen: 4,
251
+ stop: 2,
252
+ connect: 1,
253
+ disconnect: 0.5,
254
+ reconnect: 0.5,
255
+ open: 1,
256
+ ack: 1,
257
+ serve: 4,
258
+ close: 1,
259
+ next: 5,
260
+ complete: 1,
261
+ late: 1,
262
+ ping: 0.5,
263
+ malformed: 0.3,
264
+ wait: 1.5,
265
+ };
266
+ const names = Object.entries(weights).flatMap(([name, weight]) =>
267
+ Array.from({ length: Math.round(weight * 2) }, () => name),
268
+ );
269
+
270
+ for (let step = 0; step < STEPS; step += 1) {
271
+ const name = pick(names);
272
+ steps.push(name);
273
+ actions[name]();
274
+ // eslint-disable-next-line no-await-in-loop
275
+ await flushPromises();
276
+ checkClientFrames();
277
+
278
+ // Events reach only the listeners of their own subscription
279
+ listeners.forEach((entry) => {
280
+ entry.received.forEach((data) => {
281
+ if (!data.startsWith(`${entry.key}#`)) {
282
+ fail(`event ${data} delivered to ${entry.key}`);
283
+ }
284
+ });
285
+ });
286
+
287
+ // On an acknowledged transport every running subscription is live exactly once
288
+ const ws = current();
289
+ const model = ws && modelOf(ws);
290
+ if (ws && model?.acknowledged && ws.readyState === ControlledWebSocket.OPEN) {
291
+ const wanted = new Set(listeners.filter(({ ended }) => !ended).map(({ key }) => key));
292
+ const live = new Set(model.live.values());
293
+ wanted.forEach((key) => {
294
+ if (!live.has(key)) {
295
+ fail(`running subscription ${key} is not live on the connection`);
296
+ }
297
+ });
298
+ live.forEach((key) => {
299
+ if (!wanted.has(key)) {
300
+ fail(`live subscription ${key} has no listener`);
301
+ }
302
+ });
303
+ }
304
+ }
305
+
306
+ reached.transports += ControlledWebSocket.instances.length;
307
+ reached.subscribes += usedIds.size;
308
+ reached.events += listeners.reduce((sum, { received }) => sum + received.length, 0);
309
+ reached.resubscribes += ControlledWebSocket.instances.slice(1).filter((ws) => ws.subscriptions.length > 0).length;
310
+
311
+ // Nothing outlives the socket
312
+ socket.destroy();
313
+ // eslint-disable-next-line no-await-in-loop
314
+ await flushPromises();
315
+ vi.advanceTimersByTime(1000);
316
+ if (ControlledWebSocket.active.length > 0) {
317
+ fail("a transport outlived the socket");
318
+ }
319
+ if (vi.getTimerCount() > 0) {
320
+ fail(`${vi.getTimerCount()} timers outlived the socket`);
321
+ }
322
+ }
323
+
324
+ expect(reached.transports).toBeGreaterThan(SEEDS * 2);
325
+ expect(reached.subscribes).toBeGreaterThan(SEEDS * 5);
326
+ expect(reached.events).toBeGreaterThan(SEEDS * 3);
327
+ expect(reached.resubscribes).toBeGreaterThan(SEEDS);
328
+ });
329
+ });