@cuboapp/ws 1.0.1 → 1.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/old/client/index.ts +237 -0
- package/{src → old}/client/types.ts +12 -2
- package/old/client/utils.ts +8 -0
- package/old/index.ts +2 -0
- package/old/server/index.ts +205 -0
- package/old/server/types/handler/index.ts +20 -0
- package/old/server/types/index.ts +5 -0
- package/old/server/types/message/index.ts +7 -0
- package/old/server/types/request/index.ts +17 -0
- package/old/server/types/response/index.ts +18 -0
- package/old/server/types/server/index.ts +13 -0
- package/old/server/types/socket/index.ts +6 -0
- package/{src/server → old/server/types}/types.ts +2 -18
- package/package-lock.json +9854 -0
- package/package.json +4 -4
- package/src/client/constants/index.ts +6 -0
- package/src/client/index.ts +75 -55
- package/src/client/types/index.ts +27 -0
- package/src/client/utils/index.ts +13 -0
- package/src/index.ts +1 -0
- package/src/server/index.ts +132 -83
- package/src/server/types/handler/index.ts +22 -0
- package/src/server/types/index.ts +4 -0
- package/src/server/types/request/index.ts +27 -0
- package/src/server/types/response/index.ts +18 -0
- package/src/server/types/server/index.ts +26 -0
- package/src/server/types/socket/index.ts +6 -0
- package/src/server/utils/index.ts +13 -0
- package/src/shared/index.ts +1 -0
- package/src/shared/types/index.ts +7 -0
- package/src/client/utils.ts +0 -0
- /package/{src → old}/client/constants.ts +0 -0
- /package/{src → old}/server/utils.ts +0 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cuboapp/ws",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.3",
|
|
4
4
|
"description": "WebSockets",
|
|
5
5
|
"main": "src/index.ts",
|
|
6
6
|
"repository": "git@cuboapp.gitlab.yandexcloud.net:cubo/ws.git",
|
|
@@ -11,9 +11,9 @@
|
|
|
11
11
|
"access": "public"
|
|
12
12
|
},
|
|
13
13
|
"dependencies": {
|
|
14
|
-
"@cuboapp/http-server": "1.0.
|
|
15
|
-
"@cuboapp/utils": "1.0.
|
|
16
|
-
"ws": "^8.
|
|
14
|
+
"@cuboapp/http-server": "1.0.7",
|
|
15
|
+
"@cuboapp/utils": "1.0.9",
|
|
16
|
+
"ws": "^8.19.0"
|
|
17
17
|
},
|
|
18
18
|
"devDependencies": {
|
|
19
19
|
"@types/node": "^24.9.1",
|
package/src/client/index.ts
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { uuid } from '@cuboapp/utils'
|
|
2
2
|
|
|
3
|
+
import { WsMessage } from '../shared'
|
|
4
|
+
|
|
3
5
|
import { WsClientReadyState } from './constants'
|
|
4
|
-
import {
|
|
6
|
+
import { WsClientConnectionOptions, WsClientHandler, WsClientOptions, WsClientRequestOptions } from './types'
|
|
5
7
|
|
|
6
8
|
export * from './constants'
|
|
7
9
|
export * from './types'
|
|
8
10
|
export * from './utils'
|
|
9
11
|
|
|
10
|
-
export class WsClient<C extends unknown> {
|
|
12
|
+
export class WsClient<C extends unknown = {}> {
|
|
11
13
|
constructor(private opts: WsClientOptions<C>) {
|
|
12
14
|
// handler response
|
|
13
15
|
this.registerHandler('response', ({ message }) => {
|
|
@@ -15,6 +17,8 @@ export class WsClient<C extends unknown> {
|
|
|
15
17
|
const wait = this.waitings.get(message.id)
|
|
16
18
|
|
|
17
19
|
if (wait) {
|
|
20
|
+
wait.finished = true
|
|
21
|
+
|
|
18
22
|
if (message.error) {
|
|
19
23
|
wait.reject(message.error)
|
|
20
24
|
} else {
|
|
@@ -32,12 +36,32 @@ export class WsClient<C extends unknown> {
|
|
|
32
36
|
private disconnecting: Promise<void> | null = null
|
|
33
37
|
|
|
34
38
|
private handlers = new Map<string, WsClientHandler<C>>()
|
|
35
|
-
private waitings = new Map<string, { resolve: (res: any) => void; reject: (reason: any) => void }>()
|
|
39
|
+
private waitings = new Map<string, { finished: boolean; resolve: (res: any) => void; reject: (reason: any) => void }>()
|
|
36
40
|
|
|
37
41
|
public get connected() {
|
|
38
42
|
return this.ws?.readyState === WsClientReadyState.OPEN
|
|
39
43
|
}
|
|
40
44
|
|
|
45
|
+
private async tick(opts?: WsClientConnectionOptions) {
|
|
46
|
+
try {
|
|
47
|
+
if (!this.connected) {
|
|
48
|
+
if (!this.connecting) {
|
|
49
|
+
if (this.ws) {
|
|
50
|
+
await this.disconnect().catch((e) => {})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
await this.connect(opts)
|
|
54
|
+
}
|
|
55
|
+
} else {
|
|
56
|
+
await this.request('ping', { wait: true, timeout: this.opts.pingTimeout ?? 1000 })
|
|
57
|
+
}
|
|
58
|
+
} catch (e) {
|
|
59
|
+
console.error('WS client - ping error', e)
|
|
60
|
+
} finally {
|
|
61
|
+
setTimeout(() => this.tick(opts), this.opts.pingInterval ?? 1000)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
41
65
|
public async disconnect() {
|
|
42
66
|
if (this.disconnecting) {
|
|
43
67
|
return this.disconnecting
|
|
@@ -55,7 +79,7 @@ export class WsClient<C extends unknown> {
|
|
|
55
79
|
|
|
56
80
|
promise
|
|
57
81
|
.catch((error) => {
|
|
58
|
-
console.log('WS
|
|
82
|
+
console.log('WS client disconnected:', error)
|
|
59
83
|
})
|
|
60
84
|
.finally(() => {
|
|
61
85
|
clearTimeout(timeout)
|
|
@@ -74,7 +98,7 @@ export class WsClient<C extends unknown> {
|
|
|
74
98
|
return this.disconnecting
|
|
75
99
|
}
|
|
76
100
|
|
|
77
|
-
public async connect(opts?:
|
|
101
|
+
public async connect(opts?: WsClientConnectionOptions) {
|
|
78
102
|
const timeout = opts?.timeout ?? 1000
|
|
79
103
|
|
|
80
104
|
if (this.connecting) {
|
|
@@ -88,10 +112,7 @@ export class WsClient<C extends unknown> {
|
|
|
88
112
|
this.connecting = Promise.race([
|
|
89
113
|
promise
|
|
90
114
|
.then(() => {
|
|
91
|
-
console.log('WS connected')
|
|
92
|
-
if (!this.ticker) {
|
|
93
|
-
this.ticker = this.tick()
|
|
94
|
-
}
|
|
115
|
+
console.log('WS client connected')
|
|
95
116
|
})
|
|
96
117
|
.finally(() => {
|
|
97
118
|
this.connecting = null
|
|
@@ -102,24 +123,26 @@ export class WsClient<C extends unknown> {
|
|
|
102
123
|
r(`Connection timeout (${timeout}ms)`)
|
|
103
124
|
}, timeout)
|
|
104
125
|
})
|
|
105
|
-
])
|
|
126
|
+
]).finally(() => {
|
|
127
|
+
if (this.opts?.autoReconnect && !this.ticker) {
|
|
128
|
+
this.ticker = this.tick()
|
|
129
|
+
}
|
|
130
|
+
})
|
|
106
131
|
|
|
107
|
-
const url = `${this.opts.protocol ?? '
|
|
132
|
+
const url = `${this.opts.protocol ?? 'ws'}://${this.opts.host}${this.opts.port ? ':' + this.opts.port : ''}`
|
|
108
133
|
|
|
109
|
-
|
|
110
|
-
if (this.opts?.
|
|
111
|
-
|
|
134
|
+
let token = ''
|
|
135
|
+
if (this.opts?.authToken) {
|
|
136
|
+
token = await this.opts.authToken()
|
|
112
137
|
}
|
|
113
138
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
this.ws = new WebSocket(url, { headers } as any)
|
|
139
|
+
this.ws = new WebSocket(url, token || undefined)
|
|
117
140
|
|
|
118
141
|
this.ws?.addEventListener('open', () => {
|
|
119
142
|
resolve(true)
|
|
120
143
|
})
|
|
121
144
|
|
|
122
|
-
this.ws?.addEventListener('message', (event:
|
|
145
|
+
this.ws?.addEventListener('message', (event: any) => {
|
|
123
146
|
this.handleMessage(JSON.parse(event.data))
|
|
124
147
|
})
|
|
125
148
|
this.ws?.addEventListener('close', () => {})
|
|
@@ -132,14 +155,14 @@ export class WsClient<C extends unknown> {
|
|
|
132
155
|
this.handlers.set(name, handler)
|
|
133
156
|
}
|
|
134
157
|
|
|
135
|
-
public async request<T extends unknown>(dto:
|
|
136
|
-
public async request<T extends unknown>(dto:
|
|
137
|
-
public async request(dto:
|
|
158
|
+
public async request<T extends unknown>(dto: WsMessage | string, opts?: WsClientRequestOptions<true>): Promise<T>
|
|
159
|
+
public async request<T extends unknown>(dto: WsMessage | string, opts?: WsClientRequestOptions<false>): Promise<void>
|
|
160
|
+
public async request(dto: WsMessage | string, opts?: WsClientRequestOptions<boolean>) {
|
|
138
161
|
if (!this.ws || !this.connected) {
|
|
139
162
|
throw 'WS:request - not connected'
|
|
140
163
|
}
|
|
141
164
|
|
|
142
|
-
let message:
|
|
165
|
+
let message: WsMessage
|
|
143
166
|
|
|
144
167
|
if (typeof dto === 'string') {
|
|
145
168
|
message = {
|
|
@@ -149,58 +172,39 @@ export class WsClient<C extends unknown> {
|
|
|
149
172
|
message = dto
|
|
150
173
|
}
|
|
151
174
|
|
|
152
|
-
const wait = typeof opts === 'boolean' ? opts : opts?.wait ?? false
|
|
153
|
-
const timeout = typeof opts === 'boolean' ? (opts === true ? 1000 : undefined) : opts?.timeout ?? 1000
|
|
175
|
+
const wait = typeof opts === 'boolean' ? opts : (opts?.wait ?? false)
|
|
176
|
+
const timeout = typeof opts === 'boolean' ? (opts === true ? 1000 : undefined) : (opts?.timeout ?? 1000)
|
|
154
177
|
|
|
155
178
|
if (wait) {
|
|
156
179
|
message.id = uuid()
|
|
157
180
|
|
|
158
181
|
const { promise, resolve, reject } = Promise.withResolvers()
|
|
159
182
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
this.ws?.send(JSON.stringify(message))
|
|
183
|
+
const w = { finished: false, resolve, reject }
|
|
184
|
+
this.waitings.set(message.id, w)
|
|
163
185
|
|
|
164
186
|
if (timeout) {
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
|
|
187
|
+
setTimeout(() => {
|
|
188
|
+
if (!w.finished) {
|
|
189
|
+
console.log('reject by timeout', w.finished)
|
|
190
|
+
reject('WS request timeout: ' + JSON.stringify({ dto, opts }, null, 2))
|
|
191
|
+
}
|
|
192
|
+
}, timeout)
|
|
171
193
|
}
|
|
172
194
|
|
|
195
|
+
this.ws?.send(JSON.stringify(message))
|
|
196
|
+
|
|
173
197
|
return promise
|
|
174
198
|
} else {
|
|
175
199
|
return this.ws.send(JSON.stringify(message))
|
|
176
200
|
}
|
|
177
201
|
}
|
|
178
202
|
|
|
179
|
-
private async
|
|
180
|
-
try {
|
|
181
|
-
if (!this.connected) {
|
|
182
|
-
console.log('trying connect...')
|
|
183
|
-
|
|
184
|
-
if (this.ws) {
|
|
185
|
-
await this.disconnect()
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
await this.connect()
|
|
189
|
-
} else {
|
|
190
|
-
await this.request('ping', true)
|
|
191
|
-
}
|
|
192
|
-
} catch (e) {
|
|
193
|
-
console.error(e)
|
|
194
|
-
} finally {
|
|
195
|
-
setTimeout(() => this.tick(), 1000)
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
private async handleMessage(message: WsClientMessage) {
|
|
203
|
+
private async handleMessage(message: WsMessage) {
|
|
200
204
|
const handler = this.handlers.get(message.method)
|
|
201
205
|
if (handler) {
|
|
202
206
|
try {
|
|
203
|
-
const opts = { ...(this.opts
|
|
207
|
+
const opts = { ...(this.opts ?? {}), message }
|
|
204
208
|
|
|
205
209
|
const data = await handler(opts as any)
|
|
206
210
|
|
|
@@ -222,4 +226,20 @@ export class WsClient<C extends unknown> {
|
|
|
222
226
|
console.log('WS: message', message)
|
|
223
227
|
}
|
|
224
228
|
}
|
|
229
|
+
|
|
230
|
+
addEventListener<K extends keyof WebSocketEventMap>(
|
|
231
|
+
type: K,
|
|
232
|
+
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
|
|
233
|
+
options?: boolean | AddEventListenerOptions
|
|
234
|
+
) {
|
|
235
|
+
return this.ws?.addEventListener(type, listener, options)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
removeEventListener<K extends keyof WebSocketEventMap>(
|
|
239
|
+
type: K,
|
|
240
|
+
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
|
|
241
|
+
options?: boolean | EventListenerOptions
|
|
242
|
+
) {
|
|
243
|
+
return this.ws?.removeEventListener(type, listener, options)
|
|
244
|
+
}
|
|
225
245
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { WsMessage } from '../../shared'
|
|
2
|
+
|
|
3
|
+
export type WsClientHeader = {
|
|
4
|
+
name: string
|
|
5
|
+
value: string | number
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type WsClientOptions<C extends unknown> = {
|
|
9
|
+
protocol?: string
|
|
10
|
+
host?: string
|
|
11
|
+
port?: number
|
|
12
|
+
ctx?: C
|
|
13
|
+
|
|
14
|
+
authToken?: () => Promise<string> | string
|
|
15
|
+
|
|
16
|
+
autoReconnect?: boolean
|
|
17
|
+
pingInterval?: number
|
|
18
|
+
pingTimeout?: number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type WsClientHandler<C extends unknown> = (ctx: { message: WsMessage } & C) => any | Promise<any>
|
|
22
|
+
|
|
23
|
+
export type WsClientRequestOptions<W extends boolean> = { wait?: W; timeout?: number } | W
|
|
24
|
+
|
|
25
|
+
export type WsClientConnectionOptions = {
|
|
26
|
+
timeout?: number
|
|
27
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { WsClient } from '..'
|
|
2
|
+
import { WsClientHandler, WsClientOptions } from '../types'
|
|
3
|
+
|
|
4
|
+
export function createWsClient<C extends unknown>(opts: WsClientOptions<C>) {
|
|
5
|
+
return new WsClient(opts)
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function wsClientHandler<C extends unknown>(name: string, handler: WsClientHandler<C>) {
|
|
9
|
+
return {
|
|
10
|
+
name,
|
|
11
|
+
handler
|
|
12
|
+
}
|
|
13
|
+
}
|
package/src/index.ts
CHANGED
package/src/server/index.ts
CHANGED
|
@@ -1,101 +1,149 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { type HttpServer } from '@cuboapp/http-server'
|
|
2
2
|
import { uuid } from '@cuboapp/utils'
|
|
3
3
|
import { WebSocketServer } from 'ws'
|
|
4
4
|
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
WsServerMessage,
|
|
8
|
-
WsServerOptions,
|
|
9
|
-
WsServerRequest,
|
|
10
|
-
WsServerRequestOptions,
|
|
11
|
-
WsServerResponseWaiting,
|
|
12
|
-
WsServerSocket
|
|
13
|
-
} from './types'
|
|
5
|
+
import { WsMessage } from '../shared'
|
|
6
|
+
import { WsServerHandler, WsServerOptions, WsServerRequest, WsServerRequestOptions, WsServerRequestWaiting, WsServerSocket } from './types'
|
|
14
7
|
|
|
15
8
|
export * from './types'
|
|
16
9
|
export * from './utils'
|
|
17
10
|
|
|
18
11
|
export * from '@cuboapp/http-server'
|
|
19
12
|
|
|
20
|
-
export class WsServer<
|
|
13
|
+
export class WsServer<C = {}> {
|
|
14
|
+
public clients = new Set<WsServerSocket<C>>()
|
|
15
|
+
public httpServer: HttpServer<C>
|
|
16
|
+
|
|
17
|
+
private inited = false
|
|
18
|
+
private initing: null | Promise<void> = null
|
|
19
|
+
|
|
21
20
|
private ws: WebSocketServer
|
|
22
21
|
|
|
23
|
-
private
|
|
24
|
-
private
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
22
|
+
private handlers = new Map<string, WsServerHandler<C>>()
|
|
23
|
+
private waitings = new Map<string, WsServerRequestWaiting[]>()
|
|
24
|
+
|
|
25
|
+
constructor(private opts: WsServerOptions<C>) {}
|
|
26
|
+
|
|
27
|
+
public async init() {
|
|
28
|
+
if (this.inited) {
|
|
29
|
+
return
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (this.initing) {
|
|
33
|
+
return this.initing
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
this.initing = new Promise(async (resolve, reject) => {
|
|
37
|
+
try {
|
|
38
|
+
this.httpServer = (await import('@cuboapp/http-server')).createHttpServer<C>({
|
|
39
|
+
host: this.opts.host,
|
|
40
|
+
port: this.opts.port,
|
|
41
|
+
...(this.opts?.http || {})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
await this.httpServer.init()
|
|
45
|
+
|
|
46
|
+
// response handler
|
|
47
|
+
this.registerHandler('response', ({ message, client }) => {
|
|
48
|
+
if (message.id) {
|
|
49
|
+
const wait = this.waitings.get(message.id)?.find((c) => c.client_id === client.id)
|
|
50
|
+
|
|
51
|
+
if (wait) {
|
|
52
|
+
if (message.error) {
|
|
53
|
+
wait.reject(message.error)
|
|
54
|
+
} else {
|
|
55
|
+
wait.resolve(message.data)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
47
58
|
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
})
|
|
59
|
+
})
|
|
51
60
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
61
|
+
// ping-pong
|
|
62
|
+
this.registerHandler('ping', () => 'pong')
|
|
63
|
+
|
|
64
|
+
this.ws = new WebSocketServer({
|
|
65
|
+
server: this.httpServer.getInstance(),
|
|
66
|
+
verifyClient: async (info, callback) => {
|
|
67
|
+
try {
|
|
68
|
+
if (this.opts?.auth?.default === true && !!this.opts?.auth?.handler) {
|
|
69
|
+
await this.opts?.auth?.handler({ server: this, request: info.req as any })
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
callback(true)
|
|
73
|
+
} catch (e: any) {
|
|
74
|
+
callback(false, e.statusCode ?? 400, `Ws:verifyClient - ${e.statusText ?? 'server error'}`)
|
|
75
|
+
}
|
|
65
76
|
}
|
|
66
|
-
}
|
|
67
|
-
callback(false, 400, `Ws:verifyClient - server error`)
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
})
|
|
77
|
+
})
|
|
71
78
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
79
|
+
this.ws.addListener('connection', (socket: WsServerSocket<C>, request: WsServerRequest<C>) => {
|
|
80
|
+
socket.id = uuid()
|
|
81
|
+
socket.auth = request.auth
|
|
75
82
|
|
|
76
|
-
|
|
83
|
+
if (this.opts.debug) {
|
|
84
|
+
console.log('Client "' + socket.id + '" connected')
|
|
85
|
+
}
|
|
77
86
|
|
|
78
|
-
|
|
79
|
-
|
|
87
|
+
socket.addListener('close', () => {
|
|
88
|
+
if (this.opts.debug) {
|
|
89
|
+
console.log('Client "' + socket.id + '" disconnected')
|
|
90
|
+
}
|
|
80
91
|
|
|
81
|
-
|
|
82
|
-
|
|
92
|
+
this.clients.delete(socket)
|
|
93
|
+
})
|
|
83
94
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
95
|
+
socket.addListener('message', (e) => {
|
|
96
|
+
try {
|
|
97
|
+
this.handleMessage(socket, JSON.parse(e.toString('utf-8'))).catch((e) => {
|
|
98
|
+
if (this.opts.debug) {
|
|
99
|
+
console.error('WS:message error', e)
|
|
100
|
+
}
|
|
101
|
+
})
|
|
102
|
+
} catch (e) {
|
|
103
|
+
if (this.opts.debug) {
|
|
104
|
+
console.error('WS:message fatal', e)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
88
107
|
})
|
|
89
|
-
|
|
90
|
-
|
|
108
|
+
|
|
109
|
+
this.clients.add(socket)
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
this.inited = true
|
|
113
|
+
this.initing = null
|
|
114
|
+
|
|
115
|
+
if (this.opts.debug) {
|
|
116
|
+
console.log('WS server started: ', JSON.stringify({ host: this.opts.host, port: this.opts.port }))
|
|
91
117
|
}
|
|
92
|
-
})
|
|
93
118
|
|
|
94
|
-
|
|
119
|
+
resolve()
|
|
120
|
+
} catch (e) {
|
|
121
|
+
reject(e)
|
|
122
|
+
}
|
|
95
123
|
})
|
|
124
|
+
|
|
125
|
+
return this.initing
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
public getStats() {
|
|
129
|
+
return {
|
|
130
|
+
queue: {
|
|
131
|
+
size: this.clients.size
|
|
132
|
+
},
|
|
133
|
+
handlers: {
|
|
134
|
+
size: this.handlers.size,
|
|
135
|
+
keys: Array.from(this.handlers.keys()).length
|
|
136
|
+
},
|
|
137
|
+
waitings: {
|
|
138
|
+
size: this.waitings.size,
|
|
139
|
+
keys: Array.from(this.waitings.keys()).length
|
|
140
|
+
}
|
|
141
|
+
}
|
|
96
142
|
}
|
|
97
143
|
|
|
98
144
|
async start() {
|
|
145
|
+
await this.init()
|
|
146
|
+
|
|
99
147
|
await this.httpServer.start()
|
|
100
148
|
}
|
|
101
149
|
|
|
@@ -103,18 +151,18 @@ export class WsServer<A extends unknown, C extends unknown> {
|
|
|
103
151
|
await this.httpServer.stop()
|
|
104
152
|
}
|
|
105
153
|
|
|
106
|
-
public async registerHandler<D extends unknown>(name: string, handler: WsServerHandler<
|
|
107
|
-
this.handlers.set(name, handler)
|
|
154
|
+
public async registerHandler<D extends unknown>(name: string, handler: WsServerHandler<C, D>) {
|
|
155
|
+
this.handlers.set(name, handler as any)
|
|
108
156
|
}
|
|
109
157
|
|
|
110
|
-
public async
|
|
111
|
-
public async
|
|
112
|
-
public async
|
|
158
|
+
public async clientRequest<T extends unknown, D extends unknown>(dto: WsMessage<D> | string, opts?: WsServerRequestOptions<C, true>): Promise<T[]>
|
|
159
|
+
public async clientRequest<T extends unknown, D extends unknown>(dto: WsMessage<D> | string, opts?: WsServerRequestOptions<C, false>): Promise<void>
|
|
160
|
+
public async clientRequest<T extends unknown, D extends unknown>(dto: WsMessage<D> | string, opts?: WsServerRequestOptions<C, boolean>) {
|
|
113
161
|
if (!this.ws) {
|
|
114
162
|
throw 'WS:request - not initied'
|
|
115
163
|
}
|
|
116
164
|
|
|
117
|
-
let message:
|
|
165
|
+
let message: WsMessage<D>
|
|
118
166
|
|
|
119
167
|
if (typeof dto === 'string') {
|
|
120
168
|
message = {
|
|
@@ -124,14 +172,14 @@ export class WsServer<A extends unknown, C extends unknown> {
|
|
|
124
172
|
message = dto
|
|
125
173
|
}
|
|
126
174
|
|
|
127
|
-
const wait = typeof opts === 'boolean' ? opts : opts?.wait ?? false
|
|
128
|
-
const timeout = typeof opts === 'boolean' ? (opts === true ? 1000 : undefined) : opts?.timeout ?? 1000
|
|
175
|
+
const wait = typeof opts === 'boolean' ? opts : (opts?.wait ?? false)
|
|
176
|
+
const timeout = typeof opts === 'boolean' ? (opts === true ? 1000 : undefined) : (opts?.timeout ?? 1000)
|
|
129
177
|
const filter = typeof opts === 'boolean' || !opts?.filter ? undefined : opts.filter
|
|
130
178
|
|
|
131
179
|
if (wait) {
|
|
132
180
|
message.id = uuid()
|
|
133
181
|
|
|
134
|
-
const watings:
|
|
182
|
+
const watings: WsServerRequestWaiting[] = []
|
|
135
183
|
const promises: Promise<T>[] = []
|
|
136
184
|
|
|
137
185
|
this.clients.forEach((client) => {
|
|
@@ -173,11 +221,12 @@ export class WsServer<A extends unknown, C extends unknown> {
|
|
|
173
221
|
}
|
|
174
222
|
}
|
|
175
223
|
|
|
176
|
-
private async handleMessage(client: WsServerSocket<
|
|
224
|
+
private async handleMessage(client: WsServerSocket<C>, message: WsMessage) {
|
|
177
225
|
const handler = this.handlers.get(message.method)
|
|
178
226
|
|
|
179
227
|
if (handler) {
|
|
180
|
-
const data = await handler({
|
|
228
|
+
const data = await handler({ client, message } as any)
|
|
229
|
+
|
|
181
230
|
if (data !== undefined) {
|
|
182
231
|
client.send(
|
|
183
232
|
JSON.stringify({
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type HttpServerRequest, type HttpServerResponse } from '@cuboapp/http-server'
|
|
2
|
+
|
|
3
|
+
import { WsMessage } from '../../../shared'
|
|
4
|
+
|
|
5
|
+
import { WsServerRequestDto } from '../request'
|
|
6
|
+
import { WsServerTypicalResponse } from '../response'
|
|
7
|
+
|
|
8
|
+
export type WsServerRequestContext<C extends unknown, R extends unknown> = {
|
|
9
|
+
request: HttpServerRequest<C>
|
|
10
|
+
response: HttpServerResponse<C>
|
|
11
|
+
|
|
12
|
+
auth: C extends { auth?: any } ? C['auth'] : undefined
|
|
13
|
+
|
|
14
|
+
method: string
|
|
15
|
+
query: R extends WsServerRequestDto ? R['Query'] : Record<string, any>
|
|
16
|
+
|
|
17
|
+
message: WsMessage<R extends WsServerRequestDto ? R['Data'] : any>
|
|
18
|
+
} & R
|
|
19
|
+
|
|
20
|
+
export type WsServerRouteHandler<C extends unknown, R extends unknown> = (
|
|
21
|
+
ctx: WsServerRequestContext<C, R>
|
|
22
|
+
) => Promise<WsServerTypicalResponse> | WsServerTypicalResponse
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type IncomingMessage } from 'http'
|
|
2
|
+
|
|
3
|
+
import { WsServerSocket } from '../socket'
|
|
4
|
+
|
|
5
|
+
export type WsServerRequestDto = {
|
|
6
|
+
Data?: any
|
|
7
|
+
Params?: Record<string, any>
|
|
8
|
+
Query?: Record<string, any>
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type WsServerRequestOptions<C, W extends boolean> =
|
|
12
|
+
| {
|
|
13
|
+
wait?: W
|
|
14
|
+
timeout?: number
|
|
15
|
+
filter?: (client: WsServerSocket<C>) => boolean
|
|
16
|
+
}
|
|
17
|
+
| W
|
|
18
|
+
|
|
19
|
+
export interface WsServerRequest<C extends unknown> extends IncomingMessage {
|
|
20
|
+
auth: C extends { auth?: any } ? C['auth'] : undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type WsServerRequestWaiting = {
|
|
24
|
+
client_id: string
|
|
25
|
+
resolve: (res: any) => void
|
|
26
|
+
reject: (reason: any) => void
|
|
27
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type ServerResponse } from 'node:http'
|
|
2
|
+
|
|
3
|
+
import { WsServerRequest } from '../request'
|
|
4
|
+
|
|
5
|
+
export type WsServerTypicalResponse =
|
|
6
|
+
| {
|
|
7
|
+
code?: number
|
|
8
|
+
message?: string
|
|
9
|
+
data?: any
|
|
10
|
+
raw?: boolean
|
|
11
|
+
headers?: Record<string, number | string>
|
|
12
|
+
}
|
|
13
|
+
| Record<string, any>
|
|
14
|
+
| string
|
|
15
|
+
| boolean
|
|
16
|
+
| number
|
|
17
|
+
|
|
18
|
+
export interface WsServerResponse<C extends unknown> extends ServerResponse<WsServerRequest<C>> {}
|