@trpc/server 11.24.1-canary.7.8ff8793e9 → 11.25.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 +1 -1
- package/dist/adapters/aws-lambda/index.cjs +1 -1
- package/dist/adapters/aws-lambda/index.d.cts +1 -1
- package/dist/adapters/aws-lambda/index.d.mts +1 -1
- package/dist/adapters/aws-lambda/index.mjs +1 -1
- package/dist/adapters/express.cjs +1 -1
- package/dist/adapters/express.d.cts +2 -2
- package/dist/adapters/express.d.mts +2 -2
- package/dist/adapters/express.mjs +1 -1
- package/dist/adapters/fastify/index.cjs +3 -3
- package/dist/adapters/fastify/index.d.cts +3 -3
- package/dist/adapters/fastify/index.d.mts +3 -3
- package/dist/adapters/fastify/index.mjs +3 -3
- package/dist/adapters/fetch/index.cjs +1 -1
- package/dist/adapters/fetch/index.d.cts +1 -1
- package/dist/adapters/fetch/index.d.mts +1 -1
- package/dist/adapters/fetch/index.mjs +1 -1
- package/dist/adapters/next-app-dir.d.cts +1 -1
- package/dist/adapters/next-app-dir.d.mts +1 -1
- package/dist/adapters/next.cjs +1 -1
- package/dist/adapters/next.d.cts +2 -2
- package/dist/adapters/next.d.mts +2 -2
- package/dist/adapters/next.mjs +1 -1
- package/dist/adapters/node-http/index.cjs +1 -1
- package/dist/adapters/node-http/index.d.cts +1 -1
- package/dist/adapters/node-http/index.d.mts +1 -1
- package/dist/adapters/node-http/index.mjs +1 -1
- package/dist/adapters/standalone.cjs +1 -1
- package/dist/adapters/standalone.d.cts +2 -2
- package/dist/adapters/standalone.d.mts +2 -2
- package/dist/adapters/standalone.mjs +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.d.cts +2 -2
- package/dist/adapters/ws.d.mts +2 -2
- package/dist/adapters/ws.mjs +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.d.cts +1 -1
- package/dist/http.d.mts +1 -1
- package/dist/http.mjs +1 -1
- package/dist/{index-Bdq70sid.d.cts → index-CFQnkrGZ.d.cts} +6 -3
- package/dist/{index-Bdq70sid.d.cts.map → index-CFQnkrGZ.d.cts.map} +1 -1
- package/dist/{index-Bdq70sid.d.mts → index-CFQnkrGZ.d.mts} +6 -3
- package/dist/{index-Bdq70sid.d.mts.map → index-CFQnkrGZ.d.mts.map} +1 -1
- package/dist/{index-C8o7kgHD.d.mts → index-DVmu6VtT.d.mts} +2 -2
- package/dist/{index-C8o7kgHD.d.mts.map → index-DVmu6VtT.d.mts.map} +1 -1
- package/dist/{index-mlF5Hred.d.cts → index-Dn1ucZS5.d.cts} +2 -2
- package/dist/{index-mlF5Hred.d.cts.map → index-Dn1ucZS5.d.cts.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{initTRPC-BHFhyRlq.mjs → initTRPC-DPoVGUwX.mjs} +2 -2
- package/dist/{initTRPC-BHFhyRlq.mjs.map → initTRPC-DPoVGUwX.mjs.map} +1 -1
- package/dist/{initTRPC-Cqhzvadj.cjs → initTRPC-yeYwDikA.cjs} +1 -1
- package/dist/{node-http-CgxAZYco.mjs → node-http-Df_b1FfK.mjs} +33 -10
- package/dist/{node-http-CgxAZYco.mjs.map → node-http-Df_b1FfK.mjs.map} +1 -1
- package/dist/{node-http-zAXiTJ5z.cjs → node-http-vS2eeV-2.cjs} +31 -8
- package/dist/observable/index.cjs +2 -2
- package/dist/observable/index.d.cts +1 -1
- package/dist/observable/index.d.mts +1 -1
- package/dist/observable/index.mjs +2 -2
- package/dist/{observable-DvS5lN8Q.cjs → observable-1zKJIeLl.cjs} +27 -9
- package/dist/{observable-YaZmQKBm.mjs → observable-Cmd1MFy3.mjs} +17 -3
- package/dist/{observable-YaZmQKBm.mjs.map → observable-Cmd1MFy3.mjs.map} +1 -1
- package/dist/{observable-C__NrSHz.cjs → observable-CtU0hoef.cjs} +16 -2
- package/dist/{observable-Crotwz1G.mjs → observable-kpFFzvou.mjs} +28 -10
- package/dist/observable-kpFFzvou.mjs.map +1 -0
- package/dist/{resolveResponse-KsaMasi_.mjs → resolveResponse-C3K3zKPn.mjs} +2 -2
- package/dist/{resolveResponse-KsaMasi_.mjs.map → resolveResponse-C3K3zKPn.mjs.map} +1 -1
- package/dist/{resolveResponse-BiNVUUPp.cjs → resolveResponse-CoiQ9diV.cjs} +1 -1
- package/dist/rpc.d.cts +1 -1
- package/dist/rpc.d.mts +1 -1
- package/dist/shared.d.cts +1 -1
- package/dist/shared.d.mts +1 -1
- package/dist/{unstable-core-do-not-import-Dwco_7Rh.d.mts → unstable-core-do-not-import-CzDUc5m2.d.mts} +2 -2
- package/dist/{unstable-core-do-not-import-Dwco_7Rh.d.mts.map → unstable-core-do-not-import-CzDUc5m2.d.mts.map} +1 -1
- package/dist/{unstable-core-do-not-import-BSR46h1T.d.cts → unstable-core-do-not-import-Db2TnFh8.d.cts} +2 -2
- package/dist/{unstable-core-do-not-import-BSR46h1T.d.cts.map → unstable-core-do-not-import-Db2TnFh8.d.cts.map} +1 -1
- package/dist/unstable-core-do-not-import.cjs +2 -2
- package/dist/unstable-core-do-not-import.d.cts +1 -1
- package/dist/unstable-core-do-not-import.d.mts +1 -1
- package/dist/unstable-core-do-not-import.mjs +2 -2
- package/dist/{ws-DISNGMFd.mjs → ws-BqEmiHOX.mjs} +348 -195
- package/dist/ws-BqEmiHOX.mjs.map +1 -0
- package/dist/{ws-DFpyRwue.d.cts → ws-D-DF_k_T.d.cts} +3 -3
- package/dist/ws-D-DF_k_T.d.cts.map +1 -0
- package/dist/{ws-CO1rjQdN.d.mts → ws-lJRDMspc.d.mts} +3 -3
- package/dist/ws-lJRDMspc.d.mts.map +1 -0
- package/dist/{ws-BefV3QoE.cjs → ws-zjwsyre9.cjs} +346 -193
- package/package.json +9 -11
- package/skills/adapter-aws-lambda/SKILL.md +1 -1
- package/skills/adapter-express/SKILL.md +1 -1
- package/skills/adapter-fastify/SKILL.md +1 -1
- package/skills/adapter-fetch/SKILL.md +1 -1
- package/skills/adapter-standalone/SKILL.md +1 -1
- package/skills/auth/SKILL.md +1 -1
- package/skills/caching/SKILL.md +1 -1
- package/skills/error-handling/SKILL.md +1 -1
- package/skills/middlewares/SKILL.md +1 -1
- package/skills/non-json-content-types/SKILL.md +1 -1
- package/skills/server-setup/SKILL.md +1 -1
- package/skills/server-side-calls/SKILL.md +1 -1
- package/skills/service-oriented-architecture/SKILL.md +1 -1
- package/skills/subscriptions/SKILL.md +11 -3
- package/skills/trpc-router/SKILL.md +1 -1
- package/skills/validators/SKILL.md +1 -1
- package/src/adapters/node-http/nodeHTTPRequestHandler.ts +37 -8
- package/src/adapters/ws.ts +333 -123
- package/src/observable/behaviorSubject.ts +20 -2
- package/src/observable/observable.ts +26 -11
- package/dist/observable-Crotwz1G.mjs.map +0 -1
- package/dist/ws-CO1rjQdN.d.mts.map +0 -1
- package/dist/ws-DFpyRwue.d.cts.map +0 -1
- package/dist/ws-DISNGMFd.mjs.map +0 -1
package/src/adapters/ws.ts
CHANGED
|
@@ -14,11 +14,12 @@ import {
|
|
|
14
14
|
} from '../@trpc/server';
|
|
15
15
|
import type { TRPCRequestInfo } from '../@trpc/server/http';
|
|
16
16
|
import { type BaseHandlerOptions } from '../@trpc/server/http';
|
|
17
|
-
import { parseTRPCMessage } from '../@trpc/server/rpc';
|
|
17
|
+
import { parseTRPCMessage, TRPC_ERROR_CODES_BY_KEY } from '../@trpc/server/rpc';
|
|
18
18
|
// @trpc/server/rpc
|
|
19
19
|
import type {
|
|
20
20
|
TRPCClientOutgoingMessage,
|
|
21
21
|
TRPCConnectionParamsMessage,
|
|
22
|
+
TRPCErrorShape,
|
|
22
23
|
TRPCReconnectNotification,
|
|
23
24
|
TRPCResponseMessage,
|
|
24
25
|
TRPCResultMessage,
|
|
@@ -27,9 +28,12 @@ import { parseConnectionParamsFromUnknown } from '../http';
|
|
|
27
28
|
import { isObservable, observableToAsyncIterable } from '../observable';
|
|
28
29
|
// oxlint-disable-next-line no-restricted-imports
|
|
29
30
|
import {
|
|
31
|
+
isAbortError,
|
|
30
32
|
isAsyncIterable,
|
|
31
33
|
isObject,
|
|
34
|
+
isPromise,
|
|
32
35
|
isTrackedEnvelope,
|
|
36
|
+
makeResource,
|
|
33
37
|
run,
|
|
34
38
|
type MaybePromise,
|
|
35
39
|
} from '../unstable-core-do-not-import';
|
|
@@ -48,6 +52,50 @@ import { jsonEncoder } from './wsEncoder';
|
|
|
48
52
|
*/
|
|
49
53
|
const WEBSOCKET_OPEN = 1; /* ws.WebSocket.OPEN */
|
|
50
54
|
|
|
55
|
+
function settle<TValue>(promise: Promise<TValue>): Promise<Result<TValue>> {
|
|
56
|
+
return promise.then(
|
|
57
|
+
(value): Result<TValue> => ({ ok: true, value }),
|
|
58
|
+
(error: unknown): Result<TValue> => ({ ok: false, error }),
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* What `await using` rejects with when disposal fails after the scope threw:
|
|
64
|
+
* `error` is the disposal failure and `suppressed` the original error.
|
|
65
|
+
*/
|
|
66
|
+
function isSuppressedError(
|
|
67
|
+
cause: unknown,
|
|
68
|
+
): cause is { error: unknown; suppressed: unknown } {
|
|
69
|
+
return (
|
|
70
|
+
isObject(cause) &&
|
|
71
|
+
cause['name'] === 'SuppressedError' &&
|
|
72
|
+
'error' in cause &&
|
|
73
|
+
'suppressed' in cause
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* What the client gets when its error can't be formatted or encoded. It says
|
|
79
|
+
* nothing about the error, which is what `errorFormatter` would have hidden.
|
|
80
|
+
*/
|
|
81
|
+
const fallbackErrorShape: TRPCErrorShape = {
|
|
82
|
+
code: TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR,
|
|
83
|
+
message: 'Internal server error',
|
|
84
|
+
data: { code: 'INTERNAL_SERVER_ERROR', httpStatus: 500 },
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A procedure that gives up because its subscription was cancelled rejects
|
|
89
|
+
* with an `AbortError`, which is wrapped as an INTERNAL_SERVER_ERROR.
|
|
90
|
+
*/
|
|
91
|
+
function isCancelledSetup(error: TRPCError, signal: AbortSignal) {
|
|
92
|
+
return (
|
|
93
|
+
signal.aborted &&
|
|
94
|
+
error.code === 'INTERNAL_SERVER_ERROR' &&
|
|
95
|
+
isAbortError(error.cause)
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
51
99
|
/**
|
|
52
100
|
* What `createContext` gets in the WebSocket adapter: the upgrade request
|
|
53
101
|
* as `req`, the socket as `res`, and `info`. It's called once per
|
|
@@ -121,6 +169,32 @@ export type WSSHandlerOptions<TRouter extends AnyRouter> =
|
|
|
121
169
|
experimental_encoder?: Encoder;
|
|
122
170
|
};
|
|
123
171
|
|
|
172
|
+
/**
|
|
173
|
+
* `iterator.next()` for a subscription loop that races it against the
|
|
174
|
+
* subscription's `signal`, with a rejection turned into a `TRPCError`.
|
|
175
|
+
*
|
|
176
|
+
* Once the subscription is stopped, the loop doesn't wait for this call, so a
|
|
177
|
+
* rejection after the stop, such as a teardown that throws, goes to
|
|
178
|
+
* `onErrorAfterStop` and resolves `'abort'`. An `AbortError` is how a stopped
|
|
179
|
+
* subscription is expected to end, and isn't reported.
|
|
180
|
+
*/
|
|
181
|
+
function nextUnlessStopped<TValue, TReturn>(
|
|
182
|
+
iterator: AsyncIterator<TValue, TReturn>,
|
|
183
|
+
signal: AbortSignal,
|
|
184
|
+
onErrorAfterStop: (error: TRPCError) => void,
|
|
185
|
+
): Promise<IteratorResult<TValue, TReturn> | TRPCError | 'abort'> {
|
|
186
|
+
return iterator.next().catch((cause: unknown) => {
|
|
187
|
+
const error = getTRPCErrorFromUnknown(cause);
|
|
188
|
+
if (!signal.aborted) {
|
|
189
|
+
return error;
|
|
190
|
+
}
|
|
191
|
+
if (!isAbortError(error.cause)) {
|
|
192
|
+
onErrorAfterStop(error);
|
|
193
|
+
}
|
|
194
|
+
return 'abort';
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
124
198
|
/**
|
|
125
199
|
* Returns a `ws` connection listener that serves a router. `applyWSSHandler`
|
|
126
200
|
* uses it; call it to attach tRPC to your own WebSocket server.
|
|
@@ -139,6 +213,16 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
139
213
|
const clientSubscriptions = new Map<number | string, AbortController>();
|
|
140
214
|
const abortController = new AbortController();
|
|
141
215
|
|
|
216
|
+
function registerSubscription(
|
|
217
|
+
id: number | string,
|
|
218
|
+
subscription: AbortController,
|
|
219
|
+
) {
|
|
220
|
+
clientSubscriptions.set(id, subscription);
|
|
221
|
+
return makeResource({}, () => {
|
|
222
|
+
clientSubscriptions.delete(id);
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
142
226
|
if (opts.keepAlive?.enabled) {
|
|
143
227
|
const { pingMs, pongWaitMs } = opts.keepAlive;
|
|
144
228
|
handleKeepAlive(client, pingMs, pongWaitMs);
|
|
@@ -152,6 +236,107 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
152
236
|
);
|
|
153
237
|
}
|
|
154
238
|
|
|
239
|
+
type ErrorInfo = Parameters<NonNullable<typeof opts.onError>>[0];
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* `onError` runs in listeners and in promises nothing awaits, where a
|
|
243
|
+
* throw or a rejection would crash the process, so either goes to
|
|
244
|
+
* `onFailure` instead.
|
|
245
|
+
*/
|
|
246
|
+
function guardOnError(
|
|
247
|
+
info: ErrorInfo,
|
|
248
|
+
onFailure: (cause: unknown) => void,
|
|
249
|
+
) {
|
|
250
|
+
try {
|
|
251
|
+
const result: unknown = opts.onError?.(info);
|
|
252
|
+
if (isPromise(result)) {
|
|
253
|
+
result.catch(onFailure);
|
|
254
|
+
}
|
|
255
|
+
} catch (cause) {
|
|
256
|
+
onFailure(cause);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Reports an error to `onError`, ignoring an `onError` that fails. */
|
|
261
|
+
function callOnError(info: ErrorInfo) {
|
|
262
|
+
guardOnError(info, () => {
|
|
263
|
+
// ignored, see guardOnError
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Reports a failure of the adapter's own error handling, such as an
|
|
269
|
+
* `errorFormatter` that throws or a reply that can't be sent. It's logged
|
|
270
|
+
* when `onError` is missing or fails, so it's never dropped silently.
|
|
271
|
+
*/
|
|
272
|
+
function reportInternalError(info: ErrorInfo) {
|
|
273
|
+
const log = () => {
|
|
274
|
+
// oxlint-disable-next-line no-console
|
|
275
|
+
console.error('[@trpc/server/adapters/ws]', info.error);
|
|
276
|
+
};
|
|
277
|
+
if (!opts.onError) {
|
|
278
|
+
log();
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
guardOnError(info, log);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* The error shape the client gets, or a minimal one when `errorFormatter`
|
|
286
|
+
* throws, so that the request is still answered.
|
|
287
|
+
*/
|
|
288
|
+
function errorShape(call: Omit<ErrorInfo, 'ctx' | 'req'>): TRPCErrorShape {
|
|
289
|
+
try {
|
|
290
|
+
return getErrorShape({ config: router._def._config, ctx, ...call });
|
|
291
|
+
} catch (cause) {
|
|
292
|
+
reportInternalError({
|
|
293
|
+
...call,
|
|
294
|
+
error: getTRPCErrorFromUnknown(cause),
|
|
295
|
+
ctx,
|
|
296
|
+
req,
|
|
297
|
+
});
|
|
298
|
+
return fallbackErrorShape;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function reportConnectionError(cause: unknown) {
|
|
303
|
+
reportInternalError({
|
|
304
|
+
error: getTRPCErrorFromUnknown(cause),
|
|
305
|
+
path: undefined,
|
|
306
|
+
type: 'unknown',
|
|
307
|
+
ctx,
|
|
308
|
+
req,
|
|
309
|
+
input: undefined,
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Sends a response that isn't tied to a request, reporting it if it
|
|
315
|
+
* can't be built or sent. One that can't be sent is replaced by the
|
|
316
|
+
* fallback error, so that a client still learns it was rejected.
|
|
317
|
+
*/
|
|
318
|
+
function respondOrReport(response: () => TRPCResponseMessage) {
|
|
319
|
+
let message: TRPCResponseMessage | null = null;
|
|
320
|
+
try {
|
|
321
|
+
message = response();
|
|
322
|
+
respond(message);
|
|
323
|
+
} catch (cause) {
|
|
324
|
+
reportConnectionError(cause);
|
|
325
|
+
if (message === null) {
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
respond({
|
|
330
|
+
id: message.id,
|
|
331
|
+
jsonrpc: message.jsonrpc,
|
|
332
|
+
error: fallbackErrorShape,
|
|
333
|
+
});
|
|
334
|
+
} catch {
|
|
335
|
+
// the same failure, and it was reported above
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
155
340
|
async function createCtxPromise(
|
|
156
341
|
getConnectionParams: () => TRPCRequestInfo['connectionParams'],
|
|
157
342
|
): Promise<ContextResult> {
|
|
@@ -178,7 +363,7 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
178
363
|
});
|
|
179
364
|
} catch (cause) {
|
|
180
365
|
const error = getTRPCErrorFromUnknown(cause);
|
|
181
|
-
|
|
366
|
+
callOnError({
|
|
182
367
|
error,
|
|
183
368
|
path: undefined,
|
|
184
369
|
type: 'unknown',
|
|
@@ -186,17 +371,15 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
186
371
|
req,
|
|
187
372
|
input: undefined,
|
|
188
373
|
});
|
|
189
|
-
|
|
374
|
+
respondOrReport(() => ({
|
|
190
375
|
id: null,
|
|
191
|
-
error:
|
|
192
|
-
config: router._def._config,
|
|
376
|
+
error: errorShape({
|
|
193
377
|
error,
|
|
194
378
|
type: 'unknown',
|
|
195
379
|
path: undefined,
|
|
196
380
|
input: undefined,
|
|
197
|
-
ctx,
|
|
198
381
|
}),
|
|
199
|
-
});
|
|
382
|
+
}));
|
|
200
383
|
|
|
201
384
|
// close in next tick
|
|
202
385
|
(globalThis.setImmediate ?? globalThis.setTimeout)(() => {
|
|
@@ -222,7 +405,11 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
222
405
|
? null
|
|
223
406
|
: createCtxPromise(() => null);
|
|
224
407
|
|
|
225
|
-
function handleRequest(
|
|
408
|
+
async function handleRequest(
|
|
409
|
+
msg: TRPCClientOutgoingMessage,
|
|
410
|
+
batchIndex: number,
|
|
411
|
+
ctxResult: Promise<ContextResult>,
|
|
412
|
+
) {
|
|
226
413
|
const { id, jsonrpc } = msg;
|
|
227
414
|
|
|
228
415
|
if (id === null) {
|
|
@@ -232,7 +419,7 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
232
419
|
message: '`id` is required',
|
|
233
420
|
}),
|
|
234
421
|
);
|
|
235
|
-
|
|
422
|
+
callOnError({
|
|
236
423
|
error,
|
|
237
424
|
path: undefined,
|
|
238
425
|
type: 'unknown',
|
|
@@ -243,13 +430,11 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
243
430
|
respond({
|
|
244
431
|
id,
|
|
245
432
|
jsonrpc,
|
|
246
|
-
error:
|
|
247
|
-
config: router._def._config,
|
|
433
|
+
error: errorShape({
|
|
248
434
|
error,
|
|
249
435
|
type: 'unknown',
|
|
250
436
|
path: undefined,
|
|
251
437
|
input: undefined,
|
|
252
|
-
ctx,
|
|
253
438
|
}),
|
|
254
439
|
});
|
|
255
440
|
return;
|
|
@@ -274,14 +459,58 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
274
459
|
};
|
|
275
460
|
}
|
|
276
461
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
462
|
+
const abortController = new AbortController();
|
|
463
|
+
// `abort()` builds an AbortError with a stack trace even when the
|
|
464
|
+
// signal is already aborted, which is the common case on a stop.
|
|
465
|
+
const abort = () => {
|
|
466
|
+
if (!abortController.signal.aborted) {
|
|
467
|
+
abortController.abort();
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
const reportError = (cause: unknown) => {
|
|
471
|
+
const error = getTRPCErrorFromUnknown(cause);
|
|
472
|
+
callOnError({ error, path, type, ctx, req, input });
|
|
473
|
+
return error;
|
|
474
|
+
};
|
|
475
|
+
const respondWithError = (cause: unknown) => {
|
|
476
|
+
const error = reportError(cause);
|
|
477
|
+
respond({
|
|
478
|
+
id,
|
|
479
|
+
jsonrpc,
|
|
480
|
+
error: errorShape({ error, type, path, input }),
|
|
481
|
+
});
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
if (type === 'subscription' && clientSubscriptions.has(id)) {
|
|
485
|
+
// duplicate request ids for client
|
|
486
|
+
respondWithError(
|
|
487
|
+
new TRPCError({
|
|
488
|
+
message: `Duplicate id ${id}`,
|
|
489
|
+
code: 'BAD_REQUEST',
|
|
490
|
+
}),
|
|
491
|
+
);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const execute = async () => {
|
|
496
|
+
// Registered before any await so that a stop or a disconnect during
|
|
497
|
+
// context creation or the procedure call cancels the subscription.
|
|
498
|
+
// The id is freed once this has settled, after the iterator's
|
|
499
|
+
// disposal and right before the client is told it may reuse it.
|
|
500
|
+
using _subscription =
|
|
501
|
+
type === 'subscription'
|
|
502
|
+
? registerSubscription(id, abortController)
|
|
503
|
+
: null;
|
|
504
|
+
|
|
505
|
+
const res = await ctxResult;
|
|
280
506
|
if (!res.ok) {
|
|
281
507
|
throw res.error;
|
|
282
508
|
}
|
|
283
509
|
|
|
284
|
-
|
|
510
|
+
if (abortController.signal.aborted) {
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
|
|
285
514
|
const result = await callTRPCProcedure({
|
|
286
515
|
router,
|
|
287
516
|
path,
|
|
@@ -321,30 +550,42 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
321
550
|
});
|
|
322
551
|
}
|
|
323
552
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
// no need to send stopped message if the client is disconnected
|
|
553
|
+
const iterable = isObservable(result)
|
|
554
|
+
? observableToAsyncIterable(result, abortController.signal)
|
|
555
|
+
: result;
|
|
328
556
|
|
|
557
|
+
// A failed iterator cleanup is reported to the server only: the
|
|
558
|
+
// client still gets `stopped`, so a subscription that completed or
|
|
559
|
+
// was stopped doesn't turn into a failed one.
|
|
560
|
+
if (abortController.signal.aborted) {
|
|
561
|
+
try {
|
|
562
|
+
// dispose the iterator without consuming it
|
|
563
|
+
await using _iterator = iteratorResource(iterable);
|
|
564
|
+
} catch (cause) {
|
|
565
|
+
reportError(cause);
|
|
566
|
+
}
|
|
329
567
|
return;
|
|
330
568
|
}
|
|
331
569
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
});
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
const iterable = isObservable(result)
|
|
343
|
-
? observableToAsyncIterable(result, abortController.signal)
|
|
344
|
-
: result;
|
|
570
|
+
respond({
|
|
571
|
+
id,
|
|
572
|
+
jsonrpc,
|
|
573
|
+
result: {
|
|
574
|
+
type: 'started',
|
|
575
|
+
},
|
|
576
|
+
});
|
|
345
577
|
|
|
346
|
-
|
|
578
|
+
let ended = false;
|
|
579
|
+
try {
|
|
347
580
|
await using iterator = iteratorResource(iterable);
|
|
581
|
+
let completed = false;
|
|
582
|
+
// Disposed before the iterator, so cleanup that waits for
|
|
583
|
+
// cancellation is woken when iteration ends other than by `done`.
|
|
584
|
+
using _abortUnlessCompleted = makeResource({}, () => {
|
|
585
|
+
if (!completed) {
|
|
586
|
+
abort();
|
|
587
|
+
}
|
|
588
|
+
});
|
|
348
589
|
|
|
349
590
|
const abortPromise = new Promise<'abort'>((resolve) => {
|
|
350
591
|
abortController.signal.onabort = () => resolve('abort');
|
|
@@ -361,32 +602,21 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
361
602
|
|
|
362
603
|
while (true) {
|
|
363
604
|
next = await Unpromise.race([
|
|
364
|
-
iterator.
|
|
605
|
+
nextUnlessStopped(iterator, abortController.signal, (error) =>
|
|
606
|
+
callOnError({ error, path, type, ctx, req, input }),
|
|
607
|
+
),
|
|
365
608
|
abortPromise,
|
|
366
609
|
]);
|
|
367
610
|
|
|
368
611
|
if (next === 'abort') {
|
|
369
|
-
await iterator.return?.();
|
|
370
612
|
break;
|
|
371
613
|
}
|
|
372
614
|
if (next instanceof Error) {
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
respond({
|
|
376
|
-
id,
|
|
377
|
-
jsonrpc,
|
|
378
|
-
error: getErrorShape({
|
|
379
|
-
config: router._def._config,
|
|
380
|
-
error,
|
|
381
|
-
type,
|
|
382
|
-
path,
|
|
383
|
-
input,
|
|
384
|
-
ctx,
|
|
385
|
-
}),
|
|
386
|
-
});
|
|
387
|
-
break;
|
|
615
|
+
// Report the error only after the iterator's disposal settles.
|
|
616
|
+
throw next;
|
|
388
617
|
}
|
|
389
618
|
if (next.done) {
|
|
619
|
+
completed = true;
|
|
390
620
|
break;
|
|
391
621
|
}
|
|
392
622
|
|
|
@@ -414,59 +644,45 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
414
644
|
next = null;
|
|
415
645
|
result = null;
|
|
416
646
|
}
|
|
647
|
+
ended = true;
|
|
648
|
+
} catch (cause) {
|
|
649
|
+
abort();
|
|
650
|
+
if (ended) {
|
|
651
|
+
reportError(cause);
|
|
652
|
+
} else if (isSuppressedError(cause)) {
|
|
653
|
+
// the client gets the iteration error, the server both
|
|
654
|
+
respondWithError(cause.suppressed);
|
|
655
|
+
reportError(cause.error);
|
|
656
|
+
} else {
|
|
657
|
+
respondWithError(cause);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
};
|
|
417
661
|
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
})
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
const error = getTRPCErrorFromUnknown(cause);
|
|
429
|
-
opts.onError?.({ error, path, type, ctx, req, input });
|
|
430
|
-
respond({
|
|
431
|
-
id,
|
|
432
|
-
jsonrpc,
|
|
433
|
-
error: getErrorShape({
|
|
434
|
-
config: router._def._config,
|
|
435
|
-
error,
|
|
436
|
-
type,
|
|
662
|
+
const outcome = await settle(execute());
|
|
663
|
+
if (!outcome.ok) {
|
|
664
|
+
const error = getTRPCErrorFromUnknown(outcome.error);
|
|
665
|
+
if (!isCancelledSetup(error, abortController.signal)) {
|
|
666
|
+
try {
|
|
667
|
+
respondWithError(error);
|
|
668
|
+
} catch (cause) {
|
|
669
|
+
// the error reply couldn't be encoded or sent
|
|
670
|
+
reportInternalError({
|
|
671
|
+
error: getTRPCErrorFromUnknown(cause),
|
|
437
672
|
path,
|
|
438
|
-
|
|
673
|
+
type,
|
|
439
674
|
ctx,
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
},
|
|
452
|
-
});
|
|
453
|
-
}).catch((cause) => {
|
|
454
|
-
// procedure threw an error
|
|
455
|
-
const error = getTRPCErrorFromUnknown(cause);
|
|
456
|
-
opts.onError?.({ error, path, type, ctx, req, input });
|
|
457
|
-
respond({
|
|
458
|
-
id,
|
|
459
|
-
jsonrpc,
|
|
460
|
-
error: getErrorShape({
|
|
461
|
-
config: router._def._config,
|
|
462
|
-
error,
|
|
463
|
-
type,
|
|
464
|
-
path,
|
|
465
|
-
input,
|
|
466
|
-
ctx,
|
|
467
|
-
}),
|
|
468
|
-
});
|
|
469
|
-
});
|
|
675
|
+
req,
|
|
676
|
+
input,
|
|
677
|
+
});
|
|
678
|
+
respondOrReport(() => ({ id, jsonrpc, error: fallbackErrorShape }));
|
|
679
|
+
}
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
if (type === 'subscription') {
|
|
684
|
+
respond({ id, jsonrpc, result: { type: 'stopped' } });
|
|
685
|
+
}
|
|
470
686
|
}
|
|
471
687
|
client.on('message', (rawData, isBinary) => {
|
|
472
688
|
// Handle PING/PONG as text regardless of encoder
|
|
@@ -491,17 +707,15 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
491
707
|
code: 'UNPROCESSABLE_CONTENT',
|
|
492
708
|
message: 'Unexpected WebSocket message format',
|
|
493
709
|
});
|
|
494
|
-
|
|
710
|
+
respondOrReport(() => ({
|
|
495
711
|
id: null,
|
|
496
|
-
error:
|
|
497
|
-
config: router._def._config,
|
|
712
|
+
error: errorShape({
|
|
498
713
|
error,
|
|
499
714
|
type: 'unknown',
|
|
500
715
|
path: undefined,
|
|
501
716
|
input: undefined,
|
|
502
|
-
ctx,
|
|
503
717
|
}),
|
|
504
|
-
});
|
|
718
|
+
}));
|
|
505
719
|
return;
|
|
506
720
|
}
|
|
507
721
|
const data: string | Uint8Array = isBinary
|
|
@@ -547,7 +761,7 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
547
761
|
code: 'BAD_REQUEST',
|
|
548
762
|
message: `Batch call exceeds maximum size`,
|
|
549
763
|
});
|
|
550
|
-
|
|
764
|
+
callOnError({
|
|
551
765
|
error,
|
|
552
766
|
path: undefined,
|
|
553
767
|
type: 'unknown',
|
|
@@ -555,13 +769,11 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
555
769
|
req,
|
|
556
770
|
input: undefined,
|
|
557
771
|
});
|
|
558
|
-
const
|
|
559
|
-
config: router._def._config,
|
|
772
|
+
const shape = errorShape({
|
|
560
773
|
error,
|
|
561
774
|
type: 'unknown',
|
|
562
775
|
path: undefined,
|
|
563
776
|
input: undefined,
|
|
564
|
-
ctx,
|
|
565
777
|
});
|
|
566
778
|
|
|
567
779
|
// Checked before parsing so that no input is deserialized.
|
|
@@ -574,16 +786,14 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
574
786
|
raw['method'] !== 'subscription.stop' &&
|
|
575
787
|
(typeof raw['id'] === 'number' || typeof raw['id'] === 'string')
|
|
576
788
|
) {
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
error: errorShape,
|
|
581
|
-
});
|
|
789
|
+
const id = raw['id'];
|
|
790
|
+
const jsonrpc = raw['jsonrpc'] === '2.0' ? '2.0' : undefined;
|
|
791
|
+
respondOrReport(() => ({ id, jsonrpc, error: shape }));
|
|
582
792
|
responded = true;
|
|
583
793
|
}
|
|
584
794
|
}
|
|
585
795
|
if (!responded) {
|
|
586
|
-
|
|
796
|
+
respondOrReport(() => ({ id: null, error: shape }));
|
|
587
797
|
}
|
|
588
798
|
return [];
|
|
589
799
|
}
|
|
@@ -595,23 +805,23 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
595
805
|
cause,
|
|
596
806
|
});
|
|
597
807
|
|
|
598
|
-
|
|
808
|
+
respondOrReport(() => ({
|
|
599
809
|
id: null,
|
|
600
|
-
error:
|
|
601
|
-
config: router._def._config,
|
|
810
|
+
error: errorShape({
|
|
602
811
|
error,
|
|
603
812
|
type: 'unknown',
|
|
604
813
|
path: undefined,
|
|
605
814
|
input: undefined,
|
|
606
|
-
ctx,
|
|
607
815
|
}),
|
|
608
|
-
});
|
|
816
|
+
}));
|
|
609
817
|
|
|
610
818
|
return [];
|
|
611
819
|
}
|
|
612
820
|
});
|
|
613
821
|
|
|
614
|
-
|
|
822
|
+
for (const [index, msg] of parsedMsgs.entries()) {
|
|
823
|
+
handleRequest(msg, index, ctxPromise).catch(reportConnectionError);
|
|
824
|
+
}
|
|
615
825
|
});
|
|
616
826
|
|
|
617
827
|
// WebSocket errors should be handled, as otherwise unhandled exceptions will crash Node.js.
|
|
@@ -619,7 +829,7 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
619
829
|
// "RangeError: Invalid WebSocket frame: RSV2 and RSV3 must be clear"
|
|
620
830
|
// Here is the relevant discussion: https://github.com/websockets/ws/issues/1354#issuecomment-774616962
|
|
621
831
|
client.on('error', (cause) => {
|
|
622
|
-
|
|
832
|
+
callOnError({
|
|
623
833
|
ctx,
|
|
624
834
|
error: getTRPCErrorFromUnknown(cause),
|
|
625
835
|
input: undefined,
|
|
@@ -4,7 +4,10 @@ import type { Observable, Observer } from './types';
|
|
|
4
4
|
/** An observable that holds a current value. */
|
|
5
5
|
export interface BehaviorSubject<TValue> extends Observable<TValue, never> {
|
|
6
6
|
observable: Observable<TValue, never>;
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Sets the value and sends it to subscribers, if it changed. A subscriber
|
|
9
|
+
* that throws doesn't stop the others; its error is rethrown asynchronously.
|
|
10
|
+
*/
|
|
8
11
|
next: (value: TValue) => void;
|
|
9
12
|
/** The current value. */
|
|
10
13
|
get: () => TValue;
|
|
@@ -16,6 +19,21 @@ export interface ReadonlyBehaviorSubject<TValue> extends Omit<
|
|
|
16
19
|
'next'
|
|
17
20
|
> {}
|
|
18
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Calls one of several observers. A throw would stop the caller from
|
|
24
|
+
* notifying the rest, so it is rethrown asynchronously instead: it still
|
|
25
|
+
* shows up as an uncaught exception.
|
|
26
|
+
*/
|
|
27
|
+
function callObserver(callback: () => void) {
|
|
28
|
+
try {
|
|
29
|
+
callback();
|
|
30
|
+
} catch (error) {
|
|
31
|
+
setTimeout(() => {
|
|
32
|
+
throw error;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
19
37
|
/**
|
|
20
38
|
* Creates an observable that holds a current value. New subscribers get
|
|
21
39
|
* it right away, unless it's `undefined`.
|
|
@@ -54,7 +72,7 @@ export function behaviorSubject<TValue>(
|
|
|
54
72
|
// observer removed by an earlier callback must not be notified
|
|
55
73
|
for (const observer of [...observerList]) {
|
|
56
74
|
if (observerList.has(observer)) {
|
|
57
|
-
observer.next(nextValue);
|
|
75
|
+
callObserver(() => observer.next(nextValue));
|
|
58
76
|
}
|
|
59
77
|
}
|
|
60
78
|
};
|