@hyper-fetch/orpc 9.8.1 → 10.0.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 +35 -1
- package/__tests__/e2e/e2e.orpc-realtime-server.ts +181 -0
- package/__tests__/e2e/e2e.react-realtime.spec.tsx +181 -0
- package/__tests__/e2e/e2e.realtime.spec.ts +310 -0
- package/__tests__/features/socket/socket.schema.spec.ts +179 -0
- package/__tests__/features/stream-adapter/stream-adapter.environment.spec.ts +163 -0
- package/__tests__/features/stream-adapter/stream-adapter.lifecycle.spec.ts +509 -0
- package/__tests__/features/stream-adapter/stream-adapter.listener-lifecycle.spec.ts +291 -0
- package/__tests__/features/stream-adapter/stream-adapter.protocol.spec.ts +609 -0
- package/__tests__/features/stream-adapter/stream-adapter.subscriptions.spec.ts +270 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.environment.spec.ts +147 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.handshake-error.spec.ts +77 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.lifecycle.spec.ts +326 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.listener-lifecycle.spec.ts +222 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.protocol.spec.ts +415 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.subscriptions.spec.ts +172 -0
- package/__tests__/utils/controlled-fetch.ts +160 -0
- package/__tests__/utils/controlled-websocket.ts +140 -0
- package/__tests__/utils/socket-error.ts +7 -0
- package/__tests__/utils/stream-socket.ts +54 -0
- package/__tests__/utils/websocket-socket.ts +45 -0
- package/__tests__/vitest.setup.ts +20 -0
- package/dist/adapter/adapter.schema.d.ts +32 -0
- package/dist/adapter/adapter.schema.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts +22 -4
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +932 -11
- package/dist/index.mjs.map +1 -1
- package/dist/socket/index.d.ts +3 -0
- package/dist/socket/index.d.ts.map +1 -0
- package/dist/socket/socket.subscriptions.d.ts +31 -0
- package/dist/socket/socket.subscriptions.d.ts.map +1 -0
- package/dist/socket/socket.types.d.ts +62 -0
- package/dist/socket/socket.types.d.ts.map +1 -0
- package/dist/socket/socket.utils.d.ts +56 -0
- package/dist/socket/socket.utils.d.ts.map +1 -0
- package/dist/stream-adapter/index.d.ts +3 -0
- package/dist/stream-adapter/index.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.d.ts +21 -0
- package/dist/stream-adapter/stream-adapter.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.types.d.ts +22 -0
- package/dist/stream-adapter/stream-adapter.types.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.utils.d.ts +22 -0
- package/dist/stream-adapter/stream-adapter.utils.d.ts.map +1 -0
- package/dist/websocket-adapter/index.d.ts +3 -0
- package/dist/websocket-adapter/index.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.d.ts +21 -0
- package/dist/websocket-adapter/websocket-adapter.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.types.d.ts +22 -0
- package/dist/websocket-adapter/websocket-adapter.types.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.utils.d.ts +35 -0
- package/dist/websocket-adapter/websocket-adapter.utils.d.ts.map +1 -0
- package/package.json +3 -1
- package/src/adapter/adapter.schema.ts +57 -0
- package/src/adapter/adapter.utils.ts +40 -10
- package/src/index.ts +3 -0
- package/src/socket/index.ts +2 -0
- package/src/socket/socket.subscriptions.ts +178 -0
- package/src/socket/socket.types.ts +64 -0
- package/src/socket/socket.utils.ts +110 -0
- package/src/stream-adapter/index.ts +2 -0
- package/src/stream-adapter/stream-adapter.ts +381 -0
- package/src/stream-adapter/stream-adapter.types.ts +31 -0
- package/src/stream-adapter/stream-adapter.utils.ts +98 -0
- package/src/websocket-adapter/index.ts +2 -0
- package/src/websocket-adapter/websocket-adapter.ts +417 -0
- package/src/websocket-adapter/websocket-adapter.types.ts +31 -0
- package/src/websocket-adapter/websocket-adapter.utils.ts +119 -0
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-use-before-define */
|
|
2
|
+
import type { QueryParamsType } from "@hyper-fetch/core";
|
|
3
|
+
import { parseResponse, stringifyQueryParams } from "@hyper-fetch/core";
|
|
4
|
+
import type { SocketConnectionType } from "@hyper-fetch/sockets";
|
|
5
|
+
import { SocketAdapter } from "@hyper-fetch/sockets";
|
|
6
|
+
import { isORPCErrorStatus } from "@orpc/client";
|
|
7
|
+
|
|
8
|
+
import { createOrpcSerializer, getOrpcCallRequest, orpcEndpointMapper } from "../adapter/adapter.utils";
|
|
9
|
+
import { createOrpcSubscriptions } from "../socket/socket.subscriptions";
|
|
10
|
+
import type { OrpcSocketAdapterConfigType, OrpcSocketExtraType, OrpcSubscriptionType } from "../socket/socket.types";
|
|
11
|
+
import { getNotIteratorError, getOrpcResponseError } from "../socket/socket.utils";
|
|
12
|
+
import type { OrpcStreamAdapterOptionsType, OrpcStreamAdapterType } from "./stream-adapter.types";
|
|
13
|
+
import type { OrpcEventStreamMessageType } from "./stream-adapter.utils";
|
|
14
|
+
import { createEventStreamDecoder, getEventStreamIteratorEvent } from "./stream-adapter.utils";
|
|
15
|
+
|
|
16
|
+
/** Server side of one subscription - a running request, or the wait before it starts again */
|
|
17
|
+
type StreamTransportType = {
|
|
18
|
+
/** Aborts the running request. It is missing while the stream waits to start again. */
|
|
19
|
+
controller: AbortController | undefined;
|
|
20
|
+
/** Open timeout of the running request, or the delay before the stream starts again */
|
|
21
|
+
timer: ReturnType<typeof setTimeout> | undefined;
|
|
22
|
+
/** Failed starts in a row */
|
|
23
|
+
attempts: number;
|
|
24
|
+
timedOut: boolean;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
type StreamSubscriptionType = OrpcSubscriptionType<StreamTransportType>;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Socket adapter for the event iterators of oRPC over HTTP. Every subscription is a call of the procedure with the
|
|
31
|
+
* RPC protocol - a `POST {url}/planet/onUpdate` with the serialized input - answered with a `text/event-stream`.
|
|
32
|
+
* The same protocol as the `RPCLink` of oRPC, so it works with the `RPCHandler` of `@orpc/server/fetch` or `/node`.
|
|
33
|
+
*
|
|
34
|
+
* There is no shared connection: "connected" means the adapter opens streams. `connect()` starts every
|
|
35
|
+
* subscription, `disconnect()` aborts them, `reconnect()` starts them again with the id of their last event.
|
|
36
|
+
* Listeners of the same procedure and input share one stream, the last one to unsubscribe aborts it.
|
|
37
|
+
* A subscription starts (`onStart`) when the server answers with the event stream, and ends (`onEnd`) when the
|
|
38
|
+
* iterator finishes, fails or the server rejects the call.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* const socket = new Socket({ url: "http://localhost:3000/rpc", adapter: OrpcStreamAdapter() });
|
|
42
|
+
* const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
|
|
43
|
+
*
|
|
44
|
+
* sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data, extra }) => console.log(data, extra.id));
|
|
45
|
+
*/
|
|
46
|
+
export const OrpcStreamAdapter = ({
|
|
47
|
+
customJsonSerializers,
|
|
48
|
+
}: OrpcSocketAdapterConfigType = {}): OrpcStreamAdapterType => {
|
|
49
|
+
const serializer = createOrpcSerializer(customJsonSerializers);
|
|
50
|
+
|
|
51
|
+
return new SocketAdapter<
|
|
52
|
+
OrpcSocketExtraType,
|
|
53
|
+
OrpcStreamAdapterOptionsType,
|
|
54
|
+
undefined,
|
|
55
|
+
undefined,
|
|
56
|
+
QueryParamsType | string,
|
|
57
|
+
typeof stringifyQueryParams
|
|
58
|
+
>({ name: "orpc-stream", confirmsSubscriptions: true })
|
|
59
|
+
.setQueryParamsMapper(stringifyQueryParams)
|
|
60
|
+
.setConnector((bindings) => {
|
|
61
|
+
const {
|
|
62
|
+
socket,
|
|
63
|
+
adapter,
|
|
64
|
+
getQueryParams,
|
|
65
|
+
onConnect,
|
|
66
|
+
onConnectFailed,
|
|
67
|
+
onReconnect,
|
|
68
|
+
onDisconnect,
|
|
69
|
+
onConnected,
|
|
70
|
+
onDisconnected,
|
|
71
|
+
} = bindings;
|
|
72
|
+
|
|
73
|
+
const autoConnect = adapter.adapterOptions?.autoConnect ?? true;
|
|
74
|
+
|
|
75
|
+
// Details of the current connection (after onConnect interceptors), every stream is opened with them.
|
|
76
|
+
// Set only while the adapter is connected.
|
|
77
|
+
let connection: SocketConnectionType<OrpcStreamAdapterType> | undefined;
|
|
78
|
+
// Connection attempt in progress - concurrent `connect()` calls join it
|
|
79
|
+
let pendingConnection: Promise<boolean> | undefined;
|
|
80
|
+
|
|
81
|
+
const subscriptions = createOrpcSubscriptions<OrpcStreamAdapterType, StreamTransportType>({
|
|
82
|
+
bindings,
|
|
83
|
+
serializer,
|
|
84
|
+
start: (subscription) => startStream(subscription, 0),
|
|
85
|
+
stop: (subscription) => stopStream(subscription),
|
|
86
|
+
release: (subscription) => stopStream(subscription),
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Aborts the request or the wait of the subscription. Whatever the old request reports later is ignored.
|
|
91
|
+
* For a stream the server ended it only releases the response.
|
|
92
|
+
*/
|
|
93
|
+
const stopStream = (subscription: StreamSubscriptionType) => {
|
|
94
|
+
const { transport } = subscription;
|
|
95
|
+
subscription.transport = undefined;
|
|
96
|
+
subscription.started = false;
|
|
97
|
+
if (transport) {
|
|
98
|
+
clearTimeout(transport.timer);
|
|
99
|
+
transport.controller?.abort();
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/** After a failure the stream starts again, after the `retry` of the last event or the socket reconnect time */
|
|
104
|
+
const scheduleRestart = (subscription: StreamSubscriptionType, attempts: number) => {
|
|
105
|
+
if (attempts > socket.reconnectAttempts) {
|
|
106
|
+
subscriptions.end(
|
|
107
|
+
subscription,
|
|
108
|
+
new Error(`Stopped restarting the stream of "${subscription.topic}" after ${attempts - 1} attempts`),
|
|
109
|
+
);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const transport: StreamTransportType = { controller: undefined, timer: undefined, attempts, timedOut: false };
|
|
114
|
+
transport.timer = setTimeout(() => {
|
|
115
|
+
// Offline the stream waits for the network and starts again when the app is back online
|
|
116
|
+
if (socket.appManager.isOnline) {
|
|
117
|
+
startStream(subscription, attempts);
|
|
118
|
+
}
|
|
119
|
+
}, subscription.lastEventRetry ?? socket.reconnectTime);
|
|
120
|
+
subscription.transport = transport;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/** Returns `true` when the server ended the iterator */
|
|
124
|
+
const receiveMessage = (subscription: StreamSubscriptionType, message: OrpcEventStreamMessageType): boolean => {
|
|
125
|
+
try {
|
|
126
|
+
const event = getEventStreamIteratorEvent(message);
|
|
127
|
+
return event ? subscriptions.receive(subscription, event) : false;
|
|
128
|
+
} catch (error) {
|
|
129
|
+
// Data that is not JSON - the message is skipped, the stream goes on
|
|
130
|
+
subscriptions.report(subscription, error);
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Reads the stream until the server ends it. Resolves the error of a call the server rejected, rejects when
|
|
137
|
+
* the transport failed - the network, the timeout or a stream cut in the middle of a message.
|
|
138
|
+
*/
|
|
139
|
+
const readStream = async ({
|
|
140
|
+
subscription,
|
|
141
|
+
transport,
|
|
142
|
+
controller,
|
|
143
|
+
details: { url, queryParams, adapterOptions },
|
|
144
|
+
}: {
|
|
145
|
+
subscription: StreamSubscriptionType;
|
|
146
|
+
transport: StreamTransportType;
|
|
147
|
+
controller: AbortController;
|
|
148
|
+
details: SocketConnectionType<OrpcStreamAdapterType>;
|
|
149
|
+
}): Promise<Error | null> => {
|
|
150
|
+
const { headers, fetchOptions, fetch: customFetch } = adapterOptions ?? {};
|
|
151
|
+
const { lastEventId } = subscription;
|
|
152
|
+
const request = getOrpcCallRequest({
|
|
153
|
+
url,
|
|
154
|
+
endpoint: orpcEndpointMapper(subscription.topic),
|
|
155
|
+
queryParams: getQueryParams(queryParams),
|
|
156
|
+
// The server reads it as `lastEventId` and can resume where the previous stream stopped
|
|
157
|
+
headers: lastEventId === undefined ? { ...headers } : { ...headers, "last-event-id": lastEventId },
|
|
158
|
+
payload: subscription.payload,
|
|
159
|
+
method: "POST",
|
|
160
|
+
serializer,
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// Checked to be a function when connecting
|
|
164
|
+
const fetchStream = customFetch ?? globalThis.fetch;
|
|
165
|
+
const response = await fetchStream(request.url, {
|
|
166
|
+
...fetchOptions,
|
|
167
|
+
method: request.method,
|
|
168
|
+
headers: request.headers,
|
|
169
|
+
body: request.body,
|
|
170
|
+
signal: controller.signal,
|
|
171
|
+
});
|
|
172
|
+
clearTimeout(transport.timer);
|
|
173
|
+
|
|
174
|
+
if (isORPCErrorStatus(response.status)) {
|
|
175
|
+
const body = parseResponse(await response.text());
|
|
176
|
+
return getOrpcResponseError({ status: response.status, body, serializer });
|
|
177
|
+
}
|
|
178
|
+
if (!response.headers.get("content-type")?.startsWith("text/event-stream")) {
|
|
179
|
+
return getNotIteratorError(subscription.topic);
|
|
180
|
+
}
|
|
181
|
+
// The server accepted the call, the next failure counts from the beginning
|
|
182
|
+
transport.attempts = 0;
|
|
183
|
+
// Unless the listeners left while the response was on its way
|
|
184
|
+
if (subscription.transport === transport) {
|
|
185
|
+
subscriptions.confirm(subscription);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (!response.body) {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const reader = response.body.getReader();
|
|
193
|
+
const textDecoder = new TextDecoder();
|
|
194
|
+
let ended = false;
|
|
195
|
+
const eventDecoder = createEventStreamDecoder((message) => {
|
|
196
|
+
// Messages after the end, or after the subscription stopped, are not delivered
|
|
197
|
+
if (!ended && subscription.transport === transport) {
|
|
198
|
+
ended = receiveMessage(subscription, message);
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
let chunk = await reader.read();
|
|
203
|
+
while (!chunk.done) {
|
|
204
|
+
eventDecoder.feed(textDecoder.decode(chunk.value, { stream: true }));
|
|
205
|
+
if (ended) {
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
// eslint-disable-next-line no-await-in-loop
|
|
209
|
+
chunk = await reader.read();
|
|
210
|
+
}
|
|
211
|
+
// A stream closed without the `done` event is a finished iterator, the same as in oRPC
|
|
212
|
+
eventDecoder.feed(textDecoder.decode());
|
|
213
|
+
eventDecoder.end();
|
|
214
|
+
return null;
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const startStream = (subscription: StreamSubscriptionType, attempts: number) => {
|
|
218
|
+
// Not connected - the stream starts on connect
|
|
219
|
+
const details = connection;
|
|
220
|
+
if (!details) {
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const controller = new AbortController();
|
|
225
|
+
const transport: StreamTransportType = { controller, timer: undefined, attempts, timedOut: false };
|
|
226
|
+
subscription.transport = transport;
|
|
227
|
+
const isCurrent = () => subscription.transport === transport;
|
|
228
|
+
|
|
229
|
+
// Connection timeout - when the server does not answer in time, the stream starts again
|
|
230
|
+
transport.timer = setTimeout(() => {
|
|
231
|
+
transport.timedOut = true;
|
|
232
|
+
controller.abort();
|
|
233
|
+
}, socket.connectionTimeout);
|
|
234
|
+
|
|
235
|
+
readStream({ subscription, transport, controller, details }).then(
|
|
236
|
+
(rejection) => {
|
|
237
|
+
if (!isCurrent()) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
// The server ended the iterator or rejected the call - the subscription is over
|
|
241
|
+
subscriptions.end(subscription, rejection ?? undefined);
|
|
242
|
+
},
|
|
243
|
+
(error) => {
|
|
244
|
+
if (!isCurrent()) {
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
stopStream(subscription);
|
|
248
|
+
subscriptions.report(
|
|
249
|
+
subscription,
|
|
250
|
+
transport.timedOut
|
|
251
|
+
? new Error(`The stream of "${subscription.topic}" did not open in ${socket.connectionTimeout}ms`)
|
|
252
|
+
: error,
|
|
253
|
+
);
|
|
254
|
+
scheduleRestart(subscription, transport.attempts + 1);
|
|
255
|
+
},
|
|
256
|
+
);
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
const openConnection = async (): Promise<boolean> => {
|
|
260
|
+
const details = await onConnect();
|
|
261
|
+
if (!details) {
|
|
262
|
+
return adapter.connected;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (typeof (details.adapterOptions?.fetch ?? globalThis.fetch) !== "function") {
|
|
266
|
+
onConnectFailed({ error: new Error("fetch is not available in this environment") });
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
connection = details;
|
|
271
|
+
onConnected();
|
|
272
|
+
[...subscriptions.values()].forEach((subscription) => {
|
|
273
|
+
// A listener added by an `onConnected` callback is running already
|
|
274
|
+
if (!subscription.transport) {
|
|
275
|
+
startStream(subscription, 0);
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
return true;
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const connect = (): Promise<boolean> => {
|
|
282
|
+
// Another attempt is already on its way (e.g. the automatic one) - resolve together with it
|
|
283
|
+
if (adapter.connecting && pendingConnection) {
|
|
284
|
+
return pendingConnection;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const attempt = openConnection();
|
|
288
|
+
pendingConnection = attempt;
|
|
289
|
+
const release = () => {
|
|
290
|
+
if (pendingConnection === attempt) {
|
|
291
|
+
pendingConnection = undefined;
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
attempt.then(release, release);
|
|
295
|
+
|
|
296
|
+
return attempt;
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
/** Aborts every stream. Listeners stay registered and keep the id of their last event for the next connection. */
|
|
300
|
+
const closeConnection = async ({ manual }: { manual: boolean }): Promise<boolean> => {
|
|
301
|
+
const wasActive = adapter.connected || adapter.connecting;
|
|
302
|
+
connection = undefined;
|
|
303
|
+
[...subscriptions.values()].forEach(stopStream);
|
|
304
|
+
|
|
305
|
+
onDisconnect();
|
|
306
|
+
if (!manual) {
|
|
307
|
+
// Closing the previous streams is a part of reconnecting - only `disconnect()` keeps the socket closed
|
|
308
|
+
adapter.setForceClosed(false);
|
|
309
|
+
}
|
|
310
|
+
if (wasActive) {
|
|
311
|
+
onDisconnected();
|
|
312
|
+
}
|
|
313
|
+
return true;
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
/** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */
|
|
317
|
+
const disconnect = (): Promise<boolean> => {
|
|
318
|
+
return closeConnection({ manual: true });
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
const reconnect = async () => {
|
|
322
|
+
// Reconnecting is a request to be connected, also after a manual disconnect
|
|
323
|
+
adapter.setForceClosed(false);
|
|
324
|
+
|
|
325
|
+
await onReconnect({
|
|
326
|
+
disconnect: () => closeConnection({ manual: false }),
|
|
327
|
+
connect: async () => {
|
|
328
|
+
// `disconnect()` called in the meantime wins over the reconnection
|
|
329
|
+
if (adapter.forceClosed) {
|
|
330
|
+
adapter.setReconnectionAttempts(0);
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
return connect();
|
|
334
|
+
},
|
|
335
|
+
});
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
// Event iterators only send data from the server. Throwing synchronously makes `emitter.emit()` fail right at
|
|
339
|
+
// the call site, the same as in the Server-Sent Events adapter.
|
|
340
|
+
const emit = () => {
|
|
341
|
+
throw new Error("Cannot emit events in the oRPC stream adapter, it only receives events of subscriptions");
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
// Initialize
|
|
345
|
+
if (autoConnect) {
|
|
346
|
+
connect();
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const unmountOnline = socket.appManager.events.onOnline(() => {
|
|
350
|
+
if (connection) {
|
|
351
|
+
// Streams that failed while offline start again right away
|
|
352
|
+
[...subscriptions.values()].forEach((subscription) => {
|
|
353
|
+
const { transport } = subscription;
|
|
354
|
+
if (transport && !transport.controller) {
|
|
355
|
+
clearTimeout(transport.timer);
|
|
356
|
+
startStream(subscription, transport.attempts);
|
|
357
|
+
}
|
|
358
|
+
});
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
// A socket disconnected on purpose stays closed until `connect()` or `reconnect()` is called
|
|
362
|
+
if (autoConnect && !adapter.forceClosed) {
|
|
363
|
+
connect();
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
return {
|
|
368
|
+
connect,
|
|
369
|
+
reconnect,
|
|
370
|
+
disconnect,
|
|
371
|
+
listen: subscriptions.listen,
|
|
372
|
+
emit,
|
|
373
|
+
// Nothing of this connector outlives the socket - no online subscription, no running or waiting streams
|
|
374
|
+
dispose: () => {
|
|
375
|
+
unmountOnline();
|
|
376
|
+
connection = undefined;
|
|
377
|
+
[...subscriptions.values()].forEach(stopStream);
|
|
378
|
+
},
|
|
379
|
+
};
|
|
380
|
+
});
|
|
381
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { QueryParamsType, stringifyQueryParams } from "@hyper-fetch/core";
|
|
2
|
+
import type { SocketAdapter } from "@hyper-fetch/sockets";
|
|
3
|
+
|
|
4
|
+
import type { OrpcSocketExtraType } from "../socket/socket.types";
|
|
5
|
+
|
|
6
|
+
/** Options of the `OrpcStreamAdapter`, set with the `adapterOptions` of the socket or per connection in `onConnect` */
|
|
7
|
+
export type OrpcStreamAdapterOptionsType = {
|
|
8
|
+
/**
|
|
9
|
+
* Connects when the socket is created. Without it, call `socket.connect()`.
|
|
10
|
+
* @default true
|
|
11
|
+
*/
|
|
12
|
+
autoConnect?: boolean;
|
|
13
|
+
/** Headers of every stream request, e.g. the `authorization` header */
|
|
14
|
+
headers?: Record<string, string>;
|
|
15
|
+
/**
|
|
16
|
+
* The `fetch` used for the streams, e.g. one with a proxy agent or a mock in tests. Defaults to the global `fetch`
|
|
17
|
+
* of browsers, Node.js 18+, Bun and Deno.
|
|
18
|
+
*/
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
/** Options passed to `fetch`, e.g. `credentials: "include"` for cookies on another origin */
|
|
21
|
+
fetchOptions?: Omit<RequestInit, "method" | "headers" | "body" | "signal">;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type OrpcStreamAdapterType = SocketAdapter<
|
|
25
|
+
OrpcSocketExtraType,
|
|
26
|
+
OrpcStreamAdapterOptionsType,
|
|
27
|
+
undefined,
|
|
28
|
+
undefined,
|
|
29
|
+
QueryParamsType | string,
|
|
30
|
+
typeof stringifyQueryParams
|
|
31
|
+
>;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { OrpcIteratorEventType } from "../socket/socket.types";
|
|
2
|
+
|
|
3
|
+
/** One message of a `text/event-stream`, the fields of the Server-Sent Events format */
|
|
4
|
+
export type OrpcEventStreamMessageType = {
|
|
5
|
+
event: string | undefined;
|
|
6
|
+
data: string | undefined;
|
|
7
|
+
id: string | undefined;
|
|
8
|
+
retry: number | undefined;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const lineEnding = /\r\n|\r(?!\n)|\n/;
|
|
12
|
+
const messageDelimiter = /(?:\r\n|\r(?!\n)|\n){2}/g;
|
|
13
|
+
|
|
14
|
+
/** Reads the fields of one message, the same as `decodeEventMessage` of oRPC */
|
|
15
|
+
const decodeEventStreamMessage = (encoded: string): OrpcEventStreamMessageType => {
|
|
16
|
+
const message: OrpcEventStreamMessageType = { event: undefined, data: undefined, id: undefined, retry: undefined };
|
|
17
|
+
|
|
18
|
+
encoded.split(lineEnding).forEach((line) => {
|
|
19
|
+
const index = line.indexOf(":");
|
|
20
|
+
// Lines starting with a colon are comments, the keep-alive pings of oRPC
|
|
21
|
+
if (line === "" || index === 0) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const field = index === -1 ? line : line.slice(0, index);
|
|
25
|
+
const value = index === -1 ? "" : line.slice(line.charAt(index + 1) === " " ? index + 2 : index + 1);
|
|
26
|
+
|
|
27
|
+
if (field === "data") {
|
|
28
|
+
message.data = message.data === undefined ? value : `${message.data}\n${value}`;
|
|
29
|
+
} else if (field === "event") {
|
|
30
|
+
message.event = value;
|
|
31
|
+
} else if (field === "id") {
|
|
32
|
+
message.id = value;
|
|
33
|
+
} else if (field === "retry") {
|
|
34
|
+
const retry = Number.parseInt(value, 10);
|
|
35
|
+
if (retry >= 0 && retry.toString() === value) {
|
|
36
|
+
message.retry = retry;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
return message;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Splits the text of a `text/event-stream` into messages, the same as the `EventDecoder` of oRPC. Chunks can end
|
|
46
|
+
* anywhere, the text after the last complete message waits for the next chunk.
|
|
47
|
+
*/
|
|
48
|
+
export const createEventStreamDecoder = (onMessage: (message: OrpcEventStreamMessageType) => void) => {
|
|
49
|
+
let pending = "";
|
|
50
|
+
// A chunk that ended a message with `\r` may be followed by the `\n` of the same `\r\n`
|
|
51
|
+
let discardLeadingLineFeed = false;
|
|
52
|
+
|
|
53
|
+
const feed = (chunk: string) => {
|
|
54
|
+
pending += discardLeadingLineFeed && chunk.startsWith("\n") ? chunk.slice(1) : chunk;
|
|
55
|
+
discardLeadingLineFeed = false;
|
|
56
|
+
|
|
57
|
+
let start = 0;
|
|
58
|
+
const messages: string[] = [];
|
|
59
|
+
[...pending.matchAll(messageDelimiter)].forEach((match) => {
|
|
60
|
+
// `matchAll` always sets the index - older TypeScript versions type it as optional
|
|
61
|
+
const { index = 0 } = match;
|
|
62
|
+
messages.push(pending.slice(start, index));
|
|
63
|
+
start = index + match[0].length;
|
|
64
|
+
});
|
|
65
|
+
if (messages.length > 0) {
|
|
66
|
+
discardLeadingLineFeed = start === pending.length && pending.endsWith("\r");
|
|
67
|
+
}
|
|
68
|
+
pending = pending.slice(start);
|
|
69
|
+
|
|
70
|
+
messages.forEach((message) => onMessage(decodeEventStreamMessage(message)));
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** The same as oRPC - a stream that stops in the middle of a message is broken */
|
|
74
|
+
const end = () => {
|
|
75
|
+
if (pending !== "") {
|
|
76
|
+
throw new Error("The event stream ended before the last message was complete");
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
return { feed, end };
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Maps a message to the event of the server iterator, the same as `toEventIterator` of oRPC. Messages without an
|
|
85
|
+
* event and data are keep-alive pings and return `null`. Throws when the data is not JSON.
|
|
86
|
+
*/
|
|
87
|
+
export const getEventStreamIteratorEvent = (message: OrpcEventStreamMessageType): OrpcIteratorEventType | null => {
|
|
88
|
+
const event = message.event ?? (message.data !== undefined ? "message" : undefined);
|
|
89
|
+
const meta = { id: message.id, retry: message.retry };
|
|
90
|
+
|
|
91
|
+
if (event === "message" || event === "error") {
|
|
92
|
+
return { event, data: message.data ? JSON.parse(message.data) : undefined, meta };
|
|
93
|
+
}
|
|
94
|
+
if (event === "done" || event === "close") {
|
|
95
|
+
return { event: "done", data: undefined, meta };
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
};
|