-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathwsClient.ts
More file actions
371 lines (353 loc) · 13.2 KB
/
wsClient.ts
File metadata and controls
371 lines (353 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import JSONBig from "json-bigint";
import { WebSocketConnector } from "./wsConnector";
import { WebSocketConnectionPool } from "./wsConnectorPool";
import {
ErrorCode,
TDWebSocketClientError,
WebSocketInterfaceError,
WebSocketQueryError,
} from "../common/wsError";
import { WSVersionResponse, WSQueryResponse } from "./wsResponse";
import { ReqId } from "../common/reqid";
import logger from "../common/log";
import { safeDecodeURIComponent, compareVersions, maskSensitiveForLog, maskUrlForLog } from "../common/utils";
import { w3cwebsocket } from "websocket";
import { ConnectorInfo, TSDB_OPTION_CONNECTION } from "../common/constant";
export class WsClient {
private _wsConnector?: WebSocketConnector;
private _timeout?: number | undefined | null;
private _timezone?: string | undefined | null;
private readonly _url: URL;
private static readonly _minVersion = "3.3.2.0";
private _version?: string | undefined | null;
private _bearerToken?: string | undefined | null;
constructor(url: URL, timeout?: number | undefined | null) {
this.checkURL(url);
this._url = url;
this._timeout = timeout;
if (this._url.searchParams.has("timezone")) {
this._timezone = this._url.searchParams.get("timezone") || undefined;
this._url.searchParams.delete("timezone");
}
if (this._url.searchParams.has("bearer_token")) {
this._bearerToken = this._url.searchParams.get("bearer_token") || undefined;
}
}
async connect(database?: string | undefined | null): Promise<void> {
let connMsg = {
action: "conn",
args: {
req_id: ReqId.getReqID(),
user: safeDecodeURIComponent(this._url.username),
password: safeDecodeURIComponent(this._url.password),
db: database,
connector: ConnectorInfo,
...(this._timezone && { tz: this._timezone }),
...(this._bearerToken && { bearer_token: this._bearerToken }),
},
};
if (logger.isDebugEnabled()) {
logger.debug("[wsClient.connect.connMsg]===>" + JSONBig.stringify(connMsg, (key, value) =>
(key === "password" || key === "bearer_token") ? "[REDACTED]" : value
));
}
this._wsConnector = await WebSocketConnectionPool.instance().getConnection(
this._url,
this._timeout
);
if (this._wsConnector.readyState() === w3cwebsocket.OPEN) {
return;
}
try {
await this._wsConnector.ready();
let result: any = await this._wsConnector.sendMsg(JSON.stringify(connMsg));
if (result.msg.code == 0) {
return;
}
await this.close();
throw new WebSocketQueryError(result.msg.code, result.msg.message);
} catch (e: any) {
await this.close();
const maskedUrl = maskUrlForLog(this._url);
logger.error(`connection creation failed, url: ${maskedUrl}, code:${e.code}, msg:${e.message}`);
throw new TDWebSocketClientError(
ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL,
`connection creation failed, url: ${maskedUrl}, code:${e.code}, msg:${e.message}`
);
}
}
async setOptionConnection(option: TSDB_OPTION_CONNECTION, value: string | null): Promise<void> {
logger.debug("[wsClient.setOptionConnection]===>" + option + ", " + value);
let connMsg = {
action: "options_connection",
args: {
req_id: ReqId.getReqID(),
options: [
{
option: option,
value: value,
},
],
},
};
try {
await this.exec(JSONBig.stringify(connMsg), false);
} catch (e: any) {
logger.error("[wsClient.setOptionConnection] failed: " + e.message);
throw e;
}
}
async execNoResp(queryMsg: string): Promise<void> {
logger.debug("[wsQueryInterface.query.queryMsg]===>" + queryMsg);
if (
this._wsConnector &&
this._wsConnector.readyState() === w3cwebsocket.OPEN
) {
await this._wsConnector.sendMsgNoResp(queryMsg);
return;
}
throw new TDWebSocketClientError(
ErrorCode.ERR_CONNECTION_CLOSED,
"invalid websocket connect"
);
}
// Need to construct Response
async exec(queryMsg: string, bSqlQuery: boolean = true): Promise<any> {
return new Promise((resolve, reject) => {
if (logger.isDebugEnabled()) {
logger.debug("[wsQueryInterface.query.queryMsg]===>" + maskSensitiveForLog(queryMsg));
}
if (
this._wsConnector &&
this._wsConnector.readyState() === w3cwebsocket.OPEN
) {
this._wsConnector
.sendMsg(queryMsg)
.then((e: any) => {
if (e.msg.code == 0) {
if (bSqlQuery) {
resolve(new WSQueryResponse(e));
} else {
resolve(e);
}
} else {
reject(
new WebSocketInterfaceError(
e.msg.code,
e.msg.message
)
);
}
})
.catch((e) => {
reject(e);
});
} else {
reject(
new TDWebSocketClientError(
ErrorCode.ERR_CONNECTION_CLOSED,
"invalid websocket connect"
)
);
}
});
}
// need to construct Response.
async sendBinaryMsg(
reqId: bigint,
action: string,
message: ArrayBuffer,
bSqlQuery: boolean = true,
bResultBinary: boolean = false
): Promise<any> {
return new Promise((resolve, reject) => {
if (
this._wsConnector &&
this._wsConnector.readyState() === w3cwebsocket.OPEN
) {
this._wsConnector
.sendBinaryMsg(reqId, action, message)
.then((e: any) => {
if (bResultBinary) {
resolve(e);
}
if (e.msg.code == 0) {
if (bSqlQuery) {
resolve(new WSQueryResponse(e));
} else {
resolve(e);
}
} else {
reject(
new WebSocketInterfaceError(
e.msg.code,
e.msg.message
)
);
}
})
.catch((e) => {
reject(e);
});
} else {
reject(
new TDWebSocketClientError(
ErrorCode.ERR_CONNECTION_CLOSED,
"invalid websocket connect"
)
);
}
});
}
getState() {
if (this._wsConnector) {
return this._wsConnector.readyState();
}
return -1;
}
async ready(): Promise<void> {
try {
this._wsConnector = await WebSocketConnectionPool.instance().getConnection(
this._url,
this._timeout
);
if (this._wsConnector.readyState() !== w3cwebsocket.OPEN) {
await this._wsConnector.ready();
}
if (logger.isDebugEnabled()) {
logger.debug("ready status ", maskUrlForLog(this._url), this._wsConnector.readyState());
}
return;
} catch (e: any) {
const maskedUrl = maskUrlForLog(this._url);
logger.error(
`connection creation failed, url: ${maskedUrl}, code: ${e.code}, message: ${e.message}`
);
throw new TDWebSocketClientError(
ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL,
`connection creation failed, url: ${maskedUrl}, code: ${e.code}, message: ${e.message}`
);
}
}
async sendMsg(msg: string): Promise<any> {
return new Promise((resolve, reject) => {
logger.debug("[wsQueryInterface.sendMsg]===>" + msg);
if (
this._wsConnector &&
this._wsConnector.readyState() === w3cwebsocket.OPEN
) {
this._wsConnector
.sendMsg(msg)
.then((e: any) => {
resolve(e);
})
.catch((e) => reject(e));
} else {
reject(
new TDWebSocketClientError(
ErrorCode.ERR_CONNECTION_CLOSED,
"invalid websocket connect"
)
);
}
});
}
async freeResult(res: WSQueryResponse) {
let freeResultMsg = {
action: "free_result",
args: {
req_id: ReqId.getReqID(),
id: res.id,
},
};
return new Promise((resolve, reject) => {
let jsonStr = JSONBig.stringify(freeResultMsg);
logger.debug(
"[wsQueryInterface.freeResult.freeResultMsg]===>" + jsonStr
);
if (
this._wsConnector &&
this._wsConnector.readyState() === w3cwebsocket.OPEN
) {
this._wsConnector
.sendMsgNoResp(jsonStr)
.then((e: any) => {
resolve(e);
})
.catch((e) => reject(e));
} else {
reject(
new TDWebSocketClientError(
ErrorCode.ERR_CONNECTION_CLOSED,
"invalid websocket connect"
)
);
}
});
}
async version(): Promise<string> {
if (this._version) {
return this._version;
}
let versionMsg = {
action: "version",
args: {
req_id: ReqId.getReqID(),
},
};
if (this._wsConnector) {
try {
if (this._wsConnector.readyState() !== w3cwebsocket.OPEN) {
await this._wsConnector.ready();
}
let result: any = await this._wsConnector.sendMsg(JSONBig.stringify(versionMsg));
if (result.msg.code == 0) {
return new WSVersionResponse(result).version;
}
throw new WebSocketInterfaceError(result.msg.code, result.msg.message);
} catch (e: any) {
const maskedUrl = maskUrlForLog(this._url);
logger.error(
`connection creation failed, url: ${maskedUrl}, code: ${e.code}, message: ${e.message}`
);
throw new TDWebSocketClientError(
ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL,
`connection creation failed, url: ${maskedUrl}, code: ${e.code}, message: ${e.message}`
);
}
}
throw (ErrorCode.ERR_CONNECTION_CLOSED, "invalid websocket connect");
}
async close(): Promise<void> {
if (this._wsConnector) {
await WebSocketConnectionPool.instance().releaseConnection(
this._wsConnector
);
this._wsConnector = undefined;
}
}
checkURL(url: URL) {
// Assert token or bearer_token exists, otherwise username and password must exist.
if (!url.searchParams.get("token") && !url.searchParams.get("bearer_token")) {
if (!(url.username || url.password)) {
throw new WebSocketInterfaceError(
ErrorCode.ERR_INVALID_AUTHENTICATION,
`invalid url, provide non-empty "token" or "bearer_token", or provide username/password`
);
}
}
}
async checkVersion() {
this._version = await this.version();
let result = compareVersions(this._version, WsClient._minVersion);
if (result < 0) {
logger.error(
`TDengine version is too low, current version: ${this._version}, minimum required version: ${WsClient._minVersion}`
);
throw new WebSocketQueryError(
ErrorCode.ERR_TDENIGNE_VERSION_IS_TOO_LOW,
`Version mismatch. The minimum required TDengine version is ${WsClient._minVersion}`
);
}
}
}