@cuboapp/ws 1.0.6 → 1.0.8
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/package.json +1 -1
- package/src/client/constants/index.ts +5 -0
- package/src/client/index.ts +98 -80
- package/src/client/types/index.ts +2 -0
- package/tsconfig.json +1 -2
- package/old/client/constants.ts +0 -6
- package/old/client/index.ts +0 -237
- package/old/client/types.ts +0 -30
- package/old/client/utils.ts +0 -8
- package/old/index.ts +0 -2
- package/old/server/index.ts +0 -205
- package/old/server/types/handler/index.ts +0 -20
- package/old/server/types/index.ts +0 -5
- package/old/server/types/message/index.ts +0 -7
- package/old/server/types/request/index.ts +0 -17
- package/old/server/types/response/index.ts +0 -18
- package/old/server/types/server/index.ts +0 -13
- package/old/server/types/socket/index.ts +0 -6
- package/old/server/types/types.ts +0 -67
- package/old/server/utils.ts +0 -27
package/package.json
CHANGED
package/src/client/index.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { uuid } from '@cuboapp/utils'
|
|
1
|
+
import { EventEmitter, uuid } from '@cuboapp/utils'
|
|
2
2
|
|
|
3
3
|
import { WsMessage } from '../shared'
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { WsClientEvent } from './constants'
|
|
6
6
|
import { WsClientConnectionOptions, WsClientHandler, WsClientOptions, WsClientRequestOptions } from './types'
|
|
7
7
|
|
|
8
8
|
export * from './constants'
|
|
@@ -13,6 +13,8 @@ export class WsClient<C extends unknown = {}> {
|
|
|
13
13
|
public id = ''
|
|
14
14
|
public auth: any = {}
|
|
15
15
|
|
|
16
|
+
public ee = new EventEmitter()
|
|
17
|
+
|
|
16
18
|
constructor(private opts: WsClientOptions<C>) {
|
|
17
19
|
// handler response
|
|
18
20
|
this.registerHandler('response', ({ message }) => {
|
|
@@ -34,69 +36,81 @@ export class WsClient<C extends unknown = {}> {
|
|
|
34
36
|
|
|
35
37
|
private ws: WebSocket | null = null
|
|
36
38
|
|
|
37
|
-
private ticker: Promise<void> | null = null
|
|
38
39
|
private connecting: Promise<void> | null = null
|
|
39
40
|
private disconnecting: Promise<void> | null = null
|
|
40
41
|
|
|
41
42
|
private handlers = new Map<string, WsClientHandler<C>>()
|
|
42
43
|
private waitings = new Map<string, { finished: boolean; resolve: (res: any) => void; reject: (reason: any) => void }>()
|
|
43
44
|
|
|
44
|
-
public
|
|
45
|
-
return this.ws?.readyState === WsClientReadyState.OPEN
|
|
46
|
-
}
|
|
45
|
+
public connected = false
|
|
47
46
|
|
|
47
|
+
private _tick: any = null
|
|
48
48
|
private async tick(opts?: WsClientConnectionOptions) {
|
|
49
49
|
try {
|
|
50
50
|
if (!this.connected) {
|
|
51
|
-
|
|
52
|
-
if (this.ws) {
|
|
53
|
-
await this.disconnect().catch((e) => {})
|
|
54
|
-
}
|
|
51
|
+
await this.connect(opts)
|
|
55
52
|
|
|
56
|
-
|
|
57
|
-
}
|
|
53
|
+
this.setConnected()
|
|
58
54
|
} else {
|
|
59
55
|
await this.request('ping', { wait: true, timeout: this.opts.pingTimeout ?? 1000 })
|
|
60
56
|
}
|
|
61
57
|
} catch (e) {
|
|
62
|
-
|
|
58
|
+
if (this.opts?.debug) {
|
|
59
|
+
console.error('WS client - tick error', e)
|
|
60
|
+
}
|
|
61
|
+
this.setDisconnected()
|
|
63
62
|
} finally {
|
|
64
|
-
|
|
63
|
+
if (this.opts?.autoReconnect) {
|
|
64
|
+
if (this._tick) {
|
|
65
|
+
clearTimeout(this._tick)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
this._tick = setTimeout(() => this.tick(opts), this.opts.pingInterval ?? 1000)
|
|
69
|
+
}
|
|
65
70
|
}
|
|
66
71
|
}
|
|
67
72
|
|
|
68
|
-
|
|
69
|
-
if (this.
|
|
70
|
-
return this.
|
|
73
|
+
private async getToken() {
|
|
74
|
+
if (this.opts?.authToken) {
|
|
75
|
+
return this.opts.authToken()
|
|
71
76
|
}
|
|
77
|
+
}
|
|
72
78
|
|
|
79
|
+
private setConnected() {
|
|
73
80
|
if (!this.connected) {
|
|
74
|
-
this.
|
|
75
|
-
|
|
81
|
+
this.connected = true
|
|
82
|
+
this.ee.emit(WsClientEvent.CONNECTED)
|
|
76
83
|
}
|
|
84
|
+
}
|
|
77
85
|
|
|
78
|
-
|
|
79
|
-
this.
|
|
86
|
+
private setDisconnected() {
|
|
87
|
+
if (this.connected) {
|
|
88
|
+
this.connected = false
|
|
89
|
+
this.ee.emit(WsClientEvent.DISCONNECTED)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
80
92
|
|
|
81
|
-
|
|
93
|
+
public async disconnect() {
|
|
94
|
+
if (this.disconnecting) {
|
|
95
|
+
return this.disconnecting
|
|
96
|
+
}
|
|
82
97
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
console.log('WS client disconnected:', error)
|
|
86
|
-
})
|
|
87
|
-
.finally(() => {
|
|
88
|
-
clearTimeout(timeout)
|
|
89
|
-
this.disconnecting = null
|
|
90
|
-
})
|
|
98
|
+
this.disconnecting = new Promise<void>(async (resolve, reject) => {
|
|
99
|
+
let t = setTimeout(reject, 1000)
|
|
91
100
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
101
|
+
try {
|
|
102
|
+
this.ws?.close(1000)
|
|
103
|
+
this.ws = null
|
|
95
104
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
105
|
+
clearTimeout(t)
|
|
106
|
+
|
|
107
|
+
resolve()
|
|
108
|
+
} catch (e) {
|
|
109
|
+
reject('WS disconnect: ' + e)
|
|
110
|
+
} finally {
|
|
111
|
+
this.disconnecting = null
|
|
112
|
+
}
|
|
113
|
+
})
|
|
100
114
|
|
|
101
115
|
return this.disconnecting
|
|
102
116
|
}
|
|
@@ -106,57 +120,56 @@ export class WsClient<C extends unknown = {}> {
|
|
|
106
120
|
|
|
107
121
|
if (this.connecting) {
|
|
108
122
|
return this.connecting
|
|
109
|
-
} else if (this.connected) {
|
|
110
|
-
return
|
|
111
123
|
}
|
|
112
124
|
|
|
113
|
-
|
|
125
|
+
if (this.connected) {
|
|
126
|
+
await this.disconnect().catch((e) => {})
|
|
127
|
+
}
|
|
114
128
|
|
|
115
|
-
this.connecting = Promise
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
.finally(() => {
|
|
121
|
-
this.connecting = null
|
|
122
|
-
}),
|
|
123
|
-
new Promise<never>((_, r) => {
|
|
124
|
-
setTimeout(() => {
|
|
125
|
-
this.connecting = null
|
|
126
|
-
r(`Connection timeout (${timeout}ms)`)
|
|
127
|
-
}, timeout)
|
|
128
|
-
})
|
|
129
|
-
]).finally(() => {
|
|
130
|
-
if (this.opts?.autoReconnect && !this.ticker) {
|
|
131
|
-
this.ticker = this.tick()
|
|
132
|
-
}
|
|
133
|
-
})
|
|
129
|
+
this.connecting = new Promise<void>(async (resolve, reject) => {
|
|
130
|
+
let t = setTimeout(() => {
|
|
131
|
+
reject()
|
|
132
|
+
this.connecting = null
|
|
133
|
+
}, timeout)
|
|
134
134
|
|
|
135
|
-
|
|
135
|
+
const url = `${this.opts.protocol ?? 'ws'}://${this.opts.host}${this.opts.port ? ':' + this.opts.port : ''}`
|
|
136
|
+
const token = await this.getToken()
|
|
136
137
|
|
|
137
|
-
|
|
138
|
-
if (this.opts?.authToken) {
|
|
139
|
-
token = await this.opts.authToken()
|
|
140
|
-
}
|
|
138
|
+
this.ws = new WebSocket(url, token)
|
|
141
139
|
|
|
142
|
-
|
|
140
|
+
this.registerHandler('init', ({ message }) => {
|
|
141
|
+
// clear timeout
|
|
142
|
+
clearTimeout(t)
|
|
143
143
|
|
|
144
|
-
|
|
145
|
-
|
|
144
|
+
try {
|
|
145
|
+
const { id, auth } = message.data as { id: string; auth: any }
|
|
146
146
|
|
|
147
|
-
|
|
148
|
-
|
|
147
|
+
this.id = id
|
|
148
|
+
this.auth = auth
|
|
149
149
|
|
|
150
|
-
|
|
151
|
-
|
|
150
|
+
resolve()
|
|
151
|
+
} catch (e) {
|
|
152
|
+
this.setDisconnected()
|
|
153
|
+
reject()
|
|
154
|
+
} finally {
|
|
155
|
+
this.connecting = null
|
|
156
|
+
}
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
this.ws?.addEventListener('open', () => {})
|
|
152
160
|
|
|
153
|
-
|
|
161
|
+
this.ws?.addEventListener('message', (event: any) => {
|
|
162
|
+
this.handleMessage(JSON.parse(event.data))
|
|
163
|
+
})
|
|
154
164
|
|
|
155
|
-
|
|
156
|
-
|
|
165
|
+
this.ws?.addEventListener('close', () => {
|
|
166
|
+
this.setDisconnected()
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
this.ws?.addEventListener('error', () => {})
|
|
170
|
+
|
|
171
|
+
this.tick(opts)
|
|
157
172
|
})
|
|
158
|
-
this.ws?.addEventListener('close', () => {})
|
|
159
|
-
this.ws?.addEventListener('error', () => {})
|
|
160
173
|
|
|
161
174
|
return this.connecting
|
|
162
175
|
}
|
|
@@ -200,7 +213,6 @@ export class WsClient<C extends unknown = {}> {
|
|
|
200
213
|
if (timeout) {
|
|
201
214
|
setTimeout(() => {
|
|
202
215
|
if (!w.finished) {
|
|
203
|
-
console.log('reject by timeout', w.finished)
|
|
204
216
|
reject('WS request timeout: ' + JSON.stringify({ dto, opts }, null, 2))
|
|
205
217
|
}
|
|
206
218
|
}, timeout)
|
|
@@ -232,12 +244,18 @@ export class WsClient<C extends unknown = {}> {
|
|
|
232
244
|
)
|
|
233
245
|
}
|
|
234
246
|
} catch (e) {
|
|
235
|
-
|
|
247
|
+
if (this.opts.debug) {
|
|
248
|
+
console.log(`WS: message #${message.id} - ${e}`)
|
|
249
|
+
}
|
|
236
250
|
}
|
|
237
251
|
} else if (message.method) {
|
|
238
|
-
|
|
252
|
+
if (this.opts.debug) {
|
|
253
|
+
console.log(`WS: message${message.id ? ' #' + message.id : ''} - no handler found "${message.method}"`)
|
|
254
|
+
}
|
|
239
255
|
} else {
|
|
240
|
-
|
|
256
|
+
if (this.opts.debug) {
|
|
257
|
+
console.log('WS: message', message)
|
|
258
|
+
}
|
|
241
259
|
}
|
|
242
260
|
}
|
|
243
261
|
|
|
@@ -16,6 +16,8 @@ export type WsClientOptions<C extends unknown> = {
|
|
|
16
16
|
autoReconnect?: boolean
|
|
17
17
|
pingInterval?: number
|
|
18
18
|
pingTimeout?: number
|
|
19
|
+
|
|
20
|
+
debug?: boolean
|
|
19
21
|
}
|
|
20
22
|
|
|
21
23
|
export type WsClientHandler<C extends unknown> = (ctx: { message: WsMessage } & C) => any | Promise<any>
|
package/tsconfig.json
CHANGED
|
@@ -10,13 +10,12 @@
|
|
|
10
10
|
"noEmit": true,
|
|
11
11
|
"composite": true,
|
|
12
12
|
"strict": true,
|
|
13
|
-
"downlevelIteration": true,
|
|
14
13
|
"skipLibCheck": true,
|
|
15
14
|
"jsx": "react-jsx",
|
|
16
15
|
"allowSyntheticDefaultImports": true,
|
|
17
16
|
"forceConsistentCasingInFileNames": true,
|
|
18
17
|
"strictPropertyInitialization": false,
|
|
19
|
-
"rootDir": "
|
|
18
|
+
"rootDir": ".",
|
|
20
19
|
"outDir": "dist",
|
|
21
20
|
"paths": {
|
|
22
21
|
"@/*": ["./src/*"]
|
package/old/client/constants.ts
DELETED
package/old/client/index.ts
DELETED
|
@@ -1,237 +0,0 @@
|
|
|
1
|
-
import { uuid } from '@cuboapp/utils'
|
|
2
|
-
|
|
3
|
-
import { WsClientReadyState } from './constants'
|
|
4
|
-
import { WsClientConnectionOptions, WsClientHandler, WsClientMessage, WsClientOptions, WsClientRequestOptions } from './types'
|
|
5
|
-
|
|
6
|
-
export * from './constants'
|
|
7
|
-
export * from './types'
|
|
8
|
-
export * from './utils'
|
|
9
|
-
|
|
10
|
-
export function createWsClient<C extends unknown>(opts: WsClientOptions<C>) {
|
|
11
|
-
return new WsClient(opts)
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export class WsClient<C extends unknown> {
|
|
15
|
-
constructor(private opts: WsClientOptions<C>) {
|
|
16
|
-
// handler response
|
|
17
|
-
this.registerHandler('response', ({ message }) => {
|
|
18
|
-
if (message.id) {
|
|
19
|
-
const wait = this.waitings.get(message.id)
|
|
20
|
-
|
|
21
|
-
if (wait) {
|
|
22
|
-
wait.finished = true
|
|
23
|
-
|
|
24
|
-
if (message.error) {
|
|
25
|
-
wait.reject(message.error)
|
|
26
|
-
} else {
|
|
27
|
-
wait.resolve(message.data)
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
})
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
private ws: WebSocket | null = null
|
|
35
|
-
|
|
36
|
-
private ticker: Promise<void> | null = null
|
|
37
|
-
private connecting: Promise<void> | null = null
|
|
38
|
-
private disconnecting: Promise<void> | null = null
|
|
39
|
-
|
|
40
|
-
private handlers = new Map<string, WsClientHandler<C>>()
|
|
41
|
-
private waitings = new Map<string, { finished: boolean; resolve: (res: any) => void; reject: (reason: any) => void }>()
|
|
42
|
-
|
|
43
|
-
public get connected() {
|
|
44
|
-
return this.ws?.readyState === WsClientReadyState.OPEN
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
private async tick(opts?: WsClientConnectionOptions) {
|
|
48
|
-
try {
|
|
49
|
-
if (!this.connected) {
|
|
50
|
-
if (!this.connecting) {
|
|
51
|
-
if (this.ws) {
|
|
52
|
-
await this.disconnect().catch((e) => {})
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
await this.connect(opts)
|
|
56
|
-
}
|
|
57
|
-
} else {
|
|
58
|
-
await this.request('ping', { wait: true, timeout: this.opts.pingTimeout ?? 1000 })
|
|
59
|
-
}
|
|
60
|
-
} catch (e) {
|
|
61
|
-
console.error('WS client - ping error', e)
|
|
62
|
-
} finally {
|
|
63
|
-
setTimeout(() => this.tick(opts), this.opts.pingInterval ?? 1000)
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
public async disconnect() {
|
|
68
|
-
if (this.disconnecting) {
|
|
69
|
-
return this.disconnecting
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
if (!this.connected) {
|
|
73
|
-
this.ws = null
|
|
74
|
-
return
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const { resolve, reject, promise } = Promise.withResolvers<void>()
|
|
78
|
-
this.disconnecting = promise
|
|
79
|
-
|
|
80
|
-
const timeout = setTimeout(() => reject('Timeout'), 1000)
|
|
81
|
-
|
|
82
|
-
promise
|
|
83
|
-
.catch((error) => {
|
|
84
|
-
console.log('WS client disconnected:', error)
|
|
85
|
-
})
|
|
86
|
-
.finally(() => {
|
|
87
|
-
clearTimeout(timeout)
|
|
88
|
-
this.disconnecting = null
|
|
89
|
-
})
|
|
90
|
-
|
|
91
|
-
try {
|
|
92
|
-
this.ws?.close(0)
|
|
93
|
-
this.ws = null
|
|
94
|
-
|
|
95
|
-
resolve()
|
|
96
|
-
} catch (e) {
|
|
97
|
-
reject('WS disconnect: ' + e)
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
return this.disconnecting
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
public async connect(opts?: WsClientConnectionOptions) {
|
|
104
|
-
const timeout = opts?.timeout ?? 1000
|
|
105
|
-
|
|
106
|
-
if (this.connecting) {
|
|
107
|
-
return this.connecting
|
|
108
|
-
} else if (this.connected) {
|
|
109
|
-
return
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
const { resolve, promise } = Promise.withResolvers<boolean>()
|
|
113
|
-
|
|
114
|
-
this.connecting = Promise.race([
|
|
115
|
-
promise
|
|
116
|
-
.then(() => {
|
|
117
|
-
console.log('WS client connected')
|
|
118
|
-
})
|
|
119
|
-
.finally(() => {
|
|
120
|
-
this.connecting = null
|
|
121
|
-
}),
|
|
122
|
-
new Promise<never>((_, r) => {
|
|
123
|
-
setTimeout(() => {
|
|
124
|
-
this.connecting = null
|
|
125
|
-
r(`Connection timeout (${timeout}ms)`)
|
|
126
|
-
}, timeout)
|
|
127
|
-
})
|
|
128
|
-
]).finally(() => {
|
|
129
|
-
if (this.opts?.autoReconnect && !this.ticker) {
|
|
130
|
-
this.ticker = this.tick()
|
|
131
|
-
}
|
|
132
|
-
})
|
|
133
|
-
|
|
134
|
-
const url = `${this.opts.protocol ?? 'http'}://${this.opts.host}${this.opts.port ? ':' + this.opts.port : ''}`
|
|
135
|
-
|
|
136
|
-
const headers: any = {}
|
|
137
|
-
if (this.opts?.headers) {
|
|
138
|
-
const addHeaders = await this.opts.headers()
|
|
139
|
-
|
|
140
|
-
if (addHeaders?.length) {
|
|
141
|
-
addHeaders.forEach((v) => (headers[v.name] = v.value))
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// console.log('connect', { url, headers })
|
|
146
|
-
|
|
147
|
-
this.ws = new WebSocket(url, { headers } as any)
|
|
148
|
-
|
|
149
|
-
this.ws?.addEventListener('open', () => {
|
|
150
|
-
resolve(true)
|
|
151
|
-
})
|
|
152
|
-
|
|
153
|
-
this.ws?.addEventListener('message', (event: any) => {
|
|
154
|
-
this.handleMessage(JSON.parse(event.data))
|
|
155
|
-
})
|
|
156
|
-
this.ws?.addEventListener('close', () => {})
|
|
157
|
-
this.ws?.addEventListener('error', () => {})
|
|
158
|
-
|
|
159
|
-
return this.connecting
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
public async registerHandler(name: string, handler: WsClientHandler<C>) {
|
|
163
|
-
this.handlers.set(name, handler)
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
public async request<T extends unknown>(dto: WsClientMessage | string, opts?: WsClientRequestOptions<true>): Promise<T>
|
|
167
|
-
public async request<T extends unknown>(dto: WsClientMessage | string, opts?: WsClientRequestOptions<false>): Promise<void>
|
|
168
|
-
public async request(dto: WsClientMessage | string, opts?: WsClientRequestOptions<boolean>) {
|
|
169
|
-
if (!this.ws || !this.connected) {
|
|
170
|
-
throw 'WS:request - not connected'
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
let message: WsClientMessage
|
|
174
|
-
|
|
175
|
-
if (typeof dto === 'string') {
|
|
176
|
-
message = {
|
|
177
|
-
method: dto
|
|
178
|
-
}
|
|
179
|
-
} else {
|
|
180
|
-
message = dto
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
const wait = typeof opts === 'boolean' ? opts : opts?.wait ?? false
|
|
184
|
-
const timeout = typeof opts === 'boolean' ? (opts === true ? 1000 : undefined) : opts?.timeout ?? 1000
|
|
185
|
-
|
|
186
|
-
if (wait) {
|
|
187
|
-
message.id = uuid()
|
|
188
|
-
|
|
189
|
-
const { promise, resolve, reject } = Promise.withResolvers()
|
|
190
|
-
|
|
191
|
-
const w = { finished: false, resolve, reject }
|
|
192
|
-
this.waitings.set(message.id, w)
|
|
193
|
-
|
|
194
|
-
if (timeout) {
|
|
195
|
-
setTimeout(() => {
|
|
196
|
-
if (!w.finished) {
|
|
197
|
-
console.log('reject by timeout', w.finished)
|
|
198
|
-
reject('WS request timeout: ' + JSON.stringify({ dto, opts }, null, 2))
|
|
199
|
-
}
|
|
200
|
-
}, timeout)
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
this.ws?.send(JSON.stringify(message))
|
|
204
|
-
|
|
205
|
-
return promise
|
|
206
|
-
} else {
|
|
207
|
-
return this.ws.send(JSON.stringify(message))
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
private async handleMessage(message: WsClientMessage) {
|
|
212
|
-
const handler = this.handlers.get(message.method)
|
|
213
|
-
if (handler) {
|
|
214
|
-
try {
|
|
215
|
-
const opts = { ...(this.opts.ctx ?? {}), message }
|
|
216
|
-
|
|
217
|
-
const data = await handler(opts as any)
|
|
218
|
-
|
|
219
|
-
if (data !== undefined) {
|
|
220
|
-
this.ws!.send(
|
|
221
|
-
JSON.stringify({
|
|
222
|
-
...message,
|
|
223
|
-
data,
|
|
224
|
-
method: 'response'
|
|
225
|
-
})
|
|
226
|
-
)
|
|
227
|
-
}
|
|
228
|
-
} catch (e) {
|
|
229
|
-
console.log(`WS: message #${message.id} - ${e}`)
|
|
230
|
-
}
|
|
231
|
-
} else if (message.method) {
|
|
232
|
-
console.log(`WS: message${message.id ? ' #' + message.id : ''} - no handler found "${message.method}"`)
|
|
233
|
-
} else {
|
|
234
|
-
console.log('WS: message', message)
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
}
|
package/old/client/types.ts
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
export type WsClientOptions<C extends unknown> = {
|
|
2
|
-
protocol?: string
|
|
3
|
-
host?: string
|
|
4
|
-
port?: number
|
|
5
|
-
ctx?: C
|
|
6
|
-
headers?: () => Promise<WsClientAuth[]> | WsClientAuth[]
|
|
7
|
-
|
|
8
|
-
autoReconnect?: boolean
|
|
9
|
-
pingInterval?: number
|
|
10
|
-
pingTimeout?: number
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export type WsClientAuth = { name: string; value: string }
|
|
14
|
-
|
|
15
|
-
export type WsClientMessage = {
|
|
16
|
-
method: string
|
|
17
|
-
id?: string
|
|
18
|
-
auth?: string
|
|
19
|
-
data?: any
|
|
20
|
-
error?: any
|
|
21
|
-
timestamp?: number
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export type WsClientHandler<C extends unknown> = (ctx: { message: WsClientMessage } & C) => any | Promise<any>
|
|
25
|
-
|
|
26
|
-
export type WsClientRequestOptions<W extends boolean> = { wait?: W; timeout?: number } | W
|
|
27
|
-
|
|
28
|
-
export type WsClientConnectionOptions = {
|
|
29
|
-
timeout?: number
|
|
30
|
-
}
|
package/old/client/utils.ts
DELETED
package/old/index.ts
DELETED
package/old/server/index.ts
DELETED
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
import { createHttpServer } from '@cuboapp/http-server'
|
|
2
|
-
import { uuid } from '@cuboapp/utils'
|
|
3
|
-
import { WebSocketServer } from 'ws'
|
|
4
|
-
|
|
5
|
-
import { WsServerMessage, WsServerOptions, WsServerRequestWaiting, WsServerSocket } from './types'
|
|
6
|
-
|
|
7
|
-
export * from './types'
|
|
8
|
-
export * from './utils'
|
|
9
|
-
|
|
10
|
-
export * from '@cuboapp/http-server'
|
|
11
|
-
|
|
12
|
-
export class WsServer<C extends unknown> {
|
|
13
|
-
public clients = new Set<WsServerSocket<C>>()
|
|
14
|
-
|
|
15
|
-
private ws: WebSocketServer
|
|
16
|
-
|
|
17
|
-
private handlers = new Map<string, WsServerHandler<C, any>>()
|
|
18
|
-
private waitings = new Map<string, WsServerRequestWaiting[]>()
|
|
19
|
-
|
|
20
|
-
constructor(
|
|
21
|
-
private opts: WsServerOptions<C>,
|
|
22
|
-
private httpServer = createHttpServer<C>({
|
|
23
|
-
host: opts.host,
|
|
24
|
-
port: opts.port,
|
|
25
|
-
...(opts?.http || {})
|
|
26
|
-
}),
|
|
27
|
-
public registerRoute = httpServer.registerRoute.bind(httpServer)
|
|
28
|
-
) {
|
|
29
|
-
// response handler
|
|
30
|
-
this.registerHandler('response', ({ message, client }) => {
|
|
31
|
-
if (message.id) {
|
|
32
|
-
const wait = this.waitings.get(message.id)?.find((c) => c.client_id === client.id)
|
|
33
|
-
|
|
34
|
-
if (wait) {
|
|
35
|
-
if (message.error) {
|
|
36
|
-
wait.reject(message.error)
|
|
37
|
-
} else {
|
|
38
|
-
wait.resolve(message.data)
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
})
|
|
43
|
-
|
|
44
|
-
this.ws = new WebSocketServer({
|
|
45
|
-
server: this.httpServer.getInstance(),
|
|
46
|
-
verifyClient: async (info, callback) => {
|
|
47
|
-
try {
|
|
48
|
-
if (this.opts?.auth?.default === true && !!this.opts?.auth?.handler) {
|
|
49
|
-
await this.opts?.auth?.handler({ server: this, request: info.req as any })
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
callback(true)
|
|
53
|
-
} catch (e: any) {
|
|
54
|
-
callback(false, e.statusCode ?? 400, `Ws:verifyClient - ${e.statusText ?? 'server error'}`)
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
})
|
|
58
|
-
|
|
59
|
-
this.ws.addListener('connection', (socket: WsServerSocket<C>, request: WsServerRequest<A>) => {
|
|
60
|
-
socket.id = uuid()
|
|
61
|
-
socket.auth = request.auth
|
|
62
|
-
|
|
63
|
-
console.log('Client "' + socket.id + '" connected')
|
|
64
|
-
|
|
65
|
-
socket.addListener('close', () => {
|
|
66
|
-
console.log('Client "' + socket.id + '" disconnected')
|
|
67
|
-
|
|
68
|
-
this.clients.delete(socket)
|
|
69
|
-
})
|
|
70
|
-
|
|
71
|
-
socket.addListener('message', (e) => {
|
|
72
|
-
try {
|
|
73
|
-
this.handleMessage(socket, JSON.parse(e.toString('utf-8'))).catch((e) => {
|
|
74
|
-
console.error('WS:message error', e)
|
|
75
|
-
})
|
|
76
|
-
} catch (e) {
|
|
77
|
-
console.error('WS:message fatal', e)
|
|
78
|
-
}
|
|
79
|
-
})
|
|
80
|
-
|
|
81
|
-
this.clients.add(socket)
|
|
82
|
-
})
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
public getStats() {
|
|
86
|
-
return {
|
|
87
|
-
queue: {
|
|
88
|
-
size: this.clients.size
|
|
89
|
-
},
|
|
90
|
-
handlers: {
|
|
91
|
-
size: this.handlers.size,
|
|
92
|
-
keys: Array.from(this.handlers.keys()).length
|
|
93
|
-
},
|
|
94
|
-
waitings: {
|
|
95
|
-
size: this.waitings.size,
|
|
96
|
-
keys: Array.from(this.waitings.keys()).length
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
async start() {
|
|
102
|
-
await this.httpServer.start()
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
async stop() {
|
|
106
|
-
await this.httpServer.stop()
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
public async registerHandler<D extends unknown>(name: string, handler: WsServerHandler<A, C, D>) {
|
|
110
|
-
this.handlers.set(name, handler)
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
public async clientRequest<T extends unknown, D extends unknown>(
|
|
114
|
-
dto: WsServerMessage<D> | string,
|
|
115
|
-
opts?: WsServerRequestOptions<A, true>
|
|
116
|
-
): Promise<T[]>
|
|
117
|
-
public async clientRequest<T extends unknown, D extends unknown>(
|
|
118
|
-
dto: WsServerMessage<D> | string,
|
|
119
|
-
opts?: WsServerRequestOptions<A, false>
|
|
120
|
-
): Promise<void>
|
|
121
|
-
public async clientRequest<T extends unknown, D extends unknown>(dto: WsServerMessage<D> | string, opts?: WsServerRequestOptions<A, boolean>) {
|
|
122
|
-
if (!this.ws) {
|
|
123
|
-
throw 'WS:request - not initied'
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
let message: WsServerMessage<D>
|
|
127
|
-
|
|
128
|
-
if (typeof dto === 'string') {
|
|
129
|
-
message = {
|
|
130
|
-
method: dto
|
|
131
|
-
}
|
|
132
|
-
} else {
|
|
133
|
-
message = dto
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
const wait = typeof opts === 'boolean' ? opts : opts?.wait ?? false
|
|
137
|
-
const timeout = typeof opts === 'boolean' ? (opts === true ? 1000 : undefined) : opts?.timeout ?? 1000
|
|
138
|
-
const filter = typeof opts === 'boolean' || !opts?.filter ? undefined : opts.filter
|
|
139
|
-
|
|
140
|
-
if (wait) {
|
|
141
|
-
message.id = uuid()
|
|
142
|
-
|
|
143
|
-
const watings: WsServerResponseWaiting[] = []
|
|
144
|
-
const promises: Promise<T>[] = []
|
|
145
|
-
|
|
146
|
-
this.clients.forEach((client) => {
|
|
147
|
-
if (!filter || filter(client)) {
|
|
148
|
-
const { promise, resolve, reject } = Promise.withResolvers<T>()
|
|
149
|
-
|
|
150
|
-
promises.push(promise)
|
|
151
|
-
|
|
152
|
-
watings.push({ client_id: client.id, reject, resolve })
|
|
153
|
-
|
|
154
|
-
client.send(JSON.stringify(message))
|
|
155
|
-
}
|
|
156
|
-
})
|
|
157
|
-
|
|
158
|
-
this.waitings.set(message.id, watings)
|
|
159
|
-
|
|
160
|
-
const result = Promise.allSettled(promises).then((res) => {
|
|
161
|
-
return res.filter((r) => r.status === 'fulfilled').map((r) => r.value as T)
|
|
162
|
-
})
|
|
163
|
-
|
|
164
|
-
if (timeout) {
|
|
165
|
-
return Promise.race([
|
|
166
|
-
result,
|
|
167
|
-
new Promise<never>((_, r) => {
|
|
168
|
-
setTimeout(r, timeout)
|
|
169
|
-
})
|
|
170
|
-
]).catch(() => {
|
|
171
|
-
console.log('Request timeout ' + message.id)
|
|
172
|
-
})
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
return result as Promise<T[]>
|
|
176
|
-
} else {
|
|
177
|
-
return this.clients.forEach((client) => {
|
|
178
|
-
if (!filter || filter(client)) {
|
|
179
|
-
client.send(JSON.stringify(message))
|
|
180
|
-
}
|
|
181
|
-
})
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
private async handleMessage(client: WsServerSocket<C>, message: WsServerMessage<unknown>) {
|
|
186
|
-
const handler = this.handlers.get(message.method)
|
|
187
|
-
|
|
188
|
-
if (handler) {
|
|
189
|
-
const data = await handler({ client, message })
|
|
190
|
-
if (data !== undefined) {
|
|
191
|
-
client.send(
|
|
192
|
-
JSON.stringify({
|
|
193
|
-
...message,
|
|
194
|
-
data,
|
|
195
|
-
method: 'response'
|
|
196
|
-
})
|
|
197
|
-
)
|
|
198
|
-
}
|
|
199
|
-
} else if (message.method) {
|
|
200
|
-
throw 'No handler defined "' + message.method + '"'
|
|
201
|
-
} else {
|
|
202
|
-
throw 'No handler defined in message'
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { HttpServerRequest, HttpServerResponse } from '@cuboapp/http-server'
|
|
2
|
-
|
|
3
|
-
import { WsServerRequestDto } from '../request'
|
|
4
|
-
import { WsServerMessage, WsServerTypicalResponse } from '../types'
|
|
5
|
-
|
|
6
|
-
export type WsServerRequestContext<C extends unknown, R extends unknown> = {
|
|
7
|
-
request: HttpServerRequest<C>
|
|
8
|
-
response: HttpServerResponse<C>
|
|
9
|
-
|
|
10
|
-
auth: C extends { auth?: any } ? C['auth'] : undefined
|
|
11
|
-
|
|
12
|
-
method: string
|
|
13
|
-
query: R extends WsServerRequestDto ? R['Query'] : Record<string, any>
|
|
14
|
-
|
|
15
|
-
message: WsServerMessage<R extends WsServerRequestDto ? R['Data'] : any>
|
|
16
|
-
} & R
|
|
17
|
-
|
|
18
|
-
export type WsServerRouteHandler<C extends unknown, R extends unknown> = (
|
|
19
|
-
ctx: WsServerRequestContext<C, R>
|
|
20
|
-
) => Promise<WsServerTypicalResponse> | WsServerTypicalResponse
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { IncomingMessage } from 'http'
|
|
2
|
-
|
|
3
|
-
export type WsServerRequestDto = {
|
|
4
|
-
Data?: any
|
|
5
|
-
Params?: Record<string, any>
|
|
6
|
-
Query?: Record<string, any>
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export interface WsServerRequest<C extends unknown> extends IncomingMessage {
|
|
10
|
-
auth: C extends { auth?: any } ? C['auth'] : undefined
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export type WsServerRequestWaiting = {
|
|
14
|
-
client_id: string
|
|
15
|
-
resolve: (res: any) => void
|
|
16
|
-
reject: (reason: any) => void
|
|
17
|
-
}
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { 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>> {}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { HttpServerOptions, WsServer } from '@/index'
|
|
2
|
-
|
|
3
|
-
import { WsServerRequest } from '../request'
|
|
4
|
-
|
|
5
|
-
export type WsServerOptions<C extends unknown> = {
|
|
6
|
-
host: string
|
|
7
|
-
port: number
|
|
8
|
-
auth?: {
|
|
9
|
-
default?: boolean
|
|
10
|
-
handler?: (ctx: { server: WsServer<C>; request: WsServerRequest<C> }) => Promise<void> | void
|
|
11
|
-
}
|
|
12
|
-
http?: Partial<HttpServerOptions<C>>
|
|
13
|
-
}
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import { IncomingMessage, ServerResponse } from 'http'
|
|
2
|
-
|
|
3
|
-
import { WsServerSocket } from './socket'
|
|
4
|
-
|
|
5
|
-
export type WsServerMessage<D extends unknown> = {
|
|
6
|
-
method: string
|
|
7
|
-
id?: string
|
|
8
|
-
error?: any
|
|
9
|
-
timestamp?: number
|
|
10
|
-
data?: D
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export type WsServerHandler<A extends unknown, C extends unknown, D extends unknown> = (
|
|
14
|
-
ctx: {
|
|
15
|
-
client: WsServerSocket<A>
|
|
16
|
-
message: WsServerMessage<D>
|
|
17
|
-
} & C
|
|
18
|
-
) => any | Promise<any>
|
|
19
|
-
|
|
20
|
-
export type WsServerRouteMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'
|
|
21
|
-
|
|
22
|
-
export type WsServerTypicalResponse =
|
|
23
|
-
| {
|
|
24
|
-
statusCode?: number
|
|
25
|
-
statusText?: string
|
|
26
|
-
data?: any
|
|
27
|
-
contentType?: 'application/json' | 'text/plain' | string
|
|
28
|
-
}
|
|
29
|
-
| Record<string, any>
|
|
30
|
-
| string
|
|
31
|
-
| boolean
|
|
32
|
-
| number
|
|
33
|
-
|
|
34
|
-
export type WsServerRoute<A extends unknown, C extends unknown, D extends unknown> = {
|
|
35
|
-
handler: WsServerRouteHandler<A, C, D>
|
|
36
|
-
opts?: WsServerRouteOptions
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export type WsServerRouteOptions = {
|
|
40
|
-
authorized?: boolean
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export type WsServerRouteHandler<A extends unknown, C extends unknown, D extends unknown> = (
|
|
44
|
-
ctx: {
|
|
45
|
-
request: IncomingMessage & { auth?: A }
|
|
46
|
-
response: ServerResponse<IncomingMessage> & {
|
|
47
|
-
req: IncomingMessage & { auth?: A }
|
|
48
|
-
}
|
|
49
|
-
query: Record<string, any>
|
|
50
|
-
body: any
|
|
51
|
-
message: WsServerMessage<D>
|
|
52
|
-
} & C
|
|
53
|
-
) => Promise<WsServerTypicalResponse> | WsServerTypicalResponse
|
|
54
|
-
|
|
55
|
-
export type WsServerRequestOptions<A extends unknown, W extends boolean> =
|
|
56
|
-
| {
|
|
57
|
-
wait?: W
|
|
58
|
-
timeout?: number
|
|
59
|
-
filter?: (client: WsServerSocket<A>) => boolean
|
|
60
|
-
}
|
|
61
|
-
| W
|
|
62
|
-
|
|
63
|
-
export type WsServerResponseWaiting = {
|
|
64
|
-
client_id: string
|
|
65
|
-
resolve: (res: any) => void
|
|
66
|
-
reject: (reason: any) => void
|
|
67
|
-
}
|
package/old/server/utils.ts
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { WsServer } from '.'
|
|
2
|
-
import { WsServerHandler, WsServerOptions, WsServerRouteHandler, WsServerRouteMethod, WsServerRouteOptions } from './types'
|
|
3
|
-
|
|
4
|
-
export function wsServerRoute<A extends unknown, C extends unknown, D extends unknown>(
|
|
5
|
-
method: WsServerRouteMethod,
|
|
6
|
-
name: string,
|
|
7
|
-
handler: WsServerRouteHandler<A, C, D>,
|
|
8
|
-
opts?: WsServerRouteOptions
|
|
9
|
-
) {
|
|
10
|
-
return {
|
|
11
|
-
method,
|
|
12
|
-
name,
|
|
13
|
-
handler,
|
|
14
|
-
opts
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export function wsServerHandler<A extends unknown, C extends unknown, D extends unknown>(name: string, handler: WsServerHandler<A, C, D>) {
|
|
19
|
-
return {
|
|
20
|
-
name,
|
|
21
|
-
handler
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export function createWsServer<A extends unknown, C extends unknown>(opts: WsServerOptions<A, C>) {
|
|
26
|
-
return new WsServer<A, C>(opts)
|
|
27
|
-
}
|