@cuboapp/ws 2.0.1 → 2.0.3
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 +5 -2
- package/dist/client/index.d.ts +9 -14
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +175 -182
- package/dist/client/index.js.map +1 -1
- package/dist/client/types/index.d.ts +4 -9
- package/dist/client/types/index.d.ts.map +1 -1
- package/dist/server/index.d.ts +4 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +77 -8
- package/dist/server/index.js.map +1 -1
- package/dist/server/types/server/index.d.ts +12 -0
- package/dist/server/types/server/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/client/index.ts +155 -208
- package/src/client/types/index.ts +4 -9
- package/src/server/index.ts +64 -11
- package/src/server/types/server/index.ts +14 -0
package/src/client/index.ts
CHANGED
|
@@ -2,66 +2,49 @@ import { EventEmitter, uuid } from '@cuboapp/utils'
|
|
|
2
2
|
|
|
3
3
|
import { WsMessage } from '../shared'
|
|
4
4
|
|
|
5
|
-
import { WsClientEvent } from './constants'
|
|
5
|
+
import { WsClientEvent, WsClientReadyState } from './constants'
|
|
6
6
|
import { WsClientConnectionOptions, WsClientHandler, WsClientOptions, WsClientRequestOptions } from './types'
|
|
7
7
|
|
|
8
8
|
export * from './constants'
|
|
9
9
|
export * from './types'
|
|
10
10
|
export * from './utils'
|
|
11
11
|
|
|
12
|
-
/**
|
|
13
|
-
* Считать ли соединение оборванным после неудачного тика.
|
|
14
|
-
*
|
|
15
|
-
* Вынесено отдельной функцией, чтобы правило можно было проверить тестом: сам `tick` живёт внутри
|
|
16
|
-
* таймерного цикла, и важно здесь — КОГДА состояние переключается, а не как оно запланировано.
|
|
17
|
-
*
|
|
18
|
-
* `connected === false` означает, что была неудачная попытка ПОДКЛЮЧИТЬСЯ: ждать нечего, подключаться
|
|
19
|
-
* просто не к чему. Терпение нужно только живому сокету, который не успел ответить.
|
|
20
|
-
*/
|
|
12
|
+
/** @deprecated The client now relies on socket closure. Kept for consumers of the old ping helper. */
|
|
21
13
|
export function givesUp(connected: boolean, missedPings: number, maxMisses = 3): boolean {
|
|
22
14
|
if (!connected) return true
|
|
23
15
|
return missedPings >= Math.max(1, maxMisses)
|
|
24
16
|
}
|
|
25
17
|
|
|
18
|
+
type Waiting = {
|
|
19
|
+
socket: WebSocket
|
|
20
|
+
timer: ReturnType<typeof setTimeout>
|
|
21
|
+
resolve: (data: unknown) => void
|
|
22
|
+
reject: (reason: unknown) => void
|
|
23
|
+
}
|
|
24
|
+
|
|
26
25
|
export class WsClient<C extends unknown = {}> {
|
|
27
26
|
public id = ''
|
|
28
27
|
public auth: any = {}
|
|
29
28
|
|
|
30
29
|
public ee = new EventEmitter()
|
|
31
30
|
|
|
32
|
-
constructor(private opts: WsClientOptions<C>) {
|
|
33
|
-
// handler response
|
|
34
|
-
this.registerHandler('response', ({ message }) => {
|
|
35
|
-
if (message.id) {
|
|
36
|
-
const wait = this.waitings.get(message.id)
|
|
37
|
-
|
|
38
|
-
if (wait) {
|
|
39
|
-
wait.finished = true
|
|
40
|
-
|
|
41
|
-
if (message.error) {
|
|
42
|
-
wait.reject(message.error)
|
|
43
|
-
} else {
|
|
44
|
-
wait.resolve(message.data)
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
})
|
|
49
|
-
}
|
|
31
|
+
constructor(private opts: WsClientOptions<C>) {}
|
|
50
32
|
|
|
51
33
|
private ws: WebSocket | null = null
|
|
52
34
|
|
|
53
35
|
private connecting: Promise<void> | null = null
|
|
54
|
-
private
|
|
36
|
+
private disposeSocket: (() => void) | null = null
|
|
37
|
+
private cancelConnect: (() => void) | null = null
|
|
38
|
+
private stopped = false
|
|
39
|
+
private generation = 0
|
|
55
40
|
|
|
56
41
|
private handlers = new Map<string, WsClientHandler<C>>()
|
|
57
|
-
private waitings = new Map<string,
|
|
42
|
+
private waitings = new Map<string, Waiting>()
|
|
58
43
|
|
|
59
44
|
public connected = false
|
|
60
45
|
|
|
61
|
-
private
|
|
46
|
+
private reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
|
62
47
|
private reconnectAttempts = 0
|
|
63
|
-
/** Подряд идущие пропущенные пинги; сбрасывается любым успешным ответом. */
|
|
64
|
-
private missedPings = 0
|
|
65
48
|
|
|
66
49
|
/**
|
|
67
50
|
* Задержка перед следующей попыткой переподключения с экспоненциальным
|
|
@@ -69,7 +52,7 @@ export class WsClient<C extends unknown = {}> {
|
|
|
69
52
|
* каждую секунду (реконнект-шторм при рестарте сервера).
|
|
70
53
|
*/
|
|
71
54
|
private get reconnectDelay() {
|
|
72
|
-
const base = this.opts.reconnectInterval ??
|
|
55
|
+
const base = this.opts.reconnectInterval ?? 1000
|
|
73
56
|
const max = this.opts.reconnectMaxInterval ?? 30_000
|
|
74
57
|
|
|
75
58
|
const exp = Math.min(max, base * 2 ** Math.max(0, this.reconnectAttempts - 1))
|
|
@@ -79,56 +62,22 @@ export class WsClient<C extends unknown = {}> {
|
|
|
79
62
|
return Math.max(base, Math.round(exp + jitter))
|
|
80
63
|
}
|
|
81
64
|
|
|
82
|
-
private
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
try {
|
|
87
|
-
if (!this.connected) {
|
|
88
|
-
this.reconnectAttempts++
|
|
89
|
-
|
|
90
|
-
await this.connect(opts)
|
|
91
|
-
|
|
92
|
-
this.setConnected()
|
|
93
|
-
|
|
94
|
-
// успешно подключились — сбрасываем бэкофф и счётчик промахов
|
|
95
|
-
this.reconnectAttempts = 0
|
|
96
|
-
this.missedPings = 0
|
|
97
|
-
} else {
|
|
98
|
-
await this.request('ping', { wait: true, timeout: this.opts.pingTimeout ?? 5000 })
|
|
99
|
-
// ответ пришёл — соединение живо, копившиеся промахи больше ничего не значат
|
|
100
|
-
this.missedPings = 0
|
|
101
|
-
}
|
|
102
|
-
} catch (e) {
|
|
103
|
-
if (this.opts?.debug) {
|
|
104
|
-
console.error('WS client - tick error', e)
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* Обрыв — только после НЕСКОЛЬКИХ подряд пропущенных пингов.
|
|
109
|
-
*
|
|
110
|
-
* Раньше хватало одного: вкладка, занятая тяжёлым рендером или сборкой мусора, не успевала
|
|
111
|
-
* ответить за секунду, клиент немедленно пересоздавал сокет, CRDT переподписывался на все
|
|
112
|
-
* сущности сразу, бэкенд получал всплеск работы — и следующий пинг опаздывал уже поэтому.
|
|
113
|
-
* Соединение при этом было полностью исправно.
|
|
114
|
-
*
|
|
115
|
-
* Неудачный CONNECT — другое дело: там подключаться просто не к чему, и ждать нечего.
|
|
116
|
-
*/
|
|
117
|
-
if (this.connected) this.missedPings++
|
|
118
|
-
if (givesUp(this.connected, this.missedPings, this.opts.pingMaxMisses)) {
|
|
119
|
-
this.setDisconnected()
|
|
120
|
-
// не дозвонились — следующая попытка с бэкоффом
|
|
121
|
-
nextDelay = this.reconnectDelay
|
|
122
|
-
}
|
|
123
|
-
} finally {
|
|
124
|
-
if (this.opts?.autoReconnect) {
|
|
125
|
-
if (this._tick) {
|
|
126
|
-
clearTimeout(this._tick)
|
|
127
|
-
}
|
|
65
|
+
private clearReconnectTimer() {
|
|
66
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
|
|
67
|
+
this.reconnectTimer = null
|
|
68
|
+
}
|
|
128
69
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
70
|
+
private scheduleReconnect(generation: number, opts?: WsClientConnectionOptions) {
|
|
71
|
+
if (!this.opts.autoReconnect || this.stopped || this.connected || generation !== this.generation) return
|
|
72
|
+
this.clearReconnectTimer()
|
|
73
|
+
this.reconnectTimer = setTimeout(() => {
|
|
74
|
+
this.reconnectTimer = null
|
|
75
|
+
if (this.stopped || this.connected || generation !== this.generation) return
|
|
76
|
+
this.reconnectAttempts++
|
|
77
|
+
void this.connect(opts).catch((error) => {
|
|
78
|
+
if (this.opts.debug) console.error('WS reconnect failed', error)
|
|
79
|
+
})
|
|
80
|
+
}, this.reconnectDelay)
|
|
132
81
|
}
|
|
133
82
|
|
|
134
83
|
private async getToken() {
|
|
@@ -151,102 +100,101 @@ export class WsClient<C extends unknown = {}> {
|
|
|
151
100
|
}
|
|
152
101
|
}
|
|
153
102
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
103
|
+
private retireSocket(reason = new Error('WS disconnected')) {
|
|
104
|
+
const socket = this.ws
|
|
105
|
+
this.disposeSocket?.()
|
|
106
|
+
this.disposeSocket = null
|
|
107
|
+
this.ws = null
|
|
108
|
+
this.id = ''
|
|
109
|
+
this.auth = {}
|
|
110
|
+
for (const [id, waiting] of this.waitings) {
|
|
111
|
+
if (waiting.socket !== socket) continue
|
|
112
|
+
this.waitings.delete(id)
|
|
113
|
+
clearTimeout(waiting.timer)
|
|
114
|
+
waiting.reject(reason)
|
|
157
115
|
}
|
|
116
|
+
this.setDisconnected()
|
|
117
|
+
try { socket?.close(1000) } catch { /* already closed */ }
|
|
118
|
+
}
|
|
158
119
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
resolve()
|
|
169
|
-
} catch (e) {
|
|
170
|
-
reject('WS disconnect: ' + e)
|
|
171
|
-
} finally {
|
|
172
|
-
this.disconnecting = null
|
|
173
|
-
}
|
|
174
|
-
})
|
|
175
|
-
|
|
176
|
-
return this.disconnecting
|
|
120
|
+
public async disconnect() {
|
|
121
|
+
this.stopped = true
|
|
122
|
+
this.generation++
|
|
123
|
+
this.clearReconnectTimer()
|
|
124
|
+
this.cancelConnect?.()
|
|
125
|
+
this.cancelConnect = null
|
|
126
|
+
this.connecting = null
|
|
127
|
+
this.retireSocket()
|
|
177
128
|
}
|
|
178
129
|
|
|
179
130
|
public async connect(opts?: WsClientConnectionOptions) {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
if (this.connected) {
|
|
187
|
-
await this.disconnect().catch((e) => {})
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
this.connecting = new Promise<void>(async (resolve, reject) => {
|
|
191
|
-
let t = setTimeout(() => {
|
|
192
|
-
// закрываем зависший сокет, чтобы не плодить полуоткрытые соединения на бэке
|
|
193
|
-
try {
|
|
194
|
-
this.ws?.close()
|
|
195
|
-
} catch {}
|
|
196
|
-
this.ws = null
|
|
197
|
-
|
|
198
|
-
reject()
|
|
199
|
-
this.connecting = null
|
|
200
|
-
}, timeout)
|
|
201
|
-
|
|
202
|
-
const url = `${this.opts.protocol ?? 'ws'}://${this.opts.host}${this.opts.port ? ':' + this.opts.port : ''}`
|
|
131
|
+
if (this.connecting) return this.connecting
|
|
132
|
+
this.stopped = false
|
|
133
|
+
const generation = ++this.generation
|
|
134
|
+
this.clearReconnectTimer()
|
|
135
|
+
this.retireSocket()
|
|
136
|
+
const attempt = (async () => {
|
|
203
137
|
const token = await this.getToken()
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
this.ws
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
138
|
+
if (generation !== this.generation || this.stopped) throw new Error('WS connection cancelled')
|
|
139
|
+
const url = `${this.opts.protocol ?? 'ws'}://${this.opts.host}${this.opts.port ? ':' + this.opts.port : ''}`
|
|
140
|
+
const socket = new WebSocket(url, token)
|
|
141
|
+
this.ws = socket
|
|
142
|
+
await new Promise<void>((resolve, reject) => {
|
|
143
|
+
let finished = false
|
|
144
|
+
const current = () => this.ws === socket && generation === this.generation && !this.stopped
|
|
145
|
+
const finish = (error?: Error) => {
|
|
146
|
+
if (finished) return
|
|
147
|
+
finished = true
|
|
148
|
+
clearTimeout(timer)
|
|
149
|
+
this.cancelConnect = null
|
|
150
|
+
if (error) {
|
|
151
|
+
if (current()) this.retireSocket()
|
|
152
|
+
reject(error)
|
|
153
|
+
} else resolve()
|
|
154
|
+
}
|
|
155
|
+
const timer = setTimeout(() => finish(new Error('WS connection timeout')), opts?.timeout ?? 1000)
|
|
156
|
+
this.cancelConnect = () => finish(new Error('WS connection cancelled'))
|
|
157
|
+
const onMessage = (event: MessageEvent) => {
|
|
158
|
+
if (!current()) return
|
|
159
|
+
try {
|
|
160
|
+
const message = JSON.parse(String(event.data)) as WsMessage
|
|
161
|
+
if (message.method === 'init') {
|
|
162
|
+
if (finished) return
|
|
163
|
+
const data = message.data as { id: string; auth: unknown }
|
|
164
|
+
this.id = data.id
|
|
165
|
+
this.auth = data.auth
|
|
166
|
+
this.reconnectAttempts = 0
|
|
167
|
+
finish()
|
|
168
|
+
this.setConnected()
|
|
169
|
+
} else void this.handleMessage(message, socket)
|
|
170
|
+
} catch { /* malformed frames cannot affect another connection */ }
|
|
171
|
+
}
|
|
172
|
+
const onClose = ({ code, reason, wasClean }: CloseEvent) => {
|
|
173
|
+
if (!current()) return
|
|
174
|
+
const connected = this.connected
|
|
175
|
+
const error = new Error(connected ? 'WS disconnected' : 'WS closed before handshake', { cause: { code, reason, wasClean } })
|
|
176
|
+
this.retireSocket(error)
|
|
177
|
+
finish(error)
|
|
178
|
+
if (connected) this.scheduleReconnect(generation, opts)
|
|
179
|
+
}
|
|
180
|
+
const onError = () => {
|
|
181
|
+
if (current()) finish(new Error('WS connection error'))
|
|
182
|
+
}
|
|
183
|
+
socket.addEventListener('message', onMessage)
|
|
184
|
+
socket.addEventListener('close', onClose)
|
|
185
|
+
socket.addEventListener('error', onError)
|
|
186
|
+
this.disposeSocket = () => {
|
|
187
|
+
socket.removeEventListener('message', onMessage)
|
|
188
|
+
socket.removeEventListener('close', onClose)
|
|
189
|
+
socket.removeEventListener('error', onError)
|
|
231
190
|
}
|
|
232
191
|
})
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
this.
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
this.ws?.addEventListener('close', () => {
|
|
241
|
-
this.setDisconnected()
|
|
242
|
-
})
|
|
243
|
-
|
|
244
|
-
this.ws?.addEventListener('error', () => {})
|
|
245
|
-
|
|
246
|
-
this.tick(opts)
|
|
247
|
-
})
|
|
248
|
-
|
|
249
|
-
return this.connecting
|
|
192
|
+
})()
|
|
193
|
+
this.connecting = attempt
|
|
194
|
+
try { await attempt } finally {
|
|
195
|
+
if (this.connecting === attempt) this.connecting = null
|
|
196
|
+
this.scheduleReconnect(generation, opts)
|
|
197
|
+
}
|
|
250
198
|
}
|
|
251
199
|
|
|
252
200
|
public async registerHandler(name: string, handler: WsClientHandler<C>) {
|
|
@@ -260,48 +208,47 @@ export class WsClient<C extends unknown = {}> {
|
|
|
260
208
|
public async request<T extends unknown>(dto: WsMessage | string, opts?: WsClientRequestOptions<true>): Promise<T>
|
|
261
209
|
public async request<T extends unknown>(dto: WsMessage | string, opts?: WsClientRequestOptions<false>): Promise<void>
|
|
262
210
|
public async request(dto: WsMessage | string, opts?: WsClientRequestOptions<boolean>) {
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
let message: WsMessage
|
|
268
|
-
|
|
269
|
-
if (typeof dto === 'string') {
|
|
270
|
-
message = {
|
|
271
|
-
method: dto
|
|
272
|
-
}
|
|
273
|
-
} else {
|
|
274
|
-
message = dto
|
|
211
|
+
const socket = this.ws
|
|
212
|
+
if (!socket || !this.connected || socket.readyState !== WsClientReadyState.OPEN) {
|
|
213
|
+
throw new Error('WS:request - not connected')
|
|
275
214
|
}
|
|
276
215
|
|
|
216
|
+
const message = typeof dto === 'string' ? { method: dto } : dto
|
|
277
217
|
const wait = typeof opts === 'boolean' ? opts : (opts?.wait ?? false)
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
218
|
+
if (!wait) return socket.send(JSON.stringify(message))
|
|
219
|
+
|
|
220
|
+
const timeout = typeof opts === 'boolean' ? 1000 : opts?.timeout ?? 1000
|
|
221
|
+
const id = uuid()
|
|
222
|
+
const { promise, resolve, reject } = Promise.withResolvers<unknown>()
|
|
223
|
+
const timer = setTimeout(() => {
|
|
224
|
+
this.waitings.delete(id)
|
|
225
|
+
reject(new Error('WS request timeout'))
|
|
226
|
+
}, Number.isFinite(timeout) && timeout > 0 ? timeout : 1000)
|
|
227
|
+
this.waitings.set(id, { socket, timer, resolve, reject })
|
|
228
|
+
try {
|
|
229
|
+
socket.send(JSON.stringify({ ...message, id }))
|
|
230
|
+
} catch (error) {
|
|
231
|
+
clearTimeout(timer)
|
|
232
|
+
this.waitings.delete(id)
|
|
233
|
+
reject(error)
|
|
234
|
+
}
|
|
295
235
|
|
|
296
|
-
|
|
236
|
+
return promise
|
|
237
|
+
}
|
|
297
238
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
239
|
+
private async handleMessage(message: WsMessage, socket: WebSocket) {
|
|
240
|
+
if (message.method === 'response') {
|
|
241
|
+
const id = message.id
|
|
242
|
+
if (!id) return
|
|
243
|
+
const waiting = this.waitings.get(id)
|
|
244
|
+
if (waiting?.socket !== socket) return
|
|
245
|
+
this.waitings.delete(id)
|
|
246
|
+
clearTimeout(waiting.timer)
|
|
247
|
+
if (message.error != null) waiting.reject(message.error)
|
|
248
|
+
else waiting.resolve(message.data)
|
|
249
|
+
return
|
|
301
250
|
}
|
|
302
|
-
}
|
|
303
251
|
|
|
304
|
-
private async handleMessage(message: WsMessage) {
|
|
305
252
|
const handler = this.handlers.get(message.method)
|
|
306
253
|
if (handler) {
|
|
307
254
|
try {
|
|
@@ -309,8 +256,8 @@ export class WsClient<C extends unknown = {}> {
|
|
|
309
256
|
|
|
310
257
|
const data = await handler(opts as any)
|
|
311
258
|
|
|
312
|
-
if (data !== undefined) {
|
|
313
|
-
|
|
259
|
+
if (data !== undefined && this.ws === socket) {
|
|
260
|
+
socket.send(
|
|
314
261
|
JSON.stringify({
|
|
315
262
|
...message,
|
|
316
263
|
data,
|
|
@@ -14,20 +14,15 @@ export type WsClientOptions<C extends unknown> = {
|
|
|
14
14
|
authToken?: () => Promise<string> | string
|
|
15
15
|
|
|
16
16
|
autoReconnect?: boolean
|
|
17
|
+
/** @deprecated Ignored. WebSocket uses the server's transport heartbeat. */
|
|
17
18
|
pingInterval?: number
|
|
19
|
+
/** @deprecated Ignored. WebSocket uses the server's transport heartbeat. */
|
|
18
20
|
pingTimeout?: number
|
|
19
|
-
/**
|
|
20
|
-
* Сколько подряд пропущенных пингов считать обрывом. По умолчанию 3.
|
|
21
|
-
*
|
|
22
|
-
* Один неотвеченный пинг — это не мёртвое соединение. Вкладка, занятая тяжёлым рендером, сборкой
|
|
23
|
-
* мусора или просто медленной сетью, не отвечает вовремя и при пороге в 1 промах немедленно
|
|
24
|
-
* объявляется отключённой: сокет пересоздаётся, CRDT переподписывается на ВСЕ сущности разом,
|
|
25
|
-
* бэкенд получает всплеск работы — и следующий пинг опаздывает уже из-за этого. Цикл.
|
|
26
|
-
*/
|
|
21
|
+
/** @deprecated Ignored. WebSocket uses the server's transport heartbeat. */
|
|
27
22
|
pingMaxMisses?: number
|
|
28
23
|
|
|
29
24
|
/**
|
|
30
|
-
* Базовая задержка переподключения (мс). По умолчанию
|
|
25
|
+
* Базовая задержка переподключения (мс). По умолчанию 1000.
|
|
31
26
|
* Задержка растёт экспоненциально при подряд идущих неудачных попытках.
|
|
32
27
|
*/
|
|
33
28
|
reconnectInterval?: number
|
package/src/server/index.ts
CHANGED
|
@@ -21,6 +21,8 @@ export class WsServer<C = {}> {
|
|
|
21
21
|
|
|
22
22
|
private handlers = new Map<string, WsServerHandler<C>>()
|
|
23
23
|
private waitings = new Map<string, WsServerRequestWaiting[]>()
|
|
24
|
+
private heartbeat?: ReturnType<typeof setInterval>
|
|
25
|
+
private readonly alive = new WeakMap<object, boolean>()
|
|
24
26
|
|
|
25
27
|
constructor(private opts: WsServerOptions<C>) {}
|
|
26
28
|
|
|
@@ -62,8 +64,11 @@ export class WsServer<C = {}> {
|
|
|
62
64
|
// ping-pong
|
|
63
65
|
this.registerHandler('ping', () => 'pong')
|
|
64
66
|
|
|
67
|
+
// `noServer`: the upgrade is ours to route — `opts.upgrade` may claim it first (a relayed path);
|
|
68
|
+
// everything else goes through this server exactly as before, verifyClient included.
|
|
65
69
|
this.ws = new WebSocketServer({
|
|
66
|
-
|
|
70
|
+
noServer: true,
|
|
71
|
+
maxPayload: this.opts.maxPayload ?? 1024 * 1024,
|
|
67
72
|
verifyClient: async (info, callback) => {
|
|
68
73
|
try {
|
|
69
74
|
if (this.opts?.auth?.default === true && !!this.opts?.auth?.handler) {
|
|
@@ -77,9 +82,22 @@ export class WsServer<C = {}> {
|
|
|
77
82
|
}
|
|
78
83
|
})
|
|
79
84
|
|
|
85
|
+
const instance = this.httpServer.getInstance()
|
|
86
|
+
if (!instance) throw new Error('Ws: the http server did not initialise')
|
|
87
|
+
instance.on('upgrade', (request, socket, head) => {
|
|
88
|
+
if (this.opts.upgrade?.(request, socket, head)) return
|
|
89
|
+
this.ws.handleUpgrade(request, socket, head, (client) => this.ws.emit('connection', client, request))
|
|
90
|
+
})
|
|
91
|
+
|
|
80
92
|
this.ws.addListener('connection', (socket: WsServerSocket<C>, request: WsServerRequest<C>) => {
|
|
93
|
+
// Oversized/invalid frames are protocol errors, not uncaught process exceptions.
|
|
94
|
+
socket.on('error', () => {
|
|
95
|
+
if (this.opts.debug) console.error('WS: invalid or oversized incoming frame')
|
|
96
|
+
})
|
|
81
97
|
socket.id = uuid()
|
|
82
98
|
socket.auth = request.auth
|
|
99
|
+
this.alive.set(socket, true)
|
|
100
|
+
socket.on('pong', () => this.alive.set(socket, true))
|
|
83
101
|
|
|
84
102
|
socket.send(
|
|
85
103
|
JSON.stringify({
|
|
@@ -157,9 +175,21 @@ export class WsServer<C = {}> {
|
|
|
157
175
|
await this.init()
|
|
158
176
|
|
|
159
177
|
await this.httpServer.start()
|
|
178
|
+
if (!this.heartbeat) {
|
|
179
|
+
this.heartbeat = setInterval(() => {
|
|
180
|
+
for (const client of this.clients) {
|
|
181
|
+
if (this.alive.get(client) === false) { client.terminate(); continue }
|
|
182
|
+
this.alive.set(client, false)
|
|
183
|
+
try { client.ping() } catch { client.terminate() }
|
|
184
|
+
}
|
|
185
|
+
}, 15_000)
|
|
186
|
+
this.heartbeat.unref?.()
|
|
187
|
+
}
|
|
160
188
|
}
|
|
161
189
|
|
|
162
190
|
async stop() {
|
|
191
|
+
if (this.heartbeat) clearInterval(this.heartbeat)
|
|
192
|
+
this.heartbeat = undefined
|
|
163
193
|
await this.httpServer.stop()
|
|
164
194
|
}
|
|
165
195
|
|
|
@@ -246,21 +276,44 @@ export class WsServer<C = {}> {
|
|
|
246
276
|
}
|
|
247
277
|
}
|
|
248
278
|
|
|
279
|
+
/** Recheck a deferred operation immediately before its write, using the same live policy. */
|
|
280
|
+
public async authorizeClient(client: WsServerSocket<C>, message: WsMessage = { method: 'crdt:store' }): Promise<boolean> {
|
|
281
|
+
if (!this.clients.has(client) || client.readyState !== 1) return false
|
|
282
|
+
try { return !this.opts.authorizeMessage || !!(await this.opts.authorizeMessage(client, message)) }
|
|
283
|
+
catch { return false }
|
|
284
|
+
}
|
|
285
|
+
|
|
249
286
|
private async handleMessage(client: WsServerSocket<C>, message: WsMessage) {
|
|
287
|
+
if (!(await this.authorizeClient(client, message))) {
|
|
288
|
+
client.close(4401, 'session ended')
|
|
289
|
+
return
|
|
290
|
+
}
|
|
250
291
|
const handler = this.handlers.get(message.method)
|
|
251
292
|
|
|
252
293
|
if (handler) {
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
294
|
+
try {
|
|
295
|
+
const data = await handler({ client, message } as any)
|
|
296
|
+
|
|
297
|
+
if (data !== undefined) {
|
|
298
|
+
client.send(
|
|
299
|
+
JSON.stringify({
|
|
300
|
+
...message,
|
|
301
|
+
data,
|
|
302
|
+
method: 'response'
|
|
303
|
+
})
|
|
304
|
+
)
|
|
305
|
+
}
|
|
306
|
+
} catch (error) {
|
|
307
|
+
if (typeof message.id !== 'string' || message.id.length > 128 || client.readyState !== 1) return
|
|
308
|
+
const problem = typeof error === 'object' && error !== null ? error as { status?: unknown; statusCode?: unknown; text?: unknown } : undefined
|
|
309
|
+
const value = problem?.status ?? problem?.statusCode
|
|
310
|
+
const status = typeof value === 'number' && Number.isInteger(value) && value >= 400 && value < 500 ? value : 500
|
|
311
|
+
const text = status === 403 && problem?.text === 'Forbidden: subscription belongs to another client'
|
|
312
|
+
? 'Forbidden: subscription belongs to another client'
|
|
313
|
+
: ({ 400: 'Bad request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not found', 409: 'Conflict', 413: 'Request too large', 429: 'Too many requests' } as Record<number, string>)[status] ?? 'Request failed'
|
|
314
|
+
client.send(JSON.stringify({ method: 'response', id: message.id, error: { status, text } }))
|
|
263
315
|
}
|
|
316
|
+
|
|
264
317
|
} else if (message.method) {
|
|
265
318
|
throw 'No handler defined "' + message.method + '"'
|
|
266
319
|
} else {
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import type { IncomingMessage } from 'node:http'
|
|
2
|
+
import type { Duplex } from 'node:stream'
|
|
3
|
+
|
|
1
4
|
import { type HttpServerOptions } from '@cuboapp/http-server'
|
|
2
5
|
|
|
3
6
|
import { WsMessage } from '../../../shared'
|
|
@@ -10,15 +13,26 @@ import { WsServerSocket } from '../socket'
|
|
|
10
13
|
export type WsServerOptions<C extends unknown> = {
|
|
11
14
|
host: string
|
|
12
15
|
port: number
|
|
16
|
+
/** Maximum incoming websocket frame bytes (default 1 MiB). */
|
|
17
|
+
maxPayload?: number
|
|
13
18
|
auth?: {
|
|
14
19
|
default?: boolean
|
|
15
20
|
handler?: (ctx: { server: WsServer<C>; request: WsServerRequest<C> }) => Promise<void> | void
|
|
16
21
|
}
|
|
22
|
+
/** Revalidate a live credential before dispatching each client message; failure closes the socket. */
|
|
23
|
+
authorizeMessage?: (client: WsServerSocket<C>, message: WsMessage) => boolean | Promise<boolean>
|
|
17
24
|
debug?: boolean
|
|
18
25
|
http?: Partial<HttpServerOptions<C>>
|
|
19
26
|
|
|
20
27
|
onConnect?: (socket: WsServerSocket<C>) => void | Promise<void>
|
|
21
28
|
onDisconnect?: (socket: WsServerSocket<C>) => void | Promise<void>
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Claim an upgrade before this server's own websocket sees it — return true and the socket is yours
|
|
32
|
+
* (relay it, refuse it); false and it is handled here as usual, `auth` and all. For a server that also
|
|
33
|
+
* relays some paths elsewhere on the same port.
|
|
34
|
+
*/
|
|
35
|
+
upgrade?: (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean
|
|
22
36
|
}
|
|
23
37
|
|
|
24
38
|
export type WsServerHandler<C, D extends unknown = object> = (
|