@forgeax/engine-net-websocket 0.0.0-dev.8d955ade1c79
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/LICENSE +202 -0
- package/README.md +153 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/browser.d.ts +20 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.mjs +261 -0
- package/dist/browser.mjs.map +1 -0
- package/dist/event-queue.d.ts +13 -0
- package/dist/event-queue.d.ts.map +1 -0
- package/dist/node.d.ts +30 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.mjs +409 -0
- package/dist/node.mjs.map +1 -0
- package/dist/websocket-client-core.d.ts +30 -0
- package/dist/websocket-client-core.d.ts.map +1 -0
- package/dist/websocket-connector.d.ts +11 -0
- package/dist/websocket-connector.d.ts.map +1 -0
- package/package.json +64 -0
- package/src/browser.ts +48 -0
- package/src/event-queue.ts +43 -0
- package/src/node.ts +224 -0
- package/src/websocket-client-core.ts +237 -0
- package/src/websocket-connector.ts +35 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { EndpointEvent } from '@forgeax/engine-net';
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_MAX_QUEUED_EVENTS = 1024;
|
|
4
|
+
|
|
5
|
+
export class BoundedEventQueue {
|
|
6
|
+
readonly #events: EndpointEvent[] = [];
|
|
7
|
+
#closed = false;
|
|
8
|
+
#disconnectReason: string | undefined;
|
|
9
|
+
|
|
10
|
+
constructor(readonly maxQueuedEvents: number) {
|
|
11
|
+
if (!Number.isInteger(maxQueuedEvents) || maxQueuedEvents < 1) {
|
|
12
|
+
throw new RangeError('maxQueuedEvents must be a positive integer');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
get closed(): boolean {
|
|
17
|
+
return this.#closed;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
get disconnectReason(): string | undefined {
|
|
21
|
+
return this.#disconnectReason;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
enqueue(event: EndpointEvent): boolean {
|
|
25
|
+
if (this.#closed) return false;
|
|
26
|
+
if (this.#events.length === this.maxQueuedEvents) {
|
|
27
|
+
this.close(`event queue overflow (maxQueuedEvents=${this.maxQueuedEvents})`);
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
this.#events.push(event);
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
close(reason: string): void {
|
|
35
|
+
if (this.#closed) return;
|
|
36
|
+
this.#closed = true;
|
|
37
|
+
this.#disconnectReason = reason;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
drain(): EndpointEvent[] {
|
|
41
|
+
return this.#events.splice(0);
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/node.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ENDPOINT_ERROR_HINTS,
|
|
3
|
+
ENDPOINT_EXPECTED,
|
|
4
|
+
EndpointError,
|
|
5
|
+
type EndpointEvent,
|
|
6
|
+
type NetEndpoint,
|
|
7
|
+
type PeerId,
|
|
8
|
+
} from '@forgeax/engine-net';
|
|
9
|
+
import { err, ok, type Result } from '@forgeax/engine-types';
|
|
10
|
+
import WebSocket, { WebSocketServer } from 'ws';
|
|
11
|
+
import { BoundedEventQueue, DEFAULT_MAX_QUEUED_EVENTS } from './event-queue';
|
|
12
|
+
import type { WebSocketConstructor } from './websocket-client-core';
|
|
13
|
+
import { createWebSocketConnectorAdapter } from './websocket-connector';
|
|
14
|
+
|
|
15
|
+
export interface ListenWebSocketEndpointOptions {
|
|
16
|
+
readonly port: number;
|
|
17
|
+
readonly host?: string;
|
|
18
|
+
readonly maxPeers?: number;
|
|
19
|
+
readonly maxQueuedEvents?: number | undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ConnectWebSocketClientEndpointOptions {
|
|
23
|
+
readonly maxQueuedEvents?: number | undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Creates the Node WebSocket adapter for the public NetEndpointConnector.
|
|
28
|
+
* Each connect call accepts an AbortSignal and creates one replacement-capable
|
|
29
|
+
* NetEndpoint. Transport lifecycle and EndpointError results stay here;
|
|
30
|
+
* authoritative resync and replication policy stay with NetSession.
|
|
31
|
+
*/
|
|
32
|
+
export function createWebSocketConnector(
|
|
33
|
+
url: string,
|
|
34
|
+
options: ConnectWebSocketClientEndpointOptions = {},
|
|
35
|
+
): import('@forgeax/engine-net').NetEndpointConnector {
|
|
36
|
+
return createWebSocketConnectorAdapter(
|
|
37
|
+
{
|
|
38
|
+
WebSocket: WebSocket as unknown as WebSocketConstructor,
|
|
39
|
+
toBytes,
|
|
40
|
+
},
|
|
41
|
+
url,
|
|
42
|
+
options,
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Connects one Node WebSocket with the default one-shot AbortSignal.
|
|
48
|
+
* Use createWebSocketConnector when the caller must cancel or replace an
|
|
49
|
+
* endpoint through an explicit signal.
|
|
50
|
+
*/
|
|
51
|
+
export function connectWebSocketClientEndpoint(
|
|
52
|
+
url: string,
|
|
53
|
+
options: ConnectWebSocketClientEndpointOptions = {},
|
|
54
|
+
): Promise<Result<NetEndpoint, EndpointError>> {
|
|
55
|
+
return createWebSocketConnector(url, options).connect(new AbortController().signal);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Starts a Node WebSocket listener that exposes NetEndpoint peer events and
|
|
60
|
+
* binary messages without owning NetSession or replication policy.
|
|
61
|
+
*/
|
|
62
|
+
export function listenWebSocketEndpoint(
|
|
63
|
+
options: ListenWebSocketEndpointOptions,
|
|
64
|
+
): Promise<Result<NetEndpoint, EndpointError>> {
|
|
65
|
+
return new Promise((resolve) => {
|
|
66
|
+
const host = options.host ?? '127.0.0.1';
|
|
67
|
+
const address = `ws://${host}:${options.port}`;
|
|
68
|
+
let queue: BoundedEventQueue;
|
|
69
|
+
try {
|
|
70
|
+
queue = new BoundedEventQueue(options.maxQueuedEvents ?? DEFAULT_MAX_QUEUED_EVENTS);
|
|
71
|
+
} catch (cause) {
|
|
72
|
+
resolve(connectionFailed(address, cause));
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const terminalEvents: EndpointEvent[] = [];
|
|
77
|
+
const peers = new Map<PeerId, WebSocket>();
|
|
78
|
+
const disconnectedPeers = new Set<PeerId>();
|
|
79
|
+
const sockets = new Map<WebSocket, PeerId>();
|
|
80
|
+
const maxPeers = options.maxPeers ?? Number.POSITIVE_INFINITY;
|
|
81
|
+
let nextPeerId = 1;
|
|
82
|
+
let settled = false;
|
|
83
|
+
let closed = false;
|
|
84
|
+
const server = new WebSocketServer({ host, port: options.port, perMessageDeflate: false });
|
|
85
|
+
|
|
86
|
+
const endpoint: NetEndpoint = {
|
|
87
|
+
poll: () => [...queue.drain(), ...terminalEvents.splice(0)],
|
|
88
|
+
send: (peerId, data) => {
|
|
89
|
+
if (closed) return alreadyClosed('The WebSocket listener endpoint is closed.');
|
|
90
|
+
const socket = peers.get(peerId);
|
|
91
|
+
if (!socket && disconnectedPeers.has(peerId))
|
|
92
|
+
return err(
|
|
93
|
+
new EndpointError({
|
|
94
|
+
code: 'connection-closed',
|
|
95
|
+
expected: ENDPOINT_EXPECTED['connection-closed'],
|
|
96
|
+
hint: ENDPOINT_ERROR_HINTS['connection-closed'],
|
|
97
|
+
detail: { peerId },
|
|
98
|
+
}),
|
|
99
|
+
);
|
|
100
|
+
if (!socket)
|
|
101
|
+
return err(
|
|
102
|
+
new EndpointError({
|
|
103
|
+
code: 'peer-not-found',
|
|
104
|
+
expected: ENDPOINT_EXPECTED['peer-not-found'],
|
|
105
|
+
hint: ENDPOINT_ERROR_HINTS['peer-not-found'],
|
|
106
|
+
detail: { peerId },
|
|
107
|
+
}),
|
|
108
|
+
);
|
|
109
|
+
if (socket.readyState !== socket.OPEN)
|
|
110
|
+
return err(
|
|
111
|
+
new EndpointError({
|
|
112
|
+
code: 'connection-closed',
|
|
113
|
+
expected: ENDPOINT_EXPECTED['connection-closed'],
|
|
114
|
+
hint: ENDPOINT_ERROR_HINTS['connection-closed'],
|
|
115
|
+
detail: { peerId },
|
|
116
|
+
}),
|
|
117
|
+
);
|
|
118
|
+
try {
|
|
119
|
+
socket.send(data, { binary: true });
|
|
120
|
+
return ok(undefined);
|
|
121
|
+
} catch (cause) {
|
|
122
|
+
return err(
|
|
123
|
+
new EndpointError({
|
|
124
|
+
code: 'send-failed',
|
|
125
|
+
expected: ENDPOINT_EXPECTED['send-failed'],
|
|
126
|
+
hint: ENDPOINT_ERROR_HINTS['send-failed'],
|
|
127
|
+
detail: { peerId, cause: normalizeCause(cause) },
|
|
128
|
+
}),
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
close: () => {
|
|
133
|
+
if (closed) return alreadyClosed('The WebSocket listener endpoint is already closed.');
|
|
134
|
+
closed = true;
|
|
135
|
+
for (const socket of peers.values()) socket.close();
|
|
136
|
+
server.close();
|
|
137
|
+
return ok(undefined);
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const enqueue = (event: EndpointEvent, socket?: WebSocket): void => {
|
|
142
|
+
if (queue.enqueue(event)) return;
|
|
143
|
+
if (event.kind !== 'peer-disconnected') {
|
|
144
|
+
terminalEvents.push({ kind: 'peer-disconnected', peerId: event.peerId });
|
|
145
|
+
}
|
|
146
|
+
socket?.close();
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
server.on('connection', (socket) => {
|
|
150
|
+
if (closed || peers.size >= maxPeers) {
|
|
151
|
+
socket.close();
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const peerId = nextPeerId++ as PeerId;
|
|
155
|
+
peers.set(peerId, socket);
|
|
156
|
+
sockets.set(socket, peerId);
|
|
157
|
+
enqueue({ kind: 'peer-connected', peerId }, socket);
|
|
158
|
+
socket.on('message', (data, isBinary) => {
|
|
159
|
+
if (!isBinary) {
|
|
160
|
+
socket.close();
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const bytes = toBytes(data);
|
|
164
|
+
if (!bytes) {
|
|
165
|
+
socket.close();
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
enqueue({ kind: 'message', peerId, data: bytes }, socket);
|
|
169
|
+
});
|
|
170
|
+
socket.on('close', () => {
|
|
171
|
+
if (!peers.delete(peerId)) return;
|
|
172
|
+
disconnectedPeers.add(peerId);
|
|
173
|
+
sockets.delete(socket);
|
|
174
|
+
enqueue({ kind: 'peer-disconnected', peerId });
|
|
175
|
+
});
|
|
176
|
+
socket.on('error', () => socket.close());
|
|
177
|
+
});
|
|
178
|
+
server.on('error', (cause) => {
|
|
179
|
+
if (settled) return;
|
|
180
|
+
settled = true;
|
|
181
|
+
resolve(connectionFailed(address, cause));
|
|
182
|
+
});
|
|
183
|
+
server.on('listening', () => {
|
|
184
|
+
if (settled) return;
|
|
185
|
+
settled = true;
|
|
186
|
+
resolve(ok(endpoint));
|
|
187
|
+
});
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function toBytes(data: unknown): Uint8Array | undefined {
|
|
192
|
+
if (data instanceof Uint8Array)
|
|
193
|
+
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
194
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function connectionFailed(address: string, cause: unknown): Result<never, EndpointError> {
|
|
199
|
+
return err(
|
|
200
|
+
new EndpointError({
|
|
201
|
+
code: 'connection-failed',
|
|
202
|
+
expected: ENDPOINT_EXPECTED['connection-failed'],
|
|
203
|
+
hint: ENDPOINT_ERROR_HINTS['connection-failed'],
|
|
204
|
+
detail: { address, cause: normalizeCause(cause) },
|
|
205
|
+
}),
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function alreadyClosed(cause: string): Result<never, EndpointError> {
|
|
210
|
+
return err(
|
|
211
|
+
new EndpointError({
|
|
212
|
+
code: 'already-closed',
|
|
213
|
+
expected: ENDPOINT_EXPECTED['already-closed'],
|
|
214
|
+
hint: ENDPOINT_ERROR_HINTS['already-closed'],
|
|
215
|
+
detail: { cause },
|
|
216
|
+
}),
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function normalizeCause(cause: unknown): string {
|
|
221
|
+
if (cause instanceof Error) return cause.message;
|
|
222
|
+
if (typeof cause === 'string') return cause;
|
|
223
|
+
return 'WebSocket operation failed without a platform error message.';
|
|
224
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ENDPOINT_ERROR_HINTS,
|
|
3
|
+
ENDPOINT_EXPECTED,
|
|
4
|
+
EndpointError,
|
|
5
|
+
type EndpointEvent,
|
|
6
|
+
type NetEndpoint,
|
|
7
|
+
type PeerId,
|
|
8
|
+
} from '@forgeax/engine-net';
|
|
9
|
+
import { err, ok, type Result } from '@forgeax/engine-types';
|
|
10
|
+
import { BoundedEventQueue, DEFAULT_MAX_QUEUED_EVENTS } from './event-queue';
|
|
11
|
+
|
|
12
|
+
export interface WebSocketLike {
|
|
13
|
+
readonly CONNECTING: number;
|
|
14
|
+
readonly OPEN: number;
|
|
15
|
+
readonly CLOSING: number;
|
|
16
|
+
readonly CLOSED: number;
|
|
17
|
+
readonly readyState: number;
|
|
18
|
+
binaryType?: string;
|
|
19
|
+
onopen: ((event: unknown) => void) | null;
|
|
20
|
+
onmessage: ((event: { data: unknown }) => void) | null;
|
|
21
|
+
onerror: ((event: unknown) => void) | null;
|
|
22
|
+
onclose: ((event: unknown) => void) | null;
|
|
23
|
+
send(data: Uint8Array): void;
|
|
24
|
+
close(): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface WebSocketConstructor {
|
|
28
|
+
new (url: string): WebSocketLike;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface WebSocketClientCoreOptions {
|
|
32
|
+
readonly url: string;
|
|
33
|
+
readonly maxQueuedEvents?: number | undefined;
|
|
34
|
+
readonly peerId?: PeerId;
|
|
35
|
+
readonly signal?: AbortSignal;
|
|
36
|
+
readonly toBytes: (data: unknown) => Uint8Array | Promise<Uint8Array | undefined> | undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const CLIENT_PEER_ID = 1 as PeerId;
|
|
40
|
+
|
|
41
|
+
export function createWebSocketClientEndpoint(
|
|
42
|
+
WebSocket: WebSocketConstructor,
|
|
43
|
+
options: WebSocketClientCoreOptions,
|
|
44
|
+
): Promise<Result<NetEndpoint, EndpointError>> {
|
|
45
|
+
return new Promise((resolve) => {
|
|
46
|
+
const clientPeerId = options.peerId ?? CLIENT_PEER_ID;
|
|
47
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
48
|
+
if (signal.aborted) {
|
|
49
|
+
resolve(connectionFailed(options.url, 'WebSocket connection aborted.'));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let queue: BoundedEventQueue;
|
|
54
|
+
try {
|
|
55
|
+
queue = new BoundedEventQueue(options.maxQueuedEvents ?? DEFAULT_MAX_QUEUED_EVENTS);
|
|
56
|
+
} catch (cause) {
|
|
57
|
+
resolve(connectionFailed(options.url, cause));
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let socket: WebSocketLike;
|
|
62
|
+
try {
|
|
63
|
+
socket = new WebSocket(options.url);
|
|
64
|
+
socket.binaryType = 'arraybuffer';
|
|
65
|
+
} catch (cause) {
|
|
66
|
+
resolve(connectionFailed(options.url, cause));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const terminalEvents: EndpointEvent[] = [];
|
|
71
|
+
let opened = false;
|
|
72
|
+
let settled = false;
|
|
73
|
+
let closed = false;
|
|
74
|
+
let locallyClosed = false;
|
|
75
|
+
let messageTail = Promise.resolve();
|
|
76
|
+
|
|
77
|
+
const removeAbortListener = (): void => {
|
|
78
|
+
signal.removeEventListener('abort', abortPendingConnection);
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const abortPendingConnection = (): void => {
|
|
82
|
+
if (opened || settled) return;
|
|
83
|
+
settled = true;
|
|
84
|
+
try {
|
|
85
|
+
socket.close();
|
|
86
|
+
} catch {
|
|
87
|
+
// Closing a partially opened platform socket is best effort.
|
|
88
|
+
}
|
|
89
|
+
removeAbortListener();
|
|
90
|
+
resolve(connectionFailed(options.url, 'WebSocket connection aborted.'));
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
signal.addEventListener('abort', abortPendingConnection, { once: true });
|
|
94
|
+
if (signal.aborted) {
|
|
95
|
+
abortPendingConnection();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const disconnect = (reason: string): void => {
|
|
100
|
+
if (closed) return;
|
|
101
|
+
closed = true;
|
|
102
|
+
queue.close(reason);
|
|
103
|
+
terminalEvents.push({ kind: 'peer-disconnected', peerId: clientPeerId });
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const endpoint: NetEndpoint = {
|
|
107
|
+
poll: () => [...queue.drain(), ...terminalEvents.splice(0)],
|
|
108
|
+
send: (peerId, data) => {
|
|
109
|
+
if (closed) return locallyClosed ? alreadyClosed() : connectionClosed(peerId);
|
|
110
|
+
if (peerId !== clientPeerId)
|
|
111
|
+
return err(
|
|
112
|
+
new EndpointError({
|
|
113
|
+
code: 'peer-not-found',
|
|
114
|
+
expected: ENDPOINT_EXPECTED['peer-not-found'],
|
|
115
|
+
hint: ENDPOINT_ERROR_HINTS['peer-not-found'],
|
|
116
|
+
detail: { peerId },
|
|
117
|
+
}),
|
|
118
|
+
);
|
|
119
|
+
if (socket.readyState !== socket.OPEN)
|
|
120
|
+
return err(
|
|
121
|
+
new EndpointError({
|
|
122
|
+
code: 'connection-closed',
|
|
123
|
+
expected: ENDPOINT_EXPECTED['connection-closed'],
|
|
124
|
+
hint: ENDPOINT_ERROR_HINTS['connection-closed'],
|
|
125
|
+
detail: { peerId },
|
|
126
|
+
}),
|
|
127
|
+
);
|
|
128
|
+
try {
|
|
129
|
+
socket.send(data);
|
|
130
|
+
return ok(undefined);
|
|
131
|
+
} catch (cause) {
|
|
132
|
+
return err(
|
|
133
|
+
new EndpointError({
|
|
134
|
+
code: 'send-failed',
|
|
135
|
+
expected: ENDPOINT_EXPECTED['send-failed'],
|
|
136
|
+
hint: ENDPOINT_ERROR_HINTS['send-failed'],
|
|
137
|
+
detail: { peerId, cause: normalizeCause(cause) },
|
|
138
|
+
}),
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
close: () => {
|
|
143
|
+
if (closed)
|
|
144
|
+
return err(
|
|
145
|
+
new EndpointError({
|
|
146
|
+
code: 'already-closed',
|
|
147
|
+
expected: ENDPOINT_EXPECTED['already-closed'],
|
|
148
|
+
hint: ENDPOINT_ERROR_HINTS['already-closed'],
|
|
149
|
+
detail: { cause: 'The WebSocket endpoint is already closed.' },
|
|
150
|
+
}),
|
|
151
|
+
);
|
|
152
|
+
locallyClosed = true;
|
|
153
|
+
disconnect('Endpoint close requested.');
|
|
154
|
+
socket.close();
|
|
155
|
+
return ok(undefined);
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
socket.onopen = () => {
|
|
160
|
+
if (settled) return;
|
|
161
|
+
removeAbortListener();
|
|
162
|
+
opened = true;
|
|
163
|
+
settled = true;
|
|
164
|
+
queue.enqueue({ kind: 'peer-connected', peerId: clientPeerId });
|
|
165
|
+
resolve(ok(endpoint));
|
|
166
|
+
};
|
|
167
|
+
socket.onmessage = ({ data }) => {
|
|
168
|
+
// Blob.arrayBuffer() is asynchronous. Serialize conversion so that
|
|
169
|
+
// ordered WebSocket messages retain their wire order after decoding.
|
|
170
|
+
messageTail = messageTail
|
|
171
|
+
.then(async () => {
|
|
172
|
+
const bytes = await options.toBytes(data);
|
|
173
|
+
if (!bytes || closed) return;
|
|
174
|
+
if (!queue.enqueue({ kind: 'message', peerId: clientPeerId, data: bytes })) {
|
|
175
|
+
socket.close();
|
|
176
|
+
}
|
|
177
|
+
})
|
|
178
|
+
.catch(() => undefined);
|
|
179
|
+
};
|
|
180
|
+
socket.onerror = (cause) => {
|
|
181
|
+
if (opened) disconnect(`WebSocket error: ${normalizeCause(cause)}`);
|
|
182
|
+
else if (!settled) {
|
|
183
|
+
settled = true;
|
|
184
|
+
removeAbortListener();
|
|
185
|
+
resolve(connectionFailed(options.url, cause));
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
socket.onclose = (cause) => {
|
|
189
|
+
if (!opened && !settled) {
|
|
190
|
+
settled = true;
|
|
191
|
+
removeAbortListener();
|
|
192
|
+
resolve(connectionFailed(options.url, cause));
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
disconnect(`WebSocket closed: ${normalizeCause(cause)}`);
|
|
196
|
+
};
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function connectionFailed(address: string, cause: unknown): Result<never, EndpointError> {
|
|
201
|
+
return err(
|
|
202
|
+
new EndpointError({
|
|
203
|
+
code: 'connection-failed',
|
|
204
|
+
expected: ENDPOINT_EXPECTED['connection-failed'],
|
|
205
|
+
hint: ENDPOINT_ERROR_HINTS['connection-failed'],
|
|
206
|
+
detail: { address, cause: normalizeCause(cause) },
|
|
207
|
+
}),
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function alreadyClosed(): Result<never, EndpointError> {
|
|
212
|
+
return err(
|
|
213
|
+
new EndpointError({
|
|
214
|
+
code: 'already-closed',
|
|
215
|
+
expected: ENDPOINT_EXPECTED['already-closed'],
|
|
216
|
+
hint: ENDPOINT_ERROR_HINTS['already-closed'],
|
|
217
|
+
detail: { cause: 'The WebSocket endpoint is closed.' },
|
|
218
|
+
}),
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function connectionClosed(peerId: PeerId): Result<never, EndpointError> {
|
|
223
|
+
return err(
|
|
224
|
+
new EndpointError({
|
|
225
|
+
code: 'connection-closed',
|
|
226
|
+
expected: ENDPOINT_EXPECTED['connection-closed'],
|
|
227
|
+
hint: ENDPOINT_ERROR_HINTS['connection-closed'],
|
|
228
|
+
detail: { peerId },
|
|
229
|
+
}),
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function normalizeCause(cause: unknown): string {
|
|
234
|
+
if (cause instanceof Error) return cause.message;
|
|
235
|
+
if (typeof cause === 'string') return cause;
|
|
236
|
+
return 'WebSocket operation failed without a platform error message.';
|
|
237
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { NetEndpointConnector, PeerId } from '@forgeax/engine-net';
|
|
2
|
+
import {
|
|
3
|
+
createWebSocketClientEndpoint,
|
|
4
|
+
type WebSocketClientCoreOptions,
|
|
5
|
+
type WebSocketConstructor,
|
|
6
|
+
} from './websocket-client-core';
|
|
7
|
+
|
|
8
|
+
export interface WebSocketConnectorOptions {
|
|
9
|
+
readonly maxQueuedEvents?: number | undefined;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface WebSocketConnectorRuntime {
|
|
13
|
+
readonly WebSocket: WebSocketConstructor;
|
|
14
|
+
readonly toBytes: WebSocketClientCoreOptions['toBytes'];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function createWebSocketConnectorAdapter(
|
|
18
|
+
runtime: WebSocketConnectorRuntime,
|
|
19
|
+
url: string,
|
|
20
|
+
options: WebSocketConnectorOptions = {},
|
|
21
|
+
): NetEndpointConnector {
|
|
22
|
+
let nextPeerId = 1;
|
|
23
|
+
return {
|
|
24
|
+
connect: (signal) => {
|
|
25
|
+
const peerId = nextPeerId++ as PeerId;
|
|
26
|
+
return createWebSocketClientEndpoint(runtime.WebSocket, {
|
|
27
|
+
url,
|
|
28
|
+
maxQueuedEvents: options.maxQueuedEvents,
|
|
29
|
+
peerId,
|
|
30
|
+
signal,
|
|
31
|
+
toBytes: runtime.toBytes,
|
|
32
|
+
});
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|