@cuboapp/ws 1.0.7 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cuboapp/ws",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "WebSockets",
5
5
  "main": "src/index.ts",
6
6
  "repository": "git@cuboapp.gitlab.yandexcloud.net:cubo/ws.git",
@@ -4,3 +4,8 @@ export const WsClientReadyState = {
4
4
  CLOSING: 2,
5
5
  CLOSED: 3
6
6
  }
7
+
8
+ export const WsClientEvent = {
9
+ CONNECTED: 'connected',
10
+ DISCONNECTED: 'disconnected'
11
+ }
@@ -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 { WsClientReadyState } from './constants'
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 get connected() {
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
- if (!this.connecting) {
52
- if (this.ws) {
53
- await this.disconnect().catch((e) => {})
54
- }
51
+ await this.connect(opts)
55
52
 
56
- await this.connect(opts)
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
- console.error('WS client - ping error', e)
58
+ if (this.opts?.debug) {
59
+ console.error('WS client - tick error', e)
60
+ }
61
+ this.setDisconnected()
63
62
  } finally {
64
- setTimeout(() => this.tick(opts), this.opts.pingInterval ?? 1000)
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
- public async disconnect() {
69
- if (this.disconnecting) {
70
- return this.disconnecting
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.ws = null
75
- return
81
+ this.connected = true
82
+ this.ee.emit(WsClientEvent.CONNECTED)
76
83
  }
84
+ }
77
85
 
78
- const { resolve, reject, promise } = Promise.withResolvers<void>()
79
- this.disconnecting = promise
86
+ private setDisconnected() {
87
+ if (this.connected) {
88
+ this.connected = false
89
+ this.ee.emit(WsClientEvent.DISCONNECTED)
90
+ }
91
+ }
80
92
 
81
- const timeout = setTimeout(() => reject('Timeout'), 1000)
93
+ public async disconnect() {
94
+ if (this.disconnecting) {
95
+ return this.disconnecting
96
+ }
82
97
 
83
- promise
84
- .catch((error) => {
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
- try {
93
- this.ws?.close(0)
94
- this.ws = null
101
+ try {
102
+ this.ws?.close(1000)
103
+ this.ws = null
95
104
 
96
- resolve()
97
- } catch (e) {
98
- reject('WS disconnect: ' + e)
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
- const { resolve, promise } = Promise.withResolvers<boolean>()
125
+ if (this.connected) {
126
+ await this.disconnect().catch((e) => {})
127
+ }
114
128
 
115
- this.connecting = Promise.race([
116
- promise
117
- .then(() => {
118
- console.log('WS client connected')
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(opts)
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
- const url = `${this.opts.protocol ?? 'ws'}://${this.opts.host}${this.opts.port ? ':' + this.opts.port : ''}`
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
- let token = ''
138
- if (this.opts?.authToken) {
139
- token = await this.opts.authToken()
140
- }
138
+ this.ws = new WebSocket(url, token)
141
139
 
142
- this.ws = new WebSocket(url, token || undefined)
140
+ this.registerHandler('init', ({ message }) => {
141
+ // clear timeout
142
+ clearTimeout(t)
143
143
 
144
- this.registerHandler('init', ({ message }) => {
145
- const { id, auth } = message.data as { id: string; auth: any }
144
+ try {
145
+ const { id, auth } = message.data as { id: string; auth: any }
146
146
 
147
- this.id = id
148
- this.auth = auth
147
+ this.id = id
148
+ this.auth = auth
149
149
 
150
- resolve(true)
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
- this.ws?.addEventListener('open', () => {})
161
+ this.ws?.addEventListener('message', (event: any) => {
162
+ this.handleMessage(JSON.parse(event.data))
163
+ })
154
164
 
155
- this.ws?.addEventListener('message', (event: any) => {
156
- this.handleMessage(JSON.parse(event.data))
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
- console.log(`WS: message #${message.id} - ${e}`)
247
+ if (this.opts.debug) {
248
+ console.log(`WS: message #${message.id} - ${e}`)
249
+ }
236
250
  }
237
251
  } else if (message.method) {
238
- console.log(`WS: message${message.id ? ' #' + message.id : ''} - no handler found "${message.method}"`)
252
+ if (this.opts.debug) {
253
+ console.log(`WS: message${message.id ? ' #' + message.id : ''} - no handler found "${message.method}"`)
254
+ }
239
255
  } else {
240
- console.log('WS: message', message)
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>