@cloudbase/database 1.3.0 → 1.4.1

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.
Files changed (210) hide show
  1. package/README.md +32 -10
  2. package/dist/commonjs/ObjectId/index.d.ts +11 -0
  3. package/dist/commonjs/ObjectId/index.js +21 -0
  4. package/dist/commonjs/aggregate.d.ts +29 -29
  5. package/dist/commonjs/aggregate.js +124 -124
  6. package/dist/commonjs/collection.d.ts +17 -17
  7. package/dist/commonjs/collection.js +72 -72
  8. package/dist/commonjs/command.d.ts +175 -175
  9. package/dist/commonjs/command.js +285 -285
  10. package/dist/commonjs/commands/logic.d.ts +24 -24
  11. package/dist/commonjs/commands/logic.js +79 -79
  12. package/dist/commonjs/commands/query.d.ts +73 -73
  13. package/dist/commonjs/commands/query.js +147 -147
  14. package/dist/commonjs/commands/update.d.ts +29 -29
  15. package/dist/commonjs/commands/update.js +49 -49
  16. package/dist/commonjs/config/app.config.d.ts +6 -6
  17. package/dist/commonjs/config/app.config.js +7 -7
  18. package/dist/commonjs/config/error.config.d.ts +3 -3
  19. package/dist/commonjs/config/error.config.js +15 -15
  20. package/dist/commonjs/const/code.d.ts +34 -34
  21. package/dist/commonjs/const/code.js +36 -36
  22. package/dist/commonjs/constant.d.ts +54 -54
  23. package/dist/commonjs/constant.js +76 -76
  24. package/dist/commonjs/document.d.ts +14 -14
  25. package/dist/commonjs/document.js +219 -219
  26. package/dist/commonjs/geo/index.d.ts +6 -6
  27. package/dist/commonjs/geo/index.js +11 -11
  28. package/dist/commonjs/geo/interface.d.ts +24 -24
  29. package/dist/commonjs/geo/interface.js +2 -2
  30. package/dist/commonjs/geo/lineString.d.ts +19 -19
  31. package/dist/commonjs/geo/lineString.js +57 -57
  32. package/dist/commonjs/geo/multiLineString.d.ts +18 -18
  33. package/dist/commonjs/geo/multiLineString.js +56 -56
  34. package/dist/commonjs/geo/multiPoint.d.ts +18 -18
  35. package/dist/commonjs/geo/multiPoint.js +50 -50
  36. package/dist/commonjs/geo/multiPolygon.d.ts +18 -18
  37. package/dist/commonjs/geo/multiPolygon.js +62 -62
  38. package/dist/commonjs/geo/point.d.ts +19 -19
  39. package/dist/commonjs/geo/point.js +43 -43
  40. package/dist/commonjs/geo/polygon.d.ts +19 -19
  41. package/dist/commonjs/geo/polygon.js +70 -70
  42. package/dist/commonjs/helper/symbol.d.ts +15 -14
  43. package/dist/commonjs/helper/symbol.js +20 -19
  44. package/dist/commonjs/index.d.ts +50 -49
  45. package/dist/commonjs/index.js +41 -39
  46. package/dist/commonjs/operator-map.d.ts +4 -4
  47. package/dist/commonjs/operator-map.js +23 -23
  48. package/dist/commonjs/query.d.ts +38 -38
  49. package/dist/commonjs/query.js +247 -247
  50. package/dist/commonjs/realtime/error.d.ts +7 -7
  51. package/dist/commonjs/realtime/error.js +11 -11
  52. package/dist/commonjs/realtime/listener.d.ts +14 -14
  53. package/dist/commonjs/realtime/listener.js +17 -17
  54. package/dist/commonjs/realtime/message.d.ts +3 -3
  55. package/dist/commonjs/realtime/message.js +10 -10
  56. package/dist/commonjs/realtime/snapshot.d.ts +16 -16
  57. package/dist/commonjs/realtime/snapshot.js +42 -42
  58. package/dist/commonjs/realtime/virtual-websocket-client.d.ts +63 -63
  59. package/dist/commonjs/realtime/virtual-websocket-client.js +736 -736
  60. package/dist/commonjs/realtime/websocket-client.d.ts +78 -78
  61. package/dist/commonjs/realtime/websocket-client.js +567 -567
  62. package/dist/commonjs/realtime/ws-event.d.ts +126 -126
  63. package/dist/commonjs/realtime/ws-event.js +139 -139
  64. package/dist/commonjs/regexp/index.d.ts +18 -18
  65. package/dist/commonjs/regexp/index.js +30 -30
  66. package/dist/commonjs/serializer/common.d.ts +11 -11
  67. package/dist/commonjs/serializer/common.js +90 -90
  68. package/dist/commonjs/serializer/datatype.d.ts +7 -7
  69. package/dist/commonjs/serializer/datatype.js +99 -96
  70. package/dist/commonjs/serializer/query.d.ts +8 -8
  71. package/dist/commonjs/serializer/query.js +254 -254
  72. package/dist/commonjs/serializer/update.d.ts +16 -16
  73. package/dist/commonjs/serializer/update.js +142 -142
  74. package/dist/commonjs/serverDate/index.d.ts +13 -13
  75. package/dist/commonjs/serverDate/index.js +23 -23
  76. package/dist/commonjs/transaction/index.d.ts +30 -30
  77. package/dist/commonjs/transaction/index.js +105 -105
  78. package/dist/commonjs/transaction.d.ts +42 -42
  79. package/dist/commonjs/transaction.js +126 -126
  80. package/dist/commonjs/typings/index.d.ts +45 -45
  81. package/dist/commonjs/typings/index.js +2 -2
  82. package/dist/commonjs/typings/realtime.d.ts +219 -219
  83. package/dist/commonjs/typings/realtime.js +2 -2
  84. package/dist/commonjs/util.d.ts +9 -9
  85. package/dist/commonjs/util.js +101 -101
  86. package/dist/commonjs/utils/error.d.ts +37 -37
  87. package/dist/commonjs/utils/error.js +55 -55
  88. package/dist/commonjs/utils/symbol.d.ts +8 -8
  89. package/dist/commonjs/utils/symbol.js +39 -39
  90. package/dist/commonjs/utils/type.d.ts +13 -13
  91. package/dist/commonjs/utils/type.js +22 -22
  92. package/dist/commonjs/utils/utils.d.ts +19 -19
  93. package/dist/commonjs/utils/utils.js +59 -59
  94. package/dist/commonjs/validate.d.ts +1 -1
  95. package/dist/commonjs/validate.js +155 -155
  96. package/dist/esm/ObjectId/index.d.ts +11 -0
  97. package/dist/esm/ObjectId/index.js +17 -0
  98. package/dist/esm/aggregate.d.ts +29 -29
  99. package/dist/esm/aggregate.js +121 -121
  100. package/dist/esm/collection.d.ts +17 -17
  101. package/dist/esm/collection.js +69 -69
  102. package/dist/esm/command.d.ts +175 -175
  103. package/dist/esm/command.js +281 -281
  104. package/dist/esm/commands/logic.d.ts +24 -24
  105. package/dist/esm/commands/logic.js +74 -74
  106. package/dist/esm/commands/query.d.ts +73 -73
  107. package/dist/esm/commands/query.js +141 -141
  108. package/dist/esm/commands/update.d.ts +29 -29
  109. package/dist/esm/commands/update.js +44 -44
  110. package/dist/esm/config/app.config.d.ts +6 -6
  111. package/dist/esm/config/app.config.js +5 -5
  112. package/dist/esm/config/error.config.d.ts +3 -3
  113. package/dist/esm/config/error.config.js +13 -13
  114. package/dist/esm/const/code.d.ts +34 -34
  115. package/dist/esm/const/code.js +34 -34
  116. package/dist/esm/constant.d.ts +54 -54
  117. package/dist/esm/constant.js +67 -67
  118. package/dist/esm/document.d.ts +14 -14
  119. package/dist/esm/document.js +216 -216
  120. package/dist/esm/geo/index.d.ts +6 -6
  121. package/dist/esm/geo/index.js +6 -6
  122. package/dist/esm/geo/interface.d.ts +24 -24
  123. package/dist/esm/geo/lineString.d.ts +19 -19
  124. package/dist/esm/geo/lineString.js +54 -54
  125. package/dist/esm/geo/multiLineString.d.ts +18 -18
  126. package/dist/esm/geo/multiLineString.js +53 -53
  127. package/dist/esm/geo/multiPoint.d.ts +18 -18
  128. package/dist/esm/geo/multiPoint.js +47 -47
  129. package/dist/esm/geo/multiPolygon.d.ts +18 -18
  130. package/dist/esm/geo/multiPolygon.js +59 -59
  131. package/dist/esm/geo/point.d.ts +19 -19
  132. package/dist/esm/geo/point.js +40 -40
  133. package/dist/esm/geo/polygon.d.ts +19 -19
  134. package/dist/esm/geo/polygon.js +67 -67
  135. package/dist/esm/helper/symbol.d.ts +15 -14
  136. package/dist/esm/helper/symbol.js +15 -14
  137. package/dist/esm/index.d.ts +50 -49
  138. package/dist/esm/index.js +35 -33
  139. package/dist/esm/operator-map.d.ts +4 -4
  140. package/dist/esm/operator-map.js +20 -20
  141. package/dist/esm/query.d.ts +38 -38
  142. package/dist/esm/query.js +244 -244
  143. package/dist/esm/realtime/error.d.ts +7 -7
  144. package/dist/esm/realtime/error.js +8 -8
  145. package/dist/esm/realtime/listener.d.ts +14 -14
  146. package/dist/esm/realtime/listener.js +14 -14
  147. package/dist/esm/realtime/message.d.ts +3 -3
  148. package/dist/esm/realtime/message.js +6 -6
  149. package/dist/esm/realtime/snapshot.d.ts +16 -16
  150. package/dist/esm/realtime/snapshot.js +39 -39
  151. package/dist/esm/realtime/virtual-websocket-client.d.ts +63 -63
  152. package/dist/esm/realtime/virtual-websocket-client.js +733 -733
  153. package/dist/esm/realtime/websocket-client.d.ts +78 -78
  154. package/dist/esm/realtime/websocket-client.js +564 -564
  155. package/dist/esm/realtime/ws-event.d.ts +126 -126
  156. package/dist/esm/realtime/ws-event.js +137 -137
  157. package/dist/esm/regexp/index.d.ts +18 -18
  158. package/dist/esm/regexp/index.js +26 -26
  159. package/dist/esm/serializer/common.d.ts +11 -11
  160. package/dist/esm/serializer/common.js +82 -82
  161. package/dist/esm/serializer/datatype.d.ts +7 -7
  162. package/dist/esm/serializer/datatype.js +95 -92
  163. package/dist/esm/serializer/query.d.ts +8 -8
  164. package/dist/esm/serializer/query.js +251 -251
  165. package/dist/esm/serializer/update.d.ts +16 -16
  166. package/dist/esm/serializer/update.js +139 -139
  167. package/dist/esm/serverDate/index.d.ts +13 -13
  168. package/dist/esm/serverDate/index.js +19 -19
  169. package/dist/esm/transaction/index.d.ts +30 -30
  170. package/dist/esm/transaction/index.js +100 -100
  171. package/dist/esm/transaction.d.ts +42 -42
  172. package/dist/esm/transaction.js +121 -121
  173. package/dist/esm/typings/index.d.ts +45 -45
  174. package/dist/esm/typings/realtime.d.ts +219 -219
  175. package/dist/esm/util.d.ts +9 -9
  176. package/dist/esm/util.js +98 -98
  177. package/dist/esm/utils/error.d.ts +37 -37
  178. package/dist/esm/utils/error.js +49 -49
  179. package/dist/esm/utils/symbol.d.ts +8 -8
  180. package/dist/esm/utils/symbol.js +36 -36
  181. package/dist/esm/utils/type.d.ts +13 -13
  182. package/dist/esm/utils/type.js +20 -20
  183. package/dist/esm/utils/utils.d.ts +19 -19
  184. package/dist/esm/utils/utils.js +55 -55
  185. package/dist/esm/validate.d.ts +1 -1
  186. package/dist/esm/validate.js +152 -152
  187. package/package.json +1 -1
  188. package/src/ObjectId/index.ts +23 -0
  189. package/src/aggregate.ts +8 -5
  190. package/src/helper/symbol.ts +2 -0
  191. package/src/index.ts +4 -0
  192. package/src/serializer/datatype.ts +5 -1
  193. package/dist/commonjs/decimal128/index.d.ts +0 -8
  194. package/dist/commonjs/decimal128/index.js +0 -26
  195. package/dist/commonjs/lib/util.d.ts +0 -1
  196. package/dist/commonjs/lib/util.js +0 -25
  197. package/dist/commonjs/transaction/collection.d.ts +0 -7
  198. package/dist/commonjs/transaction/collection.js +0 -46
  199. package/dist/commonjs/transaction/document.d.ts +0 -27
  200. package/dist/commonjs/transaction/document.js +0 -205
  201. package/dist/commonjs/transaction/query.d.ts +0 -5
  202. package/dist/commonjs/transaction/query.js +0 -10
  203. package/dist/esm/lib/util.d.ts +0 -1
  204. package/dist/esm/lib/util.js +0 -23
  205. package/dist/esm/transaction/collection.d.ts +0 -7
  206. package/dist/esm/transaction/collection.js +0 -44
  207. package/dist/esm/transaction/document.d.ts +0 -27
  208. package/dist/esm/transaction/document.js +0 -203
  209. package/dist/esm/transaction/query.d.ts +0 -5
  210. package/dist/esm/transaction/query.js +0 -8
@@ -1,564 +1,564 @@
1
- import { VirtualWebSocketClient } from './virtual-websocket-client';
2
- import { sleep } from '../utils/utils';
3
- import { genRequestId } from './message';
4
- import { CLOSE_EVENT_CODE, CLOSE_EVENT_CODE_INFO, getWSCloseError } from './ws-event';
5
- import { CloudSDKError, TimeoutError } from '../utils/error';
6
- import { RealtimeErrorMessageError } from './error';
7
- import { ERR_CODE } from '../config/error.config';
8
- import { Db } from '../';
9
- const WS_READY_STATE = {
10
- CONNECTING: 0,
11
- OPEN: 1,
12
- CLOSING: 2,
13
- CLOSED: 3
14
- };
15
- const MAX_RTT_OBSERVED = 3;
16
- const DEFAULT_EXPECTED_EVENT_WAIT_TIME = 5000;
17
- const DEFAULT_UNTRUSTED_RTT_THRESHOLD = 10000;
18
- const DEFAULT_MAX_RECONNECT = 5;
19
- const DEFAULT_WS_RECONNECT_INTERVAL = 10000;
20
- const DEFAULT_PING_FAIL_TOLERANCE = 2;
21
- const DEFAULT_PONG_MISS_TOLERANCE = 2;
22
- const DEFAULT_LOGIN_TIMEOUT = 5000;
23
- export class RealtimeWebSocketClient {
24
- constructor(options) {
25
- this._virtualWSClient = new Set();
26
- this._queryIdClientMap = new Map();
27
- this._watchIdClientMap = new Map();
28
- this._pingFailed = 0;
29
- this._pongMissed = 0;
30
- this._logins = new Map();
31
- this._wsReadySubsribers = [];
32
- this._wsResponseWait = new Map();
33
- this._rttObserved = [];
34
- this.initWebSocketConnection = async (reconnect, availableRetries = this._maxReconnect) => {
35
- if (reconnect && this._reconnectState) {
36
- return;
37
- }
38
- if (reconnect) {
39
- this._reconnectState = true;
40
- }
41
- if (this._wsInitPromise) {
42
- return this._wsInitPromise;
43
- }
44
- if (reconnect) {
45
- this.pauseClients();
46
- }
47
- this.close(CLOSE_EVENT_CODE.ReconnectWebSocket);
48
- this._wsInitPromise = new Promise(async (resolve, reject) => {
49
- try {
50
- const wsSign = await this.getWsSign();
51
- await new Promise(success => {
52
- const url = wsSign.wsUrl || 'wss://tcb-ws.tencentcloudapi.com';
53
- this._ws = Db.wsClass ? new Db.wsClass(url) : new WebSocket(url);
54
- success();
55
- });
56
- if (this._ws.connect) {
57
- await this._ws.connect();
58
- }
59
- await this.initWebSocketEvent();
60
- resolve();
61
- if (reconnect) {
62
- this.resumeClients();
63
- this._reconnectState = false;
64
- }
65
- }
66
- catch (e) {
67
- console.error('[realtime] initWebSocketConnection connect fail', e);
68
- if (availableRetries > 0) {
69
- const isConnected = true;
70
- this._wsInitPromise = undefined;
71
- if (isConnected) {
72
- await sleep(this._reconnectInterval);
73
- if (reconnect) {
74
- this._reconnectState = false;
75
- }
76
- }
77
- resolve(this.initWebSocketConnection(reconnect, availableRetries - 1));
78
- }
79
- else {
80
- reject(e);
81
- if (reconnect) {
82
- this.closeAllClients(new CloudSDKError({
83
- errCode: ERR_CODE.SDK_DATABASE_REALTIME_LISTENER_RECONNECT_WATCH_FAIL,
84
- errMsg: e
85
- }));
86
- }
87
- }
88
- }
89
- });
90
- try {
91
- await this._wsInitPromise;
92
- this._wsReadySubsribers.forEach(({ resolve }) => resolve());
93
- }
94
- catch (e) {
95
- this._wsReadySubsribers.forEach(({ reject }) => reject());
96
- }
97
- finally {
98
- this._wsInitPromise = undefined;
99
- this._wsReadySubsribers = [];
100
- }
101
- };
102
- this.initWebSocketEvent = () => new Promise((resolve, reject) => {
103
- if (!this._ws) {
104
- throw new Error('can not initWebSocketEvent, ws not exists');
105
- }
106
- let wsOpened = false;
107
- this._ws.onopen = event => {
108
- console.warn('[realtime] ws event: open', event);
109
- wsOpened = true;
110
- resolve();
111
- };
112
- this._ws.onerror = event => {
113
- this._logins = new Map();
114
- if (!wsOpened) {
115
- console.error('[realtime] ws open failed with ws event: error', event);
116
- reject(event);
117
- }
118
- else {
119
- console.error('[realtime] ws event: error', event);
120
- this.clearHeartbeat();
121
- this._virtualWSClient.forEach(client => client.closeWithError(new CloudSDKError({
122
- errCode: ERR_CODE.SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_ERROR,
123
- errMsg: event
124
- })));
125
- }
126
- };
127
- this._ws.onclose = closeEvent => {
128
- console.warn('[realtime] ws event: close', closeEvent);
129
- this._logins = new Map();
130
- this.clearHeartbeat();
131
- switch (closeEvent.code) {
132
- case CLOSE_EVENT_CODE.ReconnectWebSocket: {
133
- break;
134
- }
135
- case CLOSE_EVENT_CODE.NoRealtimeListeners: {
136
- break;
137
- }
138
- case CLOSE_EVENT_CODE.HeartbeatPingError:
139
- case CLOSE_EVENT_CODE.HeartbeatPongTimeoutError:
140
- case CLOSE_EVENT_CODE.NormalClosure:
141
- case CLOSE_EVENT_CODE.AbnormalClosure: {
142
- if (this._maxReconnect > 0) {
143
- this.initWebSocketConnection(true, this._maxReconnect);
144
- }
145
- else {
146
- this.closeAllClients(getWSCloseError(closeEvent.code));
147
- }
148
- break;
149
- }
150
- case CLOSE_EVENT_CODE.NoAuthentication: {
151
- this.closeAllClients(getWSCloseError(closeEvent.code, closeEvent.reason));
152
- break;
153
- }
154
- default: {
155
- if (this._maxReconnect > 0) {
156
- this.initWebSocketConnection(true, this._maxReconnect);
157
- }
158
- else {
159
- this.closeAllClients(getWSCloseError(closeEvent.code));
160
- }
161
- }
162
- }
163
- };
164
- this._ws.onmessage = res => {
165
- const rawMsg = res.data;
166
- this.heartbeat();
167
- let msg;
168
- try {
169
- msg = JSON.parse(rawMsg);
170
- }
171
- catch (e) {
172
- throw new Error(`[realtime] onMessage parse res.data error: ${e}`);
173
- }
174
- if (msg.msgType === 'ERROR') {
175
- let virtualWatch = null;
176
- this._virtualWSClient.forEach(item => {
177
- if (item.watchId === msg.watchId) {
178
- virtualWatch = item;
179
- }
180
- });
181
- if (virtualWatch) {
182
- virtualWatch.listener.onError(msg);
183
- }
184
- }
185
- const responseWaitSpec = this._wsResponseWait.get(msg.requestId);
186
- if (responseWaitSpec) {
187
- try {
188
- if (msg.msgType === 'ERROR') {
189
- responseWaitSpec.reject(new RealtimeErrorMessageError(msg));
190
- }
191
- else {
192
- responseWaitSpec.resolve(msg);
193
- }
194
- }
195
- catch (e) {
196
- console.error('ws onMessage responseWaitSpec.resolve(msg) errored:', e);
197
- }
198
- finally {
199
- this._wsResponseWait.delete(msg.requestId);
200
- }
201
- if (responseWaitSpec.skipOnMessage) {
202
- return;
203
- }
204
- }
205
- if (msg.msgType === 'PONG') {
206
- if (this._lastPingSendTS) {
207
- const rtt = Date.now() - this._lastPingSendTS;
208
- if (rtt > DEFAULT_UNTRUSTED_RTT_THRESHOLD) {
209
- console.warn(`[realtime] untrusted rtt observed: ${rtt}`);
210
- return;
211
- }
212
- if (this._rttObserved.length >= MAX_RTT_OBSERVED) {
213
- this._rttObserved.splice(0, this._rttObserved.length - MAX_RTT_OBSERVED + 1);
214
- }
215
- this._rttObserved.push(rtt);
216
- }
217
- return;
218
- }
219
- let client = msg.watchId && this._watchIdClientMap.get(msg.watchId);
220
- if (client) {
221
- client.onMessage(msg);
222
- }
223
- else {
224
- console.error(`[realtime] no realtime listener found responsible for watchId ${msg.watchId}: `, msg);
225
- switch (msg.msgType) {
226
- case 'INIT_EVENT':
227
- case 'NEXT_EVENT':
228
- case 'CHECK_EVENT': {
229
- client = this._queryIdClientMap.get(msg.msgData.queryID);
230
- if (client) {
231
- client.onMessage(msg);
232
- }
233
- break;
234
- }
235
- default: {
236
- for (const [, client] of this._watchIdClientMap) {
237
- client.onMessage(msg);
238
- break;
239
- }
240
- }
241
- }
242
- }
243
- };
244
- this.heartbeat();
245
- });
246
- this.isWSConnected = () => {
247
- return Boolean(this._ws && this._ws.readyState === WS_READY_STATE.OPEN);
248
- };
249
- this.onceWSConnected = async () => {
250
- if (this.isWSConnected()) {
251
- return;
252
- }
253
- if (this._wsInitPromise) {
254
- return this._wsInitPromise;
255
- }
256
- return new Promise((resolve, reject) => {
257
- this._wsReadySubsribers.push({
258
- resolve,
259
- reject
260
- });
261
- });
262
- };
263
- this.webLogin = async (envId, refresh) => {
264
- if (!refresh) {
265
- if (envId) {
266
- const loginInfo = this._logins.get(envId);
267
- if (loginInfo) {
268
- if (loginInfo.loggedIn && loginInfo.loginResult) {
269
- return loginInfo.loginResult;
270
- }
271
- else if (loginInfo.loggingInPromise) {
272
- return loginInfo.loggingInPromise;
273
- }
274
- }
275
- }
276
- else {
277
- const emptyEnvLoginInfo = this._logins.get('');
278
- if (emptyEnvLoginInfo && emptyEnvLoginInfo.loggingInPromise) {
279
- return emptyEnvLoginInfo.loggingInPromise;
280
- }
281
- }
282
- }
283
- const promise = new Promise(async (resolve, reject) => {
284
- try {
285
- const wsSign = await this.getWsSign();
286
- const msgData = {
287
- envId: wsSign.envId || '',
288
- accessToken: '',
289
- referrer: 'web',
290
- sdkVersion: '',
291
- dataVersion: Db.dataVersion || ''
292
- };
293
- const loginMsg = {
294
- watchId: undefined,
295
- requestId: genRequestId(),
296
- msgType: 'LOGIN',
297
- msgData,
298
- exMsgData: {
299
- runtime: Db.runtime,
300
- signStr: wsSign.signStr,
301
- secretVersion: wsSign.secretVersion
302
- }
303
- };
304
- const loginResMsg = await this.send({
305
- msg: loginMsg,
306
- waitResponse: true,
307
- skipOnMessage: true,
308
- timeout: DEFAULT_LOGIN_TIMEOUT
309
- });
310
- if (!loginResMsg.msgData.code) {
311
- resolve({
312
- envId: wsSign.envId
313
- });
314
- }
315
- else {
316
- reject(new Error(`${loginResMsg.msgData.code} ${loginResMsg.msgData.message}`));
317
- }
318
- }
319
- catch (e) {
320
- reject(e);
321
- }
322
- });
323
- let loginInfo = envId && this._logins.get(envId);
324
- const loginStartTS = Date.now();
325
- if (loginInfo) {
326
- loginInfo.loggedIn = false;
327
- loginInfo.loggingInPromise = promise;
328
- loginInfo.loginStartTS = loginStartTS;
329
- }
330
- else {
331
- loginInfo = {
332
- loggedIn: false,
333
- loggingInPromise: promise,
334
- loginStartTS
335
- };
336
- this._logins.set(envId || '', loginInfo);
337
- }
338
- try {
339
- const loginResult = await promise;
340
- const curLoginInfo = envId && this._logins.get(envId);
341
- if (curLoginInfo &&
342
- curLoginInfo === loginInfo &&
343
- curLoginInfo.loginStartTS === loginStartTS) {
344
- loginInfo.loggedIn = true;
345
- loginInfo.loggingInPromise = undefined;
346
- loginInfo.loginStartTS = undefined;
347
- loginInfo.loginResult = loginResult;
348
- return loginResult;
349
- }
350
- else if (curLoginInfo) {
351
- if (curLoginInfo.loggedIn && curLoginInfo.loginResult) {
352
- return curLoginInfo.loginResult;
353
- }
354
- else if (curLoginInfo.loggingInPromise) {
355
- return curLoginInfo.loggingInPromise;
356
- }
357
- else {
358
- throw new Error('ws unexpected login info');
359
- }
360
- }
361
- else {
362
- throw new Error('ws login info reset');
363
- }
364
- }
365
- catch (e) {
366
- loginInfo.loggedIn = false;
367
- loginInfo.loggingInPromise = undefined;
368
- loginInfo.loginStartTS = undefined;
369
- loginInfo.loginResult = undefined;
370
- throw e;
371
- }
372
- };
373
- this.getWsSign = async () => {
374
- if (this._wsSign && this._wsSign.expiredTs > Date.now()) {
375
- return this._wsSign;
376
- }
377
- const expiredTs = Date.now() + 60000;
378
- const res = await this._context.appConfig.request.send('auth.wsWebSign', { runtime: Db.runtime });
379
- if (res.code) {
380
- throw new Error(`[tcb-js-sdk] 获取实时数据推送登录票据失败: ${res.code}`);
381
- }
382
- if (res.data) {
383
- const { signStr, wsUrl, secretVersion, envId } = res.data;
384
- return {
385
- signStr,
386
- wsUrl,
387
- secretVersion,
388
- envId,
389
- expiredTs
390
- };
391
- }
392
- else {
393
- throw new Error('[tcb-js-sdk] 获取实时数据推送登录票据失败');
394
- }
395
- };
396
- this.getWaitExpectedTimeoutLength = () => {
397
- if (!this._rttObserved.length) {
398
- return DEFAULT_EXPECTED_EVENT_WAIT_TIME;
399
- }
400
- return ((this._rttObserved.reduce((acc, cur) => acc + cur) /
401
- this._rttObserved.length) *
402
- 1.5);
403
- };
404
- this.ping = async () => {
405
- const msg = {
406
- watchId: undefined,
407
- requestId: genRequestId(),
408
- msgType: 'PING',
409
- msgData: null
410
- };
411
- await this.send({
412
- msg
413
- });
414
- };
415
- this.send = async (opts) => new Promise(async (_resolve, _reject) => {
416
- let timeoutId;
417
- let _hasResolved = false;
418
- let _hasRejected = false;
419
- const resolve = (value) => {
420
- _hasResolved = true;
421
- timeoutId && clearTimeout(timeoutId);
422
- _resolve(value);
423
- };
424
- const reject = (error) => {
425
- _hasRejected = true;
426
- timeoutId && clearTimeout(timeoutId);
427
- _reject(error);
428
- };
429
- if (opts.timeout) {
430
- timeoutId = setTimeout(async () => {
431
- if (!_hasResolved || !_hasRejected) {
432
- await sleep(0);
433
- if (!_hasResolved || !_hasRejected) {
434
- reject(new TimeoutError('wsclient.send timedout'));
435
- }
436
- }
437
- }, opts.timeout);
438
- }
439
- try {
440
- if (this._wsInitPromise) {
441
- await this._wsInitPromise;
442
- }
443
- if (!this._ws) {
444
- reject(new Error('invalid state: ws connection not exists, can not send message'));
445
- return;
446
- }
447
- if (this._ws.readyState !== WS_READY_STATE.OPEN) {
448
- reject(new Error(`ws readyState invalid: ${this._ws.readyState}, can not send message`));
449
- return;
450
- }
451
- if (opts.waitResponse) {
452
- this._wsResponseWait.set(opts.msg.requestId, {
453
- resolve,
454
- reject,
455
- skipOnMessage: opts.skipOnMessage
456
- });
457
- }
458
- try {
459
- await this._ws.send(JSON.stringify(opts.msg));
460
- if (!opts.waitResponse) {
461
- resolve();
462
- }
463
- }
464
- catch (err) {
465
- if (err) {
466
- reject(err);
467
- if (opts.waitResponse) {
468
- this._wsResponseWait.delete(opts.msg.requestId);
469
- }
470
- }
471
- }
472
- }
473
- catch (e) {
474
- reject(e);
475
- }
476
- });
477
- this.closeAllClients = (error) => {
478
- this._virtualWSClient.forEach(client => {
479
- client.closeWithError(error);
480
- });
481
- };
482
- this.pauseClients = (clients) => {
483
- ;
484
- (clients || this._virtualWSClient).forEach(client => {
485
- client.pause();
486
- });
487
- };
488
- this.resumeClients = (clients) => {
489
- ;
490
- (clients || this._virtualWSClient).forEach(client => {
491
- client.resume();
492
- });
493
- };
494
- this.onWatchStart = (client, queryID) => {
495
- this._queryIdClientMap.set(queryID, client);
496
- };
497
- this.onWatchClose = (client, queryID) => {
498
- if (queryID) {
499
- this._queryIdClientMap.delete(queryID);
500
- }
501
- this._watchIdClientMap.delete(client.watchId);
502
- this._virtualWSClient.delete(client);
503
- if (!this._virtualWSClient.size) {
504
- this.close(CLOSE_EVENT_CODE.NoRealtimeListeners);
505
- }
506
- };
507
- this._maxReconnect = options.maxReconnect || DEFAULT_MAX_RECONNECT;
508
- this._reconnectInterval =
509
- options.reconnectInterval || DEFAULT_WS_RECONNECT_INTERVAL;
510
- this._context = options.context;
511
- }
512
- heartbeat(immediate) {
513
- this.clearHeartbeat();
514
- this._pingTimeoutId = setTimeout(async () => {
515
- try {
516
- if (!this._ws || this._ws.readyState !== WS_READY_STATE.OPEN) {
517
- return;
518
- }
519
- this._lastPingSendTS = Date.now();
520
- await this.ping();
521
- this._pingFailed = 0;
522
- this._pongTimeoutId = setTimeout(() => {
523
- console.error('pong timed out');
524
- if (this._pongMissed < DEFAULT_PONG_MISS_TOLERANCE) {
525
- this._pongMissed++;
526
- this.heartbeat(true);
527
- }
528
- else {
529
- this.initWebSocketConnection(true);
530
- }
531
- }, this._context.appConfig.realtimePongWaitTimeout);
532
- }
533
- catch (e) {
534
- if (this._pingFailed < DEFAULT_PING_FAIL_TOLERANCE) {
535
- this._pingFailed++;
536
- this.heartbeat();
537
- }
538
- else {
539
- this.close(CLOSE_EVENT_CODE.HeartbeatPingError);
540
- }
541
- }
542
- }, immediate ? 0 : this._context.appConfig.realtimePingInterval);
543
- }
544
- clearHeartbeat() {
545
- this._pingTimeoutId && clearTimeout(this._pingTimeoutId);
546
- this._pongTimeoutId && clearTimeout(this._pongTimeoutId);
547
- }
548
- close(code) {
549
- this.clearHeartbeat();
550
- if (this._ws) {
551
- this._ws.close(code, CLOSE_EVENT_CODE_INFO[code].name);
552
- this._ws = undefined;
553
- }
554
- }
555
- watch(options) {
556
- if (!this._ws && !this._wsInitPromise) {
557
- this.initWebSocketConnection(false);
558
- }
559
- const virtualClient = new VirtualWebSocketClient(Object.assign(Object.assign({}, options), { send: this.send, login: this.webLogin, isWSConnected: this.isWSConnected, onceWSConnected: this.onceWSConnected, getWaitExpectedTimeoutLength: this.getWaitExpectedTimeoutLength, onWatchStart: this.onWatchStart, onWatchClose: this.onWatchClose, debug: true }));
560
- this._virtualWSClient.add(virtualClient);
561
- this._watchIdClientMap.set(virtualClient.watchId, virtualClient);
562
- return virtualClient.listener;
563
- }
564
- }
1
+ import { VirtualWebSocketClient } from './virtual-websocket-client';
2
+ import { sleep } from '../utils/utils';
3
+ import { genRequestId } from './message';
4
+ import { CLOSE_EVENT_CODE, CLOSE_EVENT_CODE_INFO, getWSCloseError } from './ws-event';
5
+ import { CloudSDKError, TimeoutError } from '../utils/error';
6
+ import { RealtimeErrorMessageError } from './error';
7
+ import { ERR_CODE } from '../config/error.config';
8
+ import { Db } from '../';
9
+ const WS_READY_STATE = {
10
+ CONNECTING: 0,
11
+ OPEN: 1,
12
+ CLOSING: 2,
13
+ CLOSED: 3
14
+ };
15
+ const MAX_RTT_OBSERVED = 3;
16
+ const DEFAULT_EXPECTED_EVENT_WAIT_TIME = 5000;
17
+ const DEFAULT_UNTRUSTED_RTT_THRESHOLD = 10000;
18
+ const DEFAULT_MAX_RECONNECT = 5;
19
+ const DEFAULT_WS_RECONNECT_INTERVAL = 10000;
20
+ const DEFAULT_PING_FAIL_TOLERANCE = 2;
21
+ const DEFAULT_PONG_MISS_TOLERANCE = 2;
22
+ const DEFAULT_LOGIN_TIMEOUT = 5000;
23
+ export class RealtimeWebSocketClient {
24
+ constructor(options) {
25
+ this._virtualWSClient = new Set();
26
+ this._queryIdClientMap = new Map();
27
+ this._watchIdClientMap = new Map();
28
+ this._pingFailed = 0;
29
+ this._pongMissed = 0;
30
+ this._logins = new Map();
31
+ this._wsReadySubsribers = [];
32
+ this._wsResponseWait = new Map();
33
+ this._rttObserved = [];
34
+ this.initWebSocketConnection = async (reconnect, availableRetries = this._maxReconnect) => {
35
+ if (reconnect && this._reconnectState) {
36
+ return;
37
+ }
38
+ if (reconnect) {
39
+ this._reconnectState = true;
40
+ }
41
+ if (this._wsInitPromise) {
42
+ return this._wsInitPromise;
43
+ }
44
+ if (reconnect) {
45
+ this.pauseClients();
46
+ }
47
+ this.close(CLOSE_EVENT_CODE.ReconnectWebSocket);
48
+ this._wsInitPromise = new Promise(async (resolve, reject) => {
49
+ try {
50
+ const wsSign = await this.getWsSign();
51
+ await new Promise(success => {
52
+ const url = wsSign.wsUrl || 'wss://tcb-ws.tencentcloudapi.com';
53
+ this._ws = Db.wsClass ? new Db.wsClass(url) : new WebSocket(url);
54
+ success();
55
+ });
56
+ if (this._ws.connect) {
57
+ await this._ws.connect();
58
+ }
59
+ await this.initWebSocketEvent();
60
+ resolve();
61
+ if (reconnect) {
62
+ this.resumeClients();
63
+ this._reconnectState = false;
64
+ }
65
+ }
66
+ catch (e) {
67
+ console.error('[realtime] initWebSocketConnection connect fail', e);
68
+ if (availableRetries > 0) {
69
+ const isConnected = true;
70
+ this._wsInitPromise = undefined;
71
+ if (isConnected) {
72
+ await sleep(this._reconnectInterval);
73
+ if (reconnect) {
74
+ this._reconnectState = false;
75
+ }
76
+ }
77
+ resolve(this.initWebSocketConnection(reconnect, availableRetries - 1));
78
+ }
79
+ else {
80
+ reject(e);
81
+ if (reconnect) {
82
+ this.closeAllClients(new CloudSDKError({
83
+ errCode: ERR_CODE.SDK_DATABASE_REALTIME_LISTENER_RECONNECT_WATCH_FAIL,
84
+ errMsg: e
85
+ }));
86
+ }
87
+ }
88
+ }
89
+ });
90
+ try {
91
+ await this._wsInitPromise;
92
+ this._wsReadySubsribers.forEach(({ resolve }) => resolve());
93
+ }
94
+ catch (e) {
95
+ this._wsReadySubsribers.forEach(({ reject }) => reject());
96
+ }
97
+ finally {
98
+ this._wsInitPromise = undefined;
99
+ this._wsReadySubsribers = [];
100
+ }
101
+ };
102
+ this.initWebSocketEvent = () => new Promise((resolve, reject) => {
103
+ if (!this._ws) {
104
+ throw new Error('can not initWebSocketEvent, ws not exists');
105
+ }
106
+ let wsOpened = false;
107
+ this._ws.onopen = event => {
108
+ console.warn('[realtime] ws event: open', event);
109
+ wsOpened = true;
110
+ resolve();
111
+ };
112
+ this._ws.onerror = event => {
113
+ this._logins = new Map();
114
+ if (!wsOpened) {
115
+ console.error('[realtime] ws open failed with ws event: error', event);
116
+ reject(event);
117
+ }
118
+ else {
119
+ console.error('[realtime] ws event: error', event);
120
+ this.clearHeartbeat();
121
+ this._virtualWSClient.forEach(client => client.closeWithError(new CloudSDKError({
122
+ errCode: ERR_CODE.SDK_DATABASE_REALTIME_LISTENER_WEBSOCKET_CONNECTION_ERROR,
123
+ errMsg: event
124
+ })));
125
+ }
126
+ };
127
+ this._ws.onclose = closeEvent => {
128
+ console.warn('[realtime] ws event: close', closeEvent);
129
+ this._logins = new Map();
130
+ this.clearHeartbeat();
131
+ switch (closeEvent.code) {
132
+ case CLOSE_EVENT_CODE.ReconnectWebSocket: {
133
+ break;
134
+ }
135
+ case CLOSE_EVENT_CODE.NoRealtimeListeners: {
136
+ break;
137
+ }
138
+ case CLOSE_EVENT_CODE.HeartbeatPingError:
139
+ case CLOSE_EVENT_CODE.HeartbeatPongTimeoutError:
140
+ case CLOSE_EVENT_CODE.NormalClosure:
141
+ case CLOSE_EVENT_CODE.AbnormalClosure: {
142
+ if (this._maxReconnect > 0) {
143
+ this.initWebSocketConnection(true, this._maxReconnect);
144
+ }
145
+ else {
146
+ this.closeAllClients(getWSCloseError(closeEvent.code));
147
+ }
148
+ break;
149
+ }
150
+ case CLOSE_EVENT_CODE.NoAuthentication: {
151
+ this.closeAllClients(getWSCloseError(closeEvent.code, closeEvent.reason));
152
+ break;
153
+ }
154
+ default: {
155
+ if (this._maxReconnect > 0) {
156
+ this.initWebSocketConnection(true, this._maxReconnect);
157
+ }
158
+ else {
159
+ this.closeAllClients(getWSCloseError(closeEvent.code));
160
+ }
161
+ }
162
+ }
163
+ };
164
+ this._ws.onmessage = res => {
165
+ const rawMsg = res.data;
166
+ this.heartbeat();
167
+ let msg;
168
+ try {
169
+ msg = JSON.parse(rawMsg);
170
+ }
171
+ catch (e) {
172
+ throw new Error(`[realtime] onMessage parse res.data error: ${e}`);
173
+ }
174
+ if (msg.msgType === 'ERROR') {
175
+ let virtualWatch = null;
176
+ this._virtualWSClient.forEach(item => {
177
+ if (item.watchId === msg.watchId) {
178
+ virtualWatch = item;
179
+ }
180
+ });
181
+ if (virtualWatch) {
182
+ virtualWatch.listener.onError(msg);
183
+ }
184
+ }
185
+ const responseWaitSpec = this._wsResponseWait.get(msg.requestId);
186
+ if (responseWaitSpec) {
187
+ try {
188
+ if (msg.msgType === 'ERROR') {
189
+ responseWaitSpec.reject(new RealtimeErrorMessageError(msg));
190
+ }
191
+ else {
192
+ responseWaitSpec.resolve(msg);
193
+ }
194
+ }
195
+ catch (e) {
196
+ console.error('ws onMessage responseWaitSpec.resolve(msg) errored:', e);
197
+ }
198
+ finally {
199
+ this._wsResponseWait.delete(msg.requestId);
200
+ }
201
+ if (responseWaitSpec.skipOnMessage) {
202
+ return;
203
+ }
204
+ }
205
+ if (msg.msgType === 'PONG') {
206
+ if (this._lastPingSendTS) {
207
+ const rtt = Date.now() - this._lastPingSendTS;
208
+ if (rtt > DEFAULT_UNTRUSTED_RTT_THRESHOLD) {
209
+ console.warn(`[realtime] untrusted rtt observed: ${rtt}`);
210
+ return;
211
+ }
212
+ if (this._rttObserved.length >= MAX_RTT_OBSERVED) {
213
+ this._rttObserved.splice(0, this._rttObserved.length - MAX_RTT_OBSERVED + 1);
214
+ }
215
+ this._rttObserved.push(rtt);
216
+ }
217
+ return;
218
+ }
219
+ let client = msg.watchId && this._watchIdClientMap.get(msg.watchId);
220
+ if (client) {
221
+ client.onMessage(msg);
222
+ }
223
+ else {
224
+ console.error(`[realtime] no realtime listener found responsible for watchId ${msg.watchId}: `, msg);
225
+ switch (msg.msgType) {
226
+ case 'INIT_EVENT':
227
+ case 'NEXT_EVENT':
228
+ case 'CHECK_EVENT': {
229
+ client = this._queryIdClientMap.get(msg.msgData.queryID);
230
+ if (client) {
231
+ client.onMessage(msg);
232
+ }
233
+ break;
234
+ }
235
+ default: {
236
+ for (const [, client] of this._watchIdClientMap) {
237
+ client.onMessage(msg);
238
+ break;
239
+ }
240
+ }
241
+ }
242
+ }
243
+ };
244
+ this.heartbeat();
245
+ });
246
+ this.isWSConnected = () => {
247
+ return Boolean(this._ws && this._ws.readyState === WS_READY_STATE.OPEN);
248
+ };
249
+ this.onceWSConnected = async () => {
250
+ if (this.isWSConnected()) {
251
+ return;
252
+ }
253
+ if (this._wsInitPromise) {
254
+ return this._wsInitPromise;
255
+ }
256
+ return new Promise((resolve, reject) => {
257
+ this._wsReadySubsribers.push({
258
+ resolve,
259
+ reject
260
+ });
261
+ });
262
+ };
263
+ this.webLogin = async (envId, refresh) => {
264
+ if (!refresh) {
265
+ if (envId) {
266
+ const loginInfo = this._logins.get(envId);
267
+ if (loginInfo) {
268
+ if (loginInfo.loggedIn && loginInfo.loginResult) {
269
+ return loginInfo.loginResult;
270
+ }
271
+ else if (loginInfo.loggingInPromise) {
272
+ return loginInfo.loggingInPromise;
273
+ }
274
+ }
275
+ }
276
+ else {
277
+ const emptyEnvLoginInfo = this._logins.get('');
278
+ if (emptyEnvLoginInfo && emptyEnvLoginInfo.loggingInPromise) {
279
+ return emptyEnvLoginInfo.loggingInPromise;
280
+ }
281
+ }
282
+ }
283
+ const promise = new Promise(async (resolve, reject) => {
284
+ try {
285
+ const wsSign = await this.getWsSign();
286
+ const msgData = {
287
+ envId: wsSign.envId || '',
288
+ accessToken: '',
289
+ referrer: 'web',
290
+ sdkVersion: '',
291
+ dataVersion: Db.dataVersion || ''
292
+ };
293
+ const loginMsg = {
294
+ watchId: undefined,
295
+ requestId: genRequestId(),
296
+ msgType: 'LOGIN',
297
+ msgData,
298
+ exMsgData: {
299
+ runtime: Db.runtime,
300
+ signStr: wsSign.signStr,
301
+ secretVersion: wsSign.secretVersion
302
+ }
303
+ };
304
+ const loginResMsg = await this.send({
305
+ msg: loginMsg,
306
+ waitResponse: true,
307
+ skipOnMessage: true,
308
+ timeout: DEFAULT_LOGIN_TIMEOUT
309
+ });
310
+ if (!loginResMsg.msgData.code) {
311
+ resolve({
312
+ envId: wsSign.envId
313
+ });
314
+ }
315
+ else {
316
+ reject(new Error(`${loginResMsg.msgData.code} ${loginResMsg.msgData.message}`));
317
+ }
318
+ }
319
+ catch (e) {
320
+ reject(e);
321
+ }
322
+ });
323
+ let loginInfo = envId && this._logins.get(envId);
324
+ const loginStartTS = Date.now();
325
+ if (loginInfo) {
326
+ loginInfo.loggedIn = false;
327
+ loginInfo.loggingInPromise = promise;
328
+ loginInfo.loginStartTS = loginStartTS;
329
+ }
330
+ else {
331
+ loginInfo = {
332
+ loggedIn: false,
333
+ loggingInPromise: promise,
334
+ loginStartTS
335
+ };
336
+ this._logins.set(envId || '', loginInfo);
337
+ }
338
+ try {
339
+ const loginResult = await promise;
340
+ const curLoginInfo = envId && this._logins.get(envId);
341
+ if (curLoginInfo &&
342
+ curLoginInfo === loginInfo &&
343
+ curLoginInfo.loginStartTS === loginStartTS) {
344
+ loginInfo.loggedIn = true;
345
+ loginInfo.loggingInPromise = undefined;
346
+ loginInfo.loginStartTS = undefined;
347
+ loginInfo.loginResult = loginResult;
348
+ return loginResult;
349
+ }
350
+ else if (curLoginInfo) {
351
+ if (curLoginInfo.loggedIn && curLoginInfo.loginResult) {
352
+ return curLoginInfo.loginResult;
353
+ }
354
+ else if (curLoginInfo.loggingInPromise) {
355
+ return curLoginInfo.loggingInPromise;
356
+ }
357
+ else {
358
+ throw new Error('ws unexpected login info');
359
+ }
360
+ }
361
+ else {
362
+ throw new Error('ws login info reset');
363
+ }
364
+ }
365
+ catch (e) {
366
+ loginInfo.loggedIn = false;
367
+ loginInfo.loggingInPromise = undefined;
368
+ loginInfo.loginStartTS = undefined;
369
+ loginInfo.loginResult = undefined;
370
+ throw e;
371
+ }
372
+ };
373
+ this.getWsSign = async () => {
374
+ if (this._wsSign && this._wsSign.expiredTs > Date.now()) {
375
+ return this._wsSign;
376
+ }
377
+ const expiredTs = Date.now() + 60000;
378
+ const res = await this._context.appConfig.request.send('auth.wsWebSign', { runtime: Db.runtime });
379
+ if (res.code) {
380
+ throw new Error(`[tcb-js-sdk] 获取实时数据推送登录票据失败: ${res.code}`);
381
+ }
382
+ if (res.data) {
383
+ const { signStr, wsUrl, secretVersion, envId } = res.data;
384
+ return {
385
+ signStr,
386
+ wsUrl,
387
+ secretVersion,
388
+ envId,
389
+ expiredTs
390
+ };
391
+ }
392
+ else {
393
+ throw new Error('[tcb-js-sdk] 获取实时数据推送登录票据失败');
394
+ }
395
+ };
396
+ this.getWaitExpectedTimeoutLength = () => {
397
+ if (!this._rttObserved.length) {
398
+ return DEFAULT_EXPECTED_EVENT_WAIT_TIME;
399
+ }
400
+ return ((this._rttObserved.reduce((acc, cur) => acc + cur) /
401
+ this._rttObserved.length) *
402
+ 1.5);
403
+ };
404
+ this.ping = async () => {
405
+ const msg = {
406
+ watchId: undefined,
407
+ requestId: genRequestId(),
408
+ msgType: 'PING',
409
+ msgData: null
410
+ };
411
+ await this.send({
412
+ msg
413
+ });
414
+ };
415
+ this.send = async (opts) => new Promise(async (_resolve, _reject) => {
416
+ let timeoutId;
417
+ let _hasResolved = false;
418
+ let _hasRejected = false;
419
+ const resolve = (value) => {
420
+ _hasResolved = true;
421
+ timeoutId && clearTimeout(timeoutId);
422
+ _resolve(value);
423
+ };
424
+ const reject = (error) => {
425
+ _hasRejected = true;
426
+ timeoutId && clearTimeout(timeoutId);
427
+ _reject(error);
428
+ };
429
+ if (opts.timeout) {
430
+ timeoutId = setTimeout(async () => {
431
+ if (!_hasResolved || !_hasRejected) {
432
+ await sleep(0);
433
+ if (!_hasResolved || !_hasRejected) {
434
+ reject(new TimeoutError('wsclient.send timedout'));
435
+ }
436
+ }
437
+ }, opts.timeout);
438
+ }
439
+ try {
440
+ if (this._wsInitPromise) {
441
+ await this._wsInitPromise;
442
+ }
443
+ if (!this._ws) {
444
+ reject(new Error('invalid state: ws connection not exists, can not send message'));
445
+ return;
446
+ }
447
+ if (this._ws.readyState !== WS_READY_STATE.OPEN) {
448
+ reject(new Error(`ws readyState invalid: ${this._ws.readyState}, can not send message`));
449
+ return;
450
+ }
451
+ if (opts.waitResponse) {
452
+ this._wsResponseWait.set(opts.msg.requestId, {
453
+ resolve,
454
+ reject,
455
+ skipOnMessage: opts.skipOnMessage
456
+ });
457
+ }
458
+ try {
459
+ await this._ws.send(JSON.stringify(opts.msg));
460
+ if (!opts.waitResponse) {
461
+ resolve();
462
+ }
463
+ }
464
+ catch (err) {
465
+ if (err) {
466
+ reject(err);
467
+ if (opts.waitResponse) {
468
+ this._wsResponseWait.delete(opts.msg.requestId);
469
+ }
470
+ }
471
+ }
472
+ }
473
+ catch (e) {
474
+ reject(e);
475
+ }
476
+ });
477
+ this.closeAllClients = (error) => {
478
+ this._virtualWSClient.forEach(client => {
479
+ client.closeWithError(error);
480
+ });
481
+ };
482
+ this.pauseClients = (clients) => {
483
+ ;
484
+ (clients || this._virtualWSClient).forEach(client => {
485
+ client.pause();
486
+ });
487
+ };
488
+ this.resumeClients = (clients) => {
489
+ ;
490
+ (clients || this._virtualWSClient).forEach(client => {
491
+ client.resume();
492
+ });
493
+ };
494
+ this.onWatchStart = (client, queryID) => {
495
+ this._queryIdClientMap.set(queryID, client);
496
+ };
497
+ this.onWatchClose = (client, queryID) => {
498
+ if (queryID) {
499
+ this._queryIdClientMap.delete(queryID);
500
+ }
501
+ this._watchIdClientMap.delete(client.watchId);
502
+ this._virtualWSClient.delete(client);
503
+ if (!this._virtualWSClient.size) {
504
+ this.close(CLOSE_EVENT_CODE.NoRealtimeListeners);
505
+ }
506
+ };
507
+ this._maxReconnect = options.maxReconnect || DEFAULT_MAX_RECONNECT;
508
+ this._reconnectInterval =
509
+ options.reconnectInterval || DEFAULT_WS_RECONNECT_INTERVAL;
510
+ this._context = options.context;
511
+ }
512
+ heartbeat(immediate) {
513
+ this.clearHeartbeat();
514
+ this._pingTimeoutId = setTimeout(async () => {
515
+ try {
516
+ if (!this._ws || this._ws.readyState !== WS_READY_STATE.OPEN) {
517
+ return;
518
+ }
519
+ this._lastPingSendTS = Date.now();
520
+ await this.ping();
521
+ this._pingFailed = 0;
522
+ this._pongTimeoutId = setTimeout(() => {
523
+ console.error('pong timed out');
524
+ if (this._pongMissed < DEFAULT_PONG_MISS_TOLERANCE) {
525
+ this._pongMissed++;
526
+ this.heartbeat(true);
527
+ }
528
+ else {
529
+ this.initWebSocketConnection(true);
530
+ }
531
+ }, this._context.appConfig.realtimePongWaitTimeout);
532
+ }
533
+ catch (e) {
534
+ if (this._pingFailed < DEFAULT_PING_FAIL_TOLERANCE) {
535
+ this._pingFailed++;
536
+ this.heartbeat();
537
+ }
538
+ else {
539
+ this.close(CLOSE_EVENT_CODE.HeartbeatPingError);
540
+ }
541
+ }
542
+ }, immediate ? 0 : this._context.appConfig.realtimePingInterval);
543
+ }
544
+ clearHeartbeat() {
545
+ this._pingTimeoutId && clearTimeout(this._pingTimeoutId);
546
+ this._pongTimeoutId && clearTimeout(this._pongTimeoutId);
547
+ }
548
+ close(code) {
549
+ this.clearHeartbeat();
550
+ if (this._ws) {
551
+ this._ws.close(code, CLOSE_EVENT_CODE_INFO[code].name);
552
+ this._ws = undefined;
553
+ }
554
+ }
555
+ watch(options) {
556
+ if (!this._ws && !this._wsInitPromise) {
557
+ this.initWebSocketConnection(false);
558
+ }
559
+ const virtualClient = new VirtualWebSocketClient(Object.assign(Object.assign({}, options), { send: this.send, login: this.webLogin, isWSConnected: this.isWSConnected, onceWSConnected: this.onceWSConnected, getWaitExpectedTimeoutLength: this.getWaitExpectedTimeoutLength, onWatchStart: this.onWatchStart, onWatchClose: this.onWatchClose, debug: true }));
560
+ this._virtualWSClient.add(virtualClient);
561
+ this._watchIdClientMap.set(virtualClient.watchId, virtualClient);
562
+ return virtualClient.listener;
563
+ }
564
+ }