@softistx/alxia-graphql 0.0.0-stage → 0.19.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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +445 -2
  3. package/dist/bounded-stream.d.ts +37 -0
  4. package/dist/bounded-stream.d.ts.map +1 -0
  5. package/dist/endpoint.d.ts +17 -0
  6. package/dist/endpoint.d.ts.map +1 -0
  7. package/dist/executor.d.ts +49 -0
  8. package/dist/executor.d.ts.map +1 -0
  9. package/dist/explorer.d.ts +24 -0
  10. package/dist/explorer.d.ts.map +1 -0
  11. package/dist/graphql.d.ts +63 -0
  12. package/dist/graphql.d.ts.map +1 -0
  13. package/dist/handler.d.ts +11 -0
  14. package/dist/handler.d.ts.map +1 -0
  15. package/dist/index.d.ts +8 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +621 -0
  18. package/dist/index.js.map +21 -0
  19. package/dist/once-per-request.d.ts +28 -0
  20. package/dist/once-per-request.d.ts.map +1 -0
  21. package/dist/operation.d.ts +3 -0
  22. package/dist/operation.d.ts.map +1 -0
  23. package/dist/options.d.ts +38 -0
  24. package/dist/options.d.ts.map +1 -0
  25. package/dist/removed.d.ts +14 -0
  26. package/dist/removed.d.ts.map +1 -0
  27. package/dist/sandbox.d.ts +15 -0
  28. package/dist/sandbox.d.ts.map +1 -0
  29. package/dist/testing/client.d.ts +95 -0
  30. package/dist/testing/client.d.ts.map +1 -0
  31. package/dist/testing/index.d.ts +2 -0
  32. package/dist/testing/index.d.ts.map +1 -0
  33. package/dist/testing/index.js +73 -0
  34. package/dist/testing/index.js.map +10 -0
  35. package/dist/ws.d.ts +30 -0
  36. package/dist/ws.d.ts.map +1 -0
  37. package/docs/README.md +31 -0
  38. package/docs/guide/context.md +351 -0
  39. package/docs/guide/endpoint.md +293 -0
  40. package/docs/guide/executor.md +75 -0
  41. package/docs/guide/ide.md +160 -0
  42. package/docs/guide/plugins.md +316 -0
  43. package/docs/guide/production.md +374 -0
  44. package/docs/guide/testing.md +171 -0
  45. package/docs/guide/websockets.md +329 -0
  46. package/docs/migrating-to-graxia.md +408 -0
  47. package/docs/roadmap.md +122 -0
  48. package/docs/troubleshooting.md +963 -0
  49. package/package.json +69 -5
@@ -0,0 +1,329 @@
1
+ # GraphQL over WebSocket
2
+
3
+ This page covers `ws`: serving the endpoint over WebSocket too, with the
4
+ [`graphql-transport-ws`](https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md)
5
+ protocol of [`graphql-ws`](https://the-guild.dev/graphql/ws) — the default
6
+ of Apollo Client's `GraphQLWsLink` and urql's `subscriptionExchange` — beside
7
+ the HTTP endpoint and its server-sent events.
8
+
9
+ ```sh
10
+ bun add graphql-ws
11
+ ```
12
+
13
+ ```ts
14
+ import { alxia } from '@softistx/alxia';
15
+ import { graphql } from '@softistx/alxia-graphql';
16
+ import { createSchema } from '@softistx/graxia';
17
+
18
+ const schema = createSchema()({
19
+ typeDefs: /* GraphQL */ `
20
+ type Query { hello: String! }
21
+ type Subscription { countdown(from: Int!): Int! }
22
+ `,
23
+ resolvers: {
24
+ Query: { hello: () => 'world' },
25
+ Subscription: {
26
+ countdown: {
27
+ async *subscribe(_, { from }: { from: number }) {
28
+ for (let n = from; n >= 0; n--) yield { countdown: n };
29
+ },
30
+ },
31
+ },
32
+ },
33
+ });
34
+
35
+ const app = alxia().plugin((app) => graphql(app, { schema, ws: true }));
36
+ app.listen(3000); // http://localhost:3000/graphql and ws://localhost:3000/graphql
37
+ ```
38
+
39
+ `graphql-ws` is an optional peer: an app that leaves `ws` off never loads
40
+ it. Server-sent events stay served at the same path either way, so a client
41
+ of each kind works against one deployment.
42
+
43
+ ## `ws`
44
+
45
+ | `ws` | |
46
+ | --- | --- |
47
+ | `false`, or none (default) | subscriptions over server-sent events alone: a WebSocket client gets no `101` |
48
+ | `true` | a socket route at the endpoint's `path`, under the app's prefix |
49
+ | `{ path?, keepAlive? }` | the same, with these options |
50
+
51
+ | Option | Type | Default | Effect |
52
+ | --- | --- | --- | --- |
53
+ | `path` | `` `/${string}` `` | the endpoint's `path` | where a client opens its socket, under the app's prefix |
54
+ | `keepAlive` | `number \| false` | `12_000` | milliseconds between the WebSocket pings the server sends each socket, so a proxy does not close an idle subscription; `false` for none. Anything but a finite positive number throws where `graphql()` is declared |
55
+
56
+ ```ts no-check
57
+ graphql(app, { schema, ws: { path: '/graphql/ws', keepAlive: 30_000 } });
58
+ ```
59
+
60
+ A socket at a path of its own runs the endpoint's graxia instance: its plugins are
61
+ set up once, for both. Queries, mutations and subscriptions all run over a
62
+ socket. The socket
63
+ route shows in the route table `listen` prints in dev, as `WS /graphql`.
64
+
65
+ ## The upgrade runs the app's middlewares
66
+
67
+ The socket is a route of `@softistx/alxia` ([WebSockets](../../../core/docs/guide/websockets.md)):
68
+ the upgrade request runs every middleware given to `use` before
69
+ `graphql()`, every `derive` and `decorate`, then opens. A guard refuses the
70
+ socket with its own answer — a `401` — and the client never connects; what
71
+ the middlewares add is in every resolver's context, typed as over HTTP:
72
+
73
+ ```ts
74
+ import { alxia, defineMiddleware } from '@softistx/alxia';
75
+ import { type GraphQLContext, graphql } from '@softistx/alxia-graphql';
76
+ import { createSchema } from '@softistx/graxia';
77
+
78
+ // A browser cannot set a header on a WebSocket: the token comes in the URL
79
+ // or a cookie there. A server-side client can send `authorization`.
80
+ const viewer = defineMiddleware(({ url, reply }, next) => {
81
+ const token = url.searchParams.get('token');
82
+ return token === null ? reply(401, { error: 'unauthorized' as const }) : next({ viewer: token });
83
+ });
84
+
85
+ const base = alxia().use(viewer);
86
+
87
+ const schema = createSchema<GraphQLContext<typeof base>>()({
88
+ typeDefs: /* GraphQL */ `
89
+ type Query { me: String! }
90
+ type Subscription { countdown(from: Int!): Int! }
91
+ `,
92
+ resolvers: {
93
+ Query: { me: (_, __, { viewer }) => viewer }, // over HTTP and over the socket
94
+ Subscription: {
95
+ countdown: {
96
+ async *subscribe(_, { from }: { from: number }) {
97
+ for (let n = from; n >= 0; n--) yield { countdown: n };
98
+ },
99
+ },
100
+ },
101
+ },
102
+ });
103
+
104
+ export const app = base.plugin((app) => graphql(app, { schema, ws: true }));
105
+ ```
106
+
107
+ The upgrade names `graphql-transport-ws` in its `101` when the client
108
+ offers it; a client that offers only another subprotocol is refused before
109
+ the upgrade with an HTTP `400` and `SUBPROTOCOL_REQUIRED`
110
+ ([Troubleshooting](../troubleshooting.md#the-sec-websocket-protocol-header-must-offer-graphql-transport-ws-400-subprotocol_required)).
111
+
112
+ ## The context of an operation over the socket
113
+
114
+ Each operation runs through graxia, as over HTTP: its plugins
115
+ apply — masked errors, depth limits — and its
116
+ `context` option is called. The context holds:
117
+
118
+ - what the upgrade's middlewares added, `set` and `ip` included;
119
+ - `params`: the operation's `query`, `variables`, `operationName`;
120
+ - `request`: the upgrade's URL and headers, as a `POST` — to graxia an
121
+ operation over the socket is one, so a mutation runs — its `signal`
122
+ aborted when the socket closes;
123
+ - `connectionParams`: what the client sent when it connected
124
+ (`connectionParams` of `createClient`), `undefined` over HTTP.
125
+
126
+ ```ts
127
+ import type { GraphQLContext } from '@softistx/alxia-graphql';
128
+ import { createSchema } from '@softistx/graxia';
129
+ import type { app } from './app';
130
+
131
+ const schema = createSchema<GraphQLContext<typeof app>>()({
132
+ typeDefs: /* GraphQL */ 'type Query { device: String }',
133
+ resolvers: {
134
+ Query: {
135
+ device: (_, __, { connectionParams }) => String(connectionParams?.['device'] ?? 'unknown'),
136
+ },
137
+ },
138
+ });
139
+ ```
140
+
141
+ `connectionParams` is `Readonly<Record<string, unknown>>`: parse it
142
+ before you trust it. A header the upgrade's middlewares set with
143
+ `set.headers` is sent with the `101`; set during an operation, it goes
144
+ nowhere.
145
+
146
+ **Client-header checks.** A plugin's `onParams` also runs for each socket
147
+ operation, and a browser's upgrade request carries no custom header: skip those
148
+ operations with `if (connectionParams) return`, never with the `Upgrade` header.
149
+ See [the troubleshooting entry](../troubleshooting.md#every-websocket-operation-is-refused-by-a-client-header-check).
150
+
151
+ ## Logging and tracing
152
+
153
+ The upgrade is answered before the first operation runs, so its request
154
+ cannot name one. Each operation on the socket is told to the observers
155
+ around the upgrade instead, from its `subscribe` message to its end — a
156
+ query's or a mutation's result sent, a subscription completed, stopped by
157
+ its client or cut by the socket's close — with its type, its name and
158
+ whether it was answered with errors. Give `logger()` and `telemetry()` to
159
+ `use` before `graphql()`, as over HTTP; nothing else to set:
160
+
161
+ ```ts
162
+ const app = alxia()
163
+ .use(logger())
164
+ .use(telemetry({ service: 'notes' }))
165
+ .plugin((app) => graphql(app, { schema, ws: true }));
166
+ ```
167
+
168
+ - `@softistx/alxia-logger` writes the upgrade's line, then one line per operation,
169
+ carrying the upgrade's `requestId`, its `duration` and `outcome`: `ok`,
170
+ or `errors` (a `warn`):
171
+
172
+ ```json
173
+ {"level":"info","requestId":"7f3c…","message":"GET /graphql 200","status":200}
174
+ {"level":"info","requestId":"7f3c…","message":"query GetNotes","duration":2.4,"outcome":"ok","operationName":"GetNotes","operationType":"query"}
175
+ ```
176
+
177
+ - `@softistx/alxia-telemetry` gives the upgrade a span that ends with its answer,
178
+ and each operation a span of its own, a child of the upgrade's:
179
+ `subscription OnNote`, with `graphql.operation.name` and
180
+ `graphql.operation.type`, an error when answered with errors. No span
181
+ lasts as long as the socket.
182
+ - Under `@defer` and `@stream` over a socket, an operation lasts until its
183
+ last payload (`hasNext: false`), not its first, and ends with errors when a
184
+ deferred fragment or a streamed item failed. It ends once, with the outcome
185
+ so far, when its client leaves.
186
+ - An error is an operation answered with errors: a resolver that threw
187
+ (in `errors[]`), a document that does not validate, a subscription that
188
+ failed. A message that does not parse names no operation, and is not
189
+ told.
190
+ - graxia makes no operation span of its own (`telemetry: { operationSpans:
191
+ false }`), so an operation is one span, `@softistx/alxia-telemetry`'s, with graxia's
192
+ parse, validate and execute spans under the upgrade's span; pass `telemetry`
193
+ to `graphql()` to change that.
194
+ - Without either observer, nothing is told, and the operations run as
195
+ they do.
196
+
197
+ `graphql()` tells them with core's `startOperation`, from a graxia plugin on
198
+ `onExecute` and `onSubscribe` (a query or mutation ends with its result, an
199
+ `@defer`/`@stream` one with its last payload, a
200
+ subscription when its `signal` aborts), and they subscribe
201
+ during the upgrade with `onOperation`: no package imports another
202
+ ([core's plugin guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/writing-a-plugin.md)).
203
+
204
+ ## Errors
205
+
206
+ An error stays GraphQL's. A resolver's arrives in a `next` message with
207
+ `errors[]` — masked to `Unexpected error.` unless `maskedErrors` says
208
+ otherwise — and the subscription goes on or completes as over HTTP. A
209
+ query that does not parse or validate is answered with an `error`
210
+ message, the protocol's, and the socket stays open. `maxTokens` applies to
211
+ each operation: a `subscribe` message holding a longer document gets that
212
+ `error`, `Document contains more than 15000 tokens`. `maxNesting` applies to
213
+ each `subscribe` operation the same way: a document nested deeper gets an
214
+ `error` message carrying `GRAPHQL_PARSE_FAILED`, the socket stays open and
215
+ nothing is logged.
216
+
217
+ `bodyLimit` does not reach the socket: a `subscribe` message is bounded by
218
+ Bun's `maxPayloadLength` (16 MiB by default), not by the 1 MiB a `POST` body
219
+ may hold. The parse cache and `maxTokens` still apply to its document, but
220
+ `maxTokens` does not count comments: a large comment-only message still
221
+ costs its parse, and only `maxPayloadLength` bounds it. A
222
+ configurable limit for WebSocket messages is on the
223
+ [roadmap](../roadmap.md).
224
+
225
+ ## Shutdown
226
+
227
+ On `SIGTERM`, `SIGINT` or `stop()`, `/ready` turns 503 and every socket is
228
+ closed with `1001 going away`: each subscription on it completes, its
229
+ resolver's iterator returned, so the drain does not wait for it. A
230
+ `graphql-ws` client retries on `1001`, by default, and reaches another
231
+ instance.
232
+
233
+ ## Clients
234
+
235
+ `graphql-ws`'s own client, in Bun or a browser:
236
+
237
+ ```ts no-check
238
+ import { createClient } from 'graphql-ws';
239
+
240
+ const client = createClient({
241
+ url: 'wss://api.example.com/graphql?token=…',
242
+ connectionParams: { device: 'web' },
243
+ });
244
+
245
+ for await (const result of client.iterate({ query: 'subscription { countdown(from: 3) }' })) {
246
+ console.log(result); // { data: { countdown: 3 } }, …
247
+ }
248
+ ```
249
+
250
+ Apollo Client: subscriptions over the socket, the rest over HTTP.
251
+
252
+ ```ts no-check
253
+ import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client';
254
+ import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
255
+ import { getMainDefinition } from '@apollo/client/utilities';
256
+ import { createClient } from 'graphql-ws';
257
+
258
+ const ws = new GraphQLWsLink(createClient({ url: 'wss://api.example.com/graphql' }));
259
+ const http = new HttpLink({ uri: 'https://api.example.com/graphql' });
260
+
261
+ const client = new ApolloClient({
262
+ cache: new InMemoryCache(),
263
+ link: ApolloLink.split(({ query }) => {
264
+ const definition = getMainDefinition(query);
265
+ return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
266
+ }, ws, http),
267
+ });
268
+ ```
269
+
270
+ urql:
271
+
272
+ ```ts no-check
273
+ import { Client, cacheExchange, fetchExchange, subscriptionExchange } from 'urql';
274
+ import { createClient } from 'graphql-ws';
275
+
276
+ const ws = createClient({ url: 'wss://api.example.com/graphql' });
277
+
278
+ const client = new Client({
279
+ url: 'https://api.example.com/graphql',
280
+ exchanges: [
281
+ cacheExchange,
282
+ fetchExchange,
283
+ subscriptionExchange({
284
+ forwardSubscription: (request) => ({
285
+ subscribe: (sink) => ({ unsubscribe: ws.subscribe({ ...request, query: request.query ?? '' }, sink) }),
286
+ }),
287
+ }),
288
+ ],
289
+ });
290
+ ```
291
+
292
+ GraphiQL can subscribe over the socket too: `graphiql: {
293
+ subscriptionsProtocol: 'WS' }`.
294
+
295
+ ## Testing it
296
+
297
+ A socket needs a server: `listen({ port: 0 })`, then `graphql-ws`'s client
298
+ with Bun's `WebSocket`. Here `app` is the guarded one
299
+ [above](#the-upgrade-runs-the-apps-middlewares), its token in the URL.
300
+
301
+ ```ts no-check
302
+ import { afterAll, expect, test } from 'bun:test';
303
+ import { createClient } from 'graphql-ws';
304
+ import { app } from './app';
305
+
306
+ const server = app.listen({ port: 0, signals: false });
307
+ afterAll(() => app.stop(true));
308
+
309
+ test('a subscription over the socket', async () => {
310
+ const url = new URL('/graphql?token=ada', server.url);
311
+ url.protocol = 'ws:';
312
+ const client = createClient({ url: url.href, webSocketImpl: WebSocket, retryAttempts: 0 });
313
+ const results = [];
314
+ for await (const result of client.iterate({ query: 'subscription { countdown(from: 1) }' })) {
315
+ results.push(result);
316
+ }
317
+ expect(results).toEqual([{ data: { countdown: 1 } }, { data: { countdown: 0 } }]);
318
+ await client.dispose();
319
+ });
320
+ ```
321
+
322
+ ## See also
323
+
324
+ - [Plugins and options](plugins.md#subscriptions): subscriptions over
325
+ server-sent events, `createPubSub`.
326
+ - [Mounting the endpoint](endpoint.md#errors-health-and-shutdown): the
327
+ drain, health probes.
328
+ - [`@softistx/alxia`'s WebSockets](../../../core/docs/guide/websockets.md):
329
+ socket routes, the upgrade.