@hyper-fetch/sockets 9.6.0 → 9.6.2
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/__tests__/e2e/e2e.lifecycle.spec.ts +258 -0
- package/__tests__/features/adapter/adapter.connection.spec.ts +63 -6
- package/__tests__/features/adapter/adapter.sse.connection.spec.ts +45 -0
- package/__tests__/features/adapter/adapter.sse.lifecycle.spec.ts +514 -0
- package/__tests__/features/adapter/adapter.sse.spec.ts +20 -6
- package/__tests__/features/adapter/adapter.websocket.heartbeat.timers.spec.ts +337 -0
- package/__tests__/features/adapter/adapter.websocket.lifecycle.spec.ts +528 -0
- package/__tests__/features/adapter/adapter.websocket.reconnection.spec.ts +669 -0
- package/__tests__/features/delivery/delivery.backpressure.spec.ts +382 -0
- package/__tests__/features/emitter/emitter.sending.spec.ts +493 -0
- package/__tests__/features/emitter/emitter.typescript.spec.ts +153 -0
- package/__tests__/features/listener/listener.dispatch.spec.ts +427 -0
- package/__tests__/features/listener/listener.params.spec.ts +192 -0
- package/__tests__/features/socket/socket.app-manager.spec.ts +24 -2
- package/__tests__/features/socket/socket.interceptors.spec.ts +430 -0
- package/__tests__/utils/controlled-event-source.ts +149 -0
- package/__tests__/utils/controlled-websocket.ts +213 -0
- package/dist/adapter/adapter.bindings.d.ts.map +1 -1
- package/dist/adapter/adapter.d.ts.map +1 -1
- package/dist/adapter-sse/sse-adapter.d.ts.map +1 -1
- package/dist/adapter-websockets/websocket-adapter.d.ts.map +1 -1
- package/dist/emitter/emitter.d.ts.map +1 -1
- package/dist/index.mjs +289 -105
- package/dist/index.mjs.map +1 -1
- package/dist/listener/listener.d.ts +2 -0
- package/dist/listener/listener.d.ts.map +1 -1
- package/dist/socket/socket.d.ts +1 -1
- package/dist/socket/socket.utils.d.ts +11 -3
- package/dist/socket/socket.utils.d.ts.map +1 -1
- package/dist/utils/topic.utils.d.ts +10 -0
- package/dist/utils/topic.utils.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/adapter/adapter.bindings.ts +44 -20
- package/src/adapter/adapter.ts +29 -10
- package/src/adapter-sse/sse-adapter.ts +101 -13
- package/src/adapter-websockets/websocket-adapter.ts +126 -41
- package/src/emitter/emitter.ts +16 -9
- package/src/listener/listener.ts +7 -8
- package/src/socket/socket.utils.ts +20 -6
- package/src/utils/topic.utils.ts +26 -0
|
@@ -22,6 +22,8 @@ export declare class Listener<Response, Topic extends string, Socket extends Soc
|
|
|
22
22
|
delivery?: ListenerDeliveryType<any, ExtractSocketAdapterType<Socket>>;
|
|
23
23
|
/** Stored with an `any` response for the same covariance reason as `delivery`. */
|
|
24
24
|
readonly listenerOptions: ListenerOptionsType<Topic, ExtractSocketAdapterType<Socket>>;
|
|
25
|
+
/** Topic as it was declared (e.g. `chat/:roomId`) - clones keep it, so params can be set again */
|
|
26
|
+
private topicTemplate;
|
|
25
27
|
constructor(socket: Socket, listenerOptions: ListenerOptionsType<Topic, ExtractSocketAdapterType<Socket>, Response>);
|
|
26
28
|
/** Set adapter-specific listener options. */
|
|
27
29
|
setOptions(options: ExtractAdapterListenerOptionsType<ExtractSocketAdapterType<Socket>>): Listener<Response, Topic, Socket, HasParams, Delivered>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listener.d.ts","sourceRoot":"","sources":["../../src/listener/listener.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,KAAK,EAA+B,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAExG,OAAO,KAAK,EAAE,UAAU,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAC3F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,KAAK,EAAE,iCAAiC,EAAE,wBAAwB,EAAE,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"listener.d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;IAIvF,sEAAsE;IACtE,SAAS,CAAC,MAAM,EAAE,gBAAgB,CAAC,KAAK,CAAC;IAIzC;;;OAGG;IACH,WAAW,CAAC,WAAW,SAAS,oBAAoB,CAAC,QAAQ,EAAE,wBAAwB,CAAC,MAAM,CAAC,CAAC,GAAG,SAAS,EAC1G,QAAQ,EAAE,WAAW;IAKvB,4EAA4E;IAC5E,KAAK,CAAC,YAAY,SAAS,IAAI,GAAG,KAAK,GAAG,SAAS,EAAE,YAAY,GAAG,SAAS,EAC3E,OAAO,CAAC,EAAE,yBAAyB,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC;IAYvF,+FAA+F;IAC/F,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,MAAM,CAAC,CAoBjF;IAEF,OAAO,CAAC,YAAY,CAElB;CACH"}
|
package/dist/socket/socket.d.ts
CHANGED
|
@@ -206,7 +206,7 @@ export declare class Socket<Adapter extends SocketAdapterInstance = WebsocketAda
|
|
|
206
206
|
extra: ExtractAdapterExtraType<Adapter>;
|
|
207
207
|
}) => {
|
|
208
208
|
data: any;
|
|
209
|
-
extra:
|
|
209
|
+
extra: ExtractAdapterExtraType<Adapter>;
|
|
210
210
|
};
|
|
211
211
|
/**
|
|
212
212
|
* ********************
|
|
@@ -15,13 +15,21 @@ export declare const getListenerRemoveByTopicKey: (event: string) => string;
|
|
|
15
15
|
export declare const getListenerEventByTopicKey: (event: string) => string;
|
|
16
16
|
export declare const getEmitterStartEventByTopicKey: (event: string) => string;
|
|
17
17
|
export declare const getEmitterErrorByTopicKey: (event: string) => string;
|
|
18
|
-
|
|
18
|
+
/**
|
|
19
|
+
* Runs the `onMessage` interceptors over the data of an incoming message. Every interceptor receives the data
|
|
20
|
+
* returned by the previous one - the adapter `extra` is never touched.
|
|
21
|
+
*/
|
|
22
|
+
export declare const interceptListener: <Extra = any>(interceptors: MessageCallbackType<any>[], event: {
|
|
19
23
|
data: any;
|
|
20
|
-
extra:
|
|
24
|
+
extra: Extra;
|
|
21
25
|
}) => {
|
|
22
26
|
data: any;
|
|
23
|
-
extra:
|
|
27
|
+
extra: Extra;
|
|
24
28
|
};
|
|
29
|
+
/**
|
|
30
|
+
* Runs the `onSend` interceptors over an emitter. Every interceptor receives the emitter
|
|
31
|
+
* returned by the previous one.
|
|
32
|
+
*/
|
|
25
33
|
export declare const interceptEmitter: <EmitterType extends EmitterInstance>(interceptors: SendCallbackType<EmitterType>[], emitter: EmitterType) => EmitterType;
|
|
26
34
|
export declare const interceptConnection: <Adapter extends SocketAdapterInstance>(interceptors: ConnectCallbackType<Adapter>[], data: {
|
|
27
35
|
connection: SocketConnectionType<Adapter>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socket.utils.d.ts","sourceRoot":"","sources":["../../src/socket/socket.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEvH,eAAO,MAAM,WAAW,cAAuB,CAAC;AAChD,eAAO,MAAM,UAAU,cAAsB,CAAC;AAC9C,eAAO,MAAM,WAAW,cAAuB,CAAC;AAChD,eAAO,MAAM,gBAAgB,cAA4B,CAAC;AAC1D,eAAO,MAAM,kBAAkB,cAA8B,CAAC;AAC9D,eAAO,MAAM,wBAAwB,cAAmC,CAAC;AACzE,eAAO,MAAM,mBAAmB,cAAyB,CAAC;AAC1D,eAAO,MAAM,oBAAoB,cAA0B,CAAC;AAC5D,eAAO,MAAM,uBAAuB,cAA8B,CAAC;AACnE,eAAO,MAAM,kBAAkB,cAAwB,CAAC;AACx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F;;;GAGG;AACH,eAAO,MAAM,iBAAiB,GAAI,KAAK,GAAG,GAAG,EAC3C,cAAc,mBAAmB,CAAC,GAAG,CAAC,EAAE,EACxC,OAAO;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,KACjC;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAc3B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,GAAI,WAAW,SAAS,eAAe,EAClE,cAAc,gBAAgB,CAAC,WAAW,CAAC,EAAE,EAC7C,SAAS,WAAW,gBAWrB,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAAU,OAAO,SAAS,qBAAqB,EAC7E,cAAc,mBAAmB,CAAC,OAAO,CAAC,EAAE,EAC5C,MAAM;IAAE,UAAU,EAAE,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,KACnE,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAYvC,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { ParamsType } from '@hyper-fetch/core';
|
|
2
|
+
/**
|
|
3
|
+
* Fills the `:param` segments of a topic template, e.g. `chat/:roomId` + `{ roomId: 1 }` gives `chat/1`.
|
|
4
|
+
*
|
|
5
|
+
* Every `:` segment is replaced once, with the longest matching name. This way `:id` does not eat the beginning
|
|
6
|
+
* of `:idx`, and a value is never parsed again - neither as another param nor as a replacement pattern like `$&`.
|
|
7
|
+
* Segments without a matching param are left untouched.
|
|
8
|
+
*/
|
|
9
|
+
export declare const mapTopicParams: (topic: string, params: ParamsType | null | undefined) => string;
|
|
10
|
+
//# sourceMappingURL=topic.utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"topic.utils.d.ts","sourceRoot":"","sources":["../../src/utils/topic.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,MAAM,EAAE,QAAQ,UAAU,GAAG,IAAI,GAAG,SAAS,KAAG,MAgBrF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyper-fetch/sockets",
|
|
3
|
-
"version": "9.6.
|
|
3
|
+
"version": "9.6.2",
|
|
4
4
|
"description": "Sockets connection for hyper-fetch",
|
|
5
5
|
"author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
|
|
6
6
|
"homepage": "https://hyperfetch.bettertyped.com/",
|
|
@@ -64,9 +64,10 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
|
|
|
64
64
|
connectionId += 1;
|
|
65
65
|
const currentConnectionId = connectionId;
|
|
66
66
|
|
|
67
|
+
// The attempts counter is kept on purpose - it is reset only by a successful connection (onConnected)
|
|
68
|
+
// or a disconnect, so attempts that never open (e.g. a hanging handshake) still count towards the limit
|
|
67
69
|
socket.adapter.setForceClosed(false);
|
|
68
70
|
socket.adapter.setConnecting(true);
|
|
69
|
-
socket.adapter.setReconnectionAttempts(0);
|
|
70
71
|
socket.events.emitConnecting({ connecting: true });
|
|
71
72
|
|
|
72
73
|
const defaults: SocketConnectionType<T> = {
|
|
@@ -133,10 +134,6 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
|
|
|
133
134
|
extra: { reconnectionAttempts: nextAttempts },
|
|
134
135
|
});
|
|
135
136
|
await connect();
|
|
136
|
-
// Restore only if the connection didn't succeed — onConnected resets to 0 on success
|
|
137
|
-
if (!adapter.connected) {
|
|
138
|
-
socket.adapter.setReconnectionAttempts(nextAttempts);
|
|
139
|
-
}
|
|
140
137
|
return true;
|
|
141
138
|
}
|
|
142
139
|
|
|
@@ -175,25 +172,40 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
|
|
|
175
172
|
|
|
176
173
|
// Emitters
|
|
177
174
|
|
|
175
|
+
const onEmitError = <ErrorType extends Error>({ emitter, error }: { emitter: EmitterInstance; error: ErrorType }) => {
|
|
176
|
+
socket.events.emitEmitterError({ error, emitter });
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Prepares an emitter for sending - maps the payload and runs the `onSend` interceptors.
|
|
181
|
+
* Returns `null` when the message cannot be sent; the reason is reported with the emitter error event
|
|
182
|
+
* (and to the `onError` callbacks when the payload mapper or an interceptor failed), it never rejects.
|
|
183
|
+
*/
|
|
178
184
|
const onEmit = async ({ emitter }: { emitter: EmitterInstance }): Promise<EmitterInstance | null> => {
|
|
179
185
|
if (adapter.connecting || !adapter.connected) {
|
|
180
|
-
|
|
186
|
+
const error = new Error("Cannot emit event when connection is not open");
|
|
187
|
+
logger.error({ title: error.message, type: "system", extra: {} });
|
|
188
|
+
onEmitError({ emitter, error });
|
|
181
189
|
return null;
|
|
182
190
|
}
|
|
183
191
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
192
|
+
try {
|
|
193
|
+
// eslint-disable-next-line no-param-reassign
|
|
194
|
+
emitter.payload = emitter.unstable_payloadMapper
|
|
195
|
+
? await emitter.unstable_payloadMapper(emitter.payload)
|
|
196
|
+
: emitter.payload;
|
|
188
197
|
|
|
189
|
-
|
|
190
|
-
|
|
198
|
+
const emitterInstance = await socket.unstable__modifySend(emitter);
|
|
199
|
+
socket.events.emitEmitterStartEvent({ emitter: emitterInstance });
|
|
191
200
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
201
|
+
return emitterInstance;
|
|
202
|
+
} catch (error) {
|
|
203
|
+
const emitError = error instanceof Error ? error : new Error(String(error));
|
|
204
|
+
logger.error({ title: "Cannot prepare event to emit", type: "system", extra: { error: emitError } });
|
|
205
|
+
onEmitError({ emitter, error: emitError });
|
|
206
|
+
onError({ error: emitError });
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
197
209
|
};
|
|
198
210
|
|
|
199
211
|
// Lifecycle
|
|
@@ -224,9 +236,21 @@ export const getAdapterBindings = <T extends SocketAdapterInstance>(socket: Sock
|
|
|
224
236
|
const onEvent = ({ topic, data, extra }: { topic: string; data: any; extra: ExtractAdapterExtraType<T> }) => {
|
|
225
237
|
logger.info({ title: "New event message", type: "system", extra: { topic, data, extra } });
|
|
226
238
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
239
|
+
let message: { data: any; extra: ExtractAdapterExtraType<T> };
|
|
240
|
+
try {
|
|
241
|
+
message = socket.unstable__modifyResponse({ data, extra });
|
|
242
|
+
} catch (error) {
|
|
243
|
+
// A failing `onMessage` interceptor must not break the transport - skip the message and report it
|
|
244
|
+
onError({ error: error instanceof Error ? error : new Error(String(error)) });
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
try {
|
|
249
|
+
socket.adapter.triggerListeners({ topic, data: message.data, extra: message.extra });
|
|
250
|
+
} finally {
|
|
251
|
+
// Devtools and global subscriptions receive the message even when a listener callback throws
|
|
252
|
+
socket.events.emitListenerEvent({ topic, data: message.data, extra: message.extra });
|
|
253
|
+
}
|
|
230
254
|
};
|
|
231
255
|
|
|
232
256
|
/** Maps query params to the format required by the adapter (defaults to the adapter's stored query params) */
|
package/src/adapter/adapter.ts
CHANGED
|
@@ -169,14 +169,15 @@ export class SocketAdapter<
|
|
|
169
169
|
>;
|
|
170
170
|
}): boolean => {
|
|
171
171
|
const listenerGroup = this.listeners.get(topic);
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
listenerGroup.delete(callback);
|
|
176
|
-
unmount?.();
|
|
177
|
-
return true;
|
|
172
|
+
// Removing a callback that is not registered (anymore) is a no-op - the remove event fires once per listener
|
|
173
|
+
if (!listenerGroup?.has(callback)) {
|
|
174
|
+
return false;
|
|
178
175
|
}
|
|
179
|
-
|
|
176
|
+
const unmount = listenerGroup.get(callback);
|
|
177
|
+
listenerGroup.delete(callback);
|
|
178
|
+
this.socket.events.emitListenerRemoveEvent({ topic });
|
|
179
|
+
unmount?.();
|
|
180
|
+
return true;
|
|
180
181
|
};
|
|
181
182
|
|
|
182
183
|
public triggerListeners = ({
|
|
@@ -191,10 +192,28 @@ export class SocketAdapter<
|
|
|
191
192
|
>;
|
|
192
193
|
}) => {
|
|
193
194
|
const listenerGroup = this.listeners.get(topic);
|
|
194
|
-
if (listenerGroup) {
|
|
195
|
-
|
|
195
|
+
if (!listenerGroup?.size) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Dispatch to the listeners registered when the message arrived: the ones added by a callback wait for the
|
|
200
|
+
// next message, the ones removed by a callback are skipped.
|
|
201
|
+
const callbacks = [...listenerGroup.keys()];
|
|
202
|
+
const errors: unknown[] = [];
|
|
203
|
+
callbacks.forEach((action) => {
|
|
204
|
+
if (!listenerGroup.has(action)) {
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
196
208
|
action({ data, extra: extra as ExtractAdapterExtraType<this> });
|
|
197
|
-
})
|
|
209
|
+
} catch (error) {
|
|
210
|
+
// One failing callback must not starve the other listeners of the topic
|
|
211
|
+
errors.push(error);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
if (errors.length > 0) {
|
|
216
|
+
throw errors[0];
|
|
198
217
|
}
|
|
199
218
|
};
|
|
200
219
|
|
|
@@ -53,7 +53,12 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
|
|
|
53
53
|
onError,
|
|
54
54
|
onEvent,
|
|
55
55
|
}) => {
|
|
56
|
+
// The transport in use. Events of any other instance (replaced or closed on purpose) are ignored.
|
|
56
57
|
let sse: ReturnType<typeof getServerSentEventsAdapter> | undefined;
|
|
58
|
+
// Connection attempt in progress - concurrent `connect()` calls join it
|
|
59
|
+
let pendingConnection: Promise<boolean> | undefined;
|
|
60
|
+
// Connection timeout while connecting, reconnection delay after the connection was lost
|
|
61
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
57
62
|
|
|
58
63
|
const autoConnect =
|
|
59
64
|
typeof socket.adapter.adapterOptions?.autoConnect === "boolean"
|
|
@@ -77,45 +82,75 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
|
|
|
77
82
|
}
|
|
78
83
|
};
|
|
79
84
|
|
|
80
|
-
const
|
|
85
|
+
const scheduleReconnect = () => {
|
|
86
|
+
clearTimeout(timeout);
|
|
87
|
+
timeout = setTimeout(() => {
|
|
88
|
+
reconnect();
|
|
89
|
+
}, socket.reconnectTime);
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const openConnection = async (): Promise<boolean> => {
|
|
81
93
|
const connection = await onConnect();
|
|
82
94
|
if (!connection) {
|
|
83
95
|
return socket.adapter.connected;
|
|
84
96
|
}
|
|
85
97
|
|
|
98
|
+
clearTimeout(timeout);
|
|
86
99
|
sse?.clearListeners();
|
|
87
100
|
sse?.close();
|
|
88
101
|
|
|
89
102
|
const url = getSocketUrl(connection.url, getQueryParams(connection.queryParams));
|
|
90
103
|
const eventSource = createEventSource(url, connection.adapterOptions);
|
|
91
|
-
sse = eventSource;
|
|
104
|
+
sse = eventSource ?? undefined;
|
|
92
105
|
|
|
93
106
|
if (!eventSource) {
|
|
94
107
|
return false;
|
|
95
108
|
}
|
|
96
109
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
110
|
+
const isCurrent = () => sse === eventSource;
|
|
111
|
+
|
|
112
|
+
// Connection timeout - when the server does not answer in time, start over
|
|
113
|
+
scheduleReconnect();
|
|
101
114
|
|
|
102
115
|
/**
|
|
103
116
|
* Mount listeners
|
|
104
117
|
*/
|
|
105
118
|
|
|
106
119
|
eventSource.addEventListener("open", () => {
|
|
120
|
+
if (!isCurrent()) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
107
123
|
clearTimeout(timeout);
|
|
108
124
|
onConnected();
|
|
109
125
|
});
|
|
110
126
|
|
|
111
127
|
eventSource.addEventListener("error", (event) => {
|
|
128
|
+
if (!isCurrent()) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
112
131
|
const error = getSocketError(event);
|
|
113
132
|
|
|
114
133
|
onError({ error: new Error(error) });
|
|
134
|
+
|
|
135
|
+
// An open stream broke. The browser either retries on its own (CONNECTING) or gives up (CLOSED) -
|
|
136
|
+
// in both cases the socket is not connected anymore. The timeout takes over when the stream
|
|
137
|
+
// does not come back in time, the same way it guards the initial connection.
|
|
138
|
+
const isLost = adapter.connected && eventSource.readyState !== EventSource.OPEN;
|
|
139
|
+
if (isLost) {
|
|
140
|
+
onDisconnected();
|
|
141
|
+
if (eventSource.readyState === EventSource.CONNECTING) {
|
|
142
|
+
adapter.setConnecting(true);
|
|
143
|
+
socket.events.emitConnecting({ connecting: true });
|
|
144
|
+
}
|
|
145
|
+
scheduleReconnect();
|
|
146
|
+
}
|
|
115
147
|
});
|
|
116
148
|
|
|
117
149
|
const { decode } = connection.adapterOptions || {};
|
|
118
150
|
eventSource.addEventListener("message", (newEvent: MessageEvent<SocketData>) => {
|
|
151
|
+
if (!isCurrent()) {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
119
154
|
const message = decodeMessage(newEvent, decode);
|
|
120
155
|
if (message) {
|
|
121
156
|
onEvent({ topic: message.topic, data: message.data, extra: newEvent });
|
|
@@ -124,6 +159,8 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
|
|
|
124
159
|
|
|
125
160
|
return new Promise((resolve) => {
|
|
126
161
|
if (eventSource.readyState === EventSource.OPEN) {
|
|
162
|
+
// No open event follows, so the attempt timeout would reconnect a working connection
|
|
163
|
+
clearTimeout(timeout);
|
|
127
164
|
resolve(true);
|
|
128
165
|
adapter.setConnected(true);
|
|
129
166
|
adapter.setConnecting(false);
|
|
@@ -145,25 +182,73 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
|
|
|
145
182
|
});
|
|
146
183
|
};
|
|
147
184
|
|
|
148
|
-
const
|
|
185
|
+
const connect = (): Promise<boolean> => {
|
|
186
|
+
// Another attempt is already on its way (e.g. the automatic one) - resolve together with it
|
|
187
|
+
if (adapter.connecting && pendingConnection) {
|
|
188
|
+
return pendingConnection;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const connection = openConnection();
|
|
192
|
+
pendingConnection = connection;
|
|
193
|
+
const release = () => {
|
|
194
|
+
if (pendingConnection === connection) {
|
|
195
|
+
pendingConnection = undefined;
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
connection.then(release, release);
|
|
199
|
+
|
|
200
|
+
return connection;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Closes the transport and resets the connection state. From this point the closed transport is detached -
|
|
205
|
+
* whatever it reports later does not reach the socket anymore.
|
|
206
|
+
*/
|
|
207
|
+
const closeConnection = async ({ manual }: { manual: boolean }): Promise<boolean> => {
|
|
208
|
+
clearTimeout(timeout);
|
|
209
|
+
|
|
149
210
|
const currentSse = sse;
|
|
211
|
+
sse = undefined;
|
|
150
212
|
const hasTransport = currentSse && currentSse.readyState !== EventSource.CLOSED;
|
|
151
213
|
|
|
152
214
|
// When there is nothing to close, only a connection attempt may still be preparing (onConnect) - cancel it
|
|
153
|
-
const
|
|
215
|
+
const wasActive = adapter.connected || adapter.connecting;
|
|
154
216
|
onDisconnect();
|
|
217
|
+
if (!manual) {
|
|
218
|
+
// Closing the previous transport is a part of reconnecting - only `disconnect()` keeps the socket closed
|
|
219
|
+
adapter.setForceClosed(false);
|
|
220
|
+
}
|
|
155
221
|
if (hasTransport) {
|
|
222
|
+
currentSse.clearListeners();
|
|
156
223
|
currentSse.close();
|
|
157
224
|
}
|
|
158
|
-
if (hasTransport ||
|
|
225
|
+
if (hasTransport || wasActive) {
|
|
159
226
|
onDisconnected();
|
|
160
227
|
}
|
|
161
228
|
|
|
162
229
|
return true;
|
|
163
230
|
};
|
|
164
231
|
|
|
165
|
-
|
|
166
|
-
|
|
232
|
+
/** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */
|
|
233
|
+
const disconnect = (): Promise<boolean> => {
|
|
234
|
+
return closeConnection({ manual: true });
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const reconnect = async () => {
|
|
238
|
+
// Reconnecting is a request to be connected, also after a manual disconnect
|
|
239
|
+
adapter.setForceClosed(false);
|
|
240
|
+
|
|
241
|
+
await onReconnect({
|
|
242
|
+
disconnect: () => closeConnection({ manual: false }),
|
|
243
|
+
connect: async () => {
|
|
244
|
+
// `disconnect()` called in the meantime wins over the reconnection
|
|
245
|
+
if (adapter.forceClosed) {
|
|
246
|
+
adapter.setReconnectionAttempts(0);
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
return connect();
|
|
250
|
+
},
|
|
251
|
+
});
|
|
167
252
|
};
|
|
168
253
|
|
|
169
254
|
/** Creates the transport, reporting a failed attempt when the environment or the connection details are invalid */
|
|
@@ -187,7 +272,9 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
|
|
|
187
272
|
return onListen({ listener, callback });
|
|
188
273
|
};
|
|
189
274
|
|
|
190
|
-
|
|
275
|
+
// Server-Sent Events are receive-only. Throwing synchronously makes `emitter.emit()` fail right at the
|
|
276
|
+
// call site instead of leaving a rejected promise nobody awaits.
|
|
277
|
+
const emit = () => {
|
|
191
278
|
throw new Error("Cannot emit events in SSE adapter");
|
|
192
279
|
};
|
|
193
280
|
|
|
@@ -197,7 +284,8 @@ export const ServerSentEventsAdapter = (): ServerSentEventsAdapterType =>
|
|
|
197
284
|
}
|
|
198
285
|
|
|
199
286
|
socket.appManager.events.onOnline(() => {
|
|
200
|
-
|
|
287
|
+
// A socket disconnected on purpose stays closed until `connect()` or `reconnect()` is called
|
|
288
|
+
if (autoConnect && !adapter.connected && !adapter.forceClosed) {
|
|
201
289
|
connect();
|
|
202
290
|
}
|
|
203
291
|
});
|