-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathwsClient.ts
More file actions
426 lines (387 loc) · 14.7 KB
/
Copy pathwsClient.ts
File metadata and controls
426 lines (387 loc) · 14.7 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import JSONBig from "json-bigint";
import { WebSocketConnector } from "./wsConnector";
import type { SessionRecoveryHook } from "./wsConnector";
import { WebSocketConnectionPool } from "./wsConnectorPool";
import { Dsn, WS_SQL_ENDPOINT } from "../common/dsn";
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 } 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 _userApp?: string | undefined | null;
private _userIp?: string | undefined | null;
private readonly _dsn: Dsn;
private static readonly _minVersion = "3.3.2.0";
private _version?: string | undefined | null;
private _bearerToken?: string | undefined | null;
private _connectedDatabase: string | null = null;
private _connectionOptions: Map<TSDB_OPTION_CONNECTION, string | null> = new Map();
private _customRecoveryHook: SessionRecoveryHook | null = null;
constructor(dsn: Dsn, timeout?: number | undefined | null) {
this.checkAuth(dsn);
this._dsn = dsn;
this._timeout = timeout;
if (this._dsn.params.has("timezone")) {
this._timezone = this._dsn.params.get("timezone") || undefined;
}
if (this._dsn.params.has("user_app")) {
this._userApp = this._dsn.params.get("user_app") || undefined;
}
if (this._dsn.params.has("user_ip")) {
this._userIp = this._dsn.params.get("user_ip") || undefined;
}
if (this._dsn.params.has("bearer_token")) {
this._bearerToken = this._dsn.params.get("bearer_token") || undefined;
}
}
private buildConnMessage(
database?: string | undefined | null,
listInstances?: boolean
) {
return {
action: "conn",
args: {
req_id: ReqId.getReqID(),
user: safeDecodeURIComponent(this._dsn.username),
password: safeDecodeURIComponent(this._dsn.password),
db: database,
connector: ConnectorInfo,
...(this._timezone && { tz: this._timezone }),
...(this._userApp && { app: this._userApp }),
...(this._userIp && { ip: this._userIp }),
...(this._bearerToken && { bearer_token: this._bearerToken }),
...(listInstances !== undefined && { list_instances: listInstances }),
},
};
}
private getWsConnector(): WebSocketConnector {
if (!this._wsConnector) {
throw new TDWebSocketClientError(
ErrorCode.ERR_CONNECTION_CLOSED,
"Invalid websocket connection"
);
}
return this._wsConnector;
}
private bindReconnectRecoveryHook(): void {
if (!this._wsConnector) {
return;
}
this._wsConnector.setSessionRecoveryHook(async () => {
if (this.isSqlPath()) {
await this.recoverSqlSessionContext();
}
if (this._customRecoveryHook) {
await this._customRecoveryHook();
}
});
}
private isSqlPath(): boolean {
return this._dsn.endpoint === WS_SQL_ENDPOINT;
}
private normalizeConnectedDatabase(database?: string | null): string | null {
if (database && database.length > 0) {
return database;
}
return this.isSqlPath() ? "information_schema" : null;
}
private async recoverSqlSessionContext(): Promise<void> {
if (!this._wsConnector) {
return;
}
const connMsg = this.buildConnMessage(
this.normalizeConnectedDatabase(this._connectedDatabase)
);
await this.sendMsgDirect(JSON.stringify(connMsg), false);
if (this._connectionOptions.size <= 0) {
this._wsConnector.markSessionReady();
return;
}
const options = Array.from(this._connectionOptions.entries()).map(
([option, value]) => ({
option,
value,
})
);
const optionsMsg = {
action: "options_connection",
args: {
req_id: ReqId.getReqID(),
options,
},
};
await this.sendMsgDirect(JSONBig.stringify(optionsMsg), false);
this._wsConnector.markSessionReady();
}
public setSessionRecoveryHook(
hook: SessionRecoveryHook | null | undefined
): void {
this._customRecoveryHook = hook || null;
this.bindReconnectRecoveryHook();
}
async connect(database?: string | undefined | null): Promise<void> {
const listInstances = this._dsn.isAdapterHA() ? true : undefined;
const connMsg = this.buildConnMessage(database, listInstances);
const normalizedDatabase = this.normalizeConnectedDatabase(database ?? null);
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._dsn,
this._timeout
);
this.bindReconnectRecoveryHook();
try {
if (this._wsConnector.readyState() === w3cwebsocket.OPEN) {
this._connectedDatabase = normalizedDatabase;
if (this.isSqlPath() && !this._wsConnector.isSessionReady()) {
await this.recoverSqlSessionContext();
}
return;
}
await this._wsConnector.ready();
let result: any = await this._wsConnector.sendMsg(JSON.stringify(connMsg));
if (result.msg.code == 0) {
this._connectedDatabase = normalizedDatabase;
this._wsConnector.markSessionReady();
if (result.msg.list_instances) {
this._wsConnector.mergeDiscoveredEndpoints(result.msg.list_instances);
}
return;
}
await this.close();
throw new WebSocketQueryError(result.msg.code, result.msg.message);
} catch (e: any) {
await this.close();
logger.error(`connection creation failed, dsn:${this._dsn}, code:${e.code}, msg:${e.message}`);
throw new TDWebSocketClientError(
ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL,
`connection creation failed, dsn:${this._dsn}, 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);
this._connectionOptions.set(option, value);
} catch (e: any) {
logger.error("[wsClient.setOptionConnection] failed: " + e.message);
throw e;
}
}
async execNoResp(message: string): Promise<void> {
logger.debug("[wsClient.execNoResp]===>" + message);
await this.getWsConnector().sendMsgNoResp(message);
}
async exec(message: string, bSqlQuery: boolean = true): Promise<any> {
if (logger.isDebugEnabled()) {
logger.debug("[wsClient.exec]===>" + maskSensitiveForLog(message));
}
const resp: any = await this.getWsConnector().sendMsg(message);
if (resp.msg.code == 0) {
if (bSqlQuery) {
return new WSQueryResponse(resp);
}
return resp;
}
throw new WebSocketInterfaceError(
resp.msg.code,
resp.msg.message
);
}
async sendMsgDirect(message: string, bSqlQuery: boolean = true): Promise<any> {
if (logger.isDebugEnabled()) {
logger.debug("[wsClient.sendMsgDirect]===>" + maskSensitiveForLog(message));
}
const resp: any = await this.getWsConnector().sendMsgDirect(message);
if (resp.msg.code == 0) {
if (bSqlQuery) {
return new WSQueryResponse(resp);
}
return resp;
}
throw new WebSocketQueryError(
resp.msg.code,
resp.msg.message
);
}
async sendBinaryMsg(
reqId: bigint,
action: string,
message: ArrayBuffer,
bSqlQuery: boolean = true,
bResultBinary: boolean = false
): Promise<any> {
const resp: any = await this.getWsConnector().sendBinaryMsg(reqId, action, message);
if (bResultBinary) {
return resp;
}
if (resp.msg.code == 0) {
if (bSqlQuery) {
return new WSQueryResponse(resp);
}
return resp;
}
throw new WebSocketInterfaceError(
resp.msg.code,
resp.msg.message
);
}
getState() {
if (this._wsConnector) {
return this._wsConnector.readyState();
}
return -1;
}
async ready(): Promise<void> {
try {
this._wsConnector = await WebSocketConnectionPool.instance().getConnection(
this._dsn,
this._timeout
);
this.bindReconnectRecoveryHook();
if (this._wsConnector.readyState() !== w3cwebsocket.OPEN) {
await this._wsConnector.ready();
}
if (this.isSqlPath() && !this._wsConnector.isSessionReady()) {
this._connectedDatabase = this.normalizeConnectedDatabase(this._connectedDatabase);
await this.recoverSqlSessionContext();
}
if (logger.isDebugEnabled()) {
logger.debug(
`ready status, dsn: ${this._dsn}, state: ${this._wsConnector.readyState()}`
);
}
return;
} catch (e: any) {
logger.error(
`connection creation failed, dsn: ${this._dsn}, code: ${e.code}, message: ${e.message}`
);
throw new TDWebSocketClientError(
ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL,
`connection creation failed, dsn: ${this._dsn}, code: ${e.code}, message: ${e.message}`
);
}
}
async waitForReady(): Promise<void> {
await this.getWsConnector().ready();
}
isNetworkError(err: unknown): boolean {
return this.getWsConnector().isNetworkError(err);
}
getReconnectRetries(): number {
return this.getWsConnector().getReconnectRetries();
}
isAdapterHA(): boolean {
return this._dsn.isAdapterHA();
}
mergeDiscoveredEndpoints(instances: string[]): void {
this.getWsConnector().mergeDiscoveredEndpoints(instances);
}
async sendMsg(message: string): Promise<any> {
logger.debug("[wsClient.sendMsg]===>" + message);
return this.getWsConnector().sendMsg(message);
}
async freeResult(res: WSQueryResponse): Promise<void> {
const freeResultMsg = {
action: "free_result",
args: {
req_id: ReqId.getReqID(),
id: res.id,
},
};
const jsonStr = JSONBig.stringify(freeResultMsg);
logger.debug("[wsClient.freeResult]===>" + jsonStr);
await this.getWsConnector().sendMsgNoResp(jsonStr);
}
async version(): Promise<string> {
if (this._version) {
return this._version;
}
let versionMsg = {
action: "version",
args: {
req_id: ReqId.getReqID(),
},
};
try {
const connector = this.getWsConnector();
if (connector.readyState() !== w3cwebsocket.OPEN) {
await connector.ready();
}
let result: any = await connector.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) {
logger.error(
`connection creation failed, dsn: ${this._dsn}, code: ${e.code}, message: ${e.message}`
);
throw new TDWebSocketClientError(
ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL,
`connection creation failed, dsn: ${this._dsn}, code: ${e.code}, message: ${e.message}`
);
}
}
async close(): Promise<void> {
if (this._wsConnector) {
this._wsConnector.setSessionRecoveryHook(null);
await WebSocketConnectionPool.instance().releaseConnection(
this._wsConnector
);
this._wsConnector = undefined;
}
this._customRecoveryHook = null;
}
private checkAuth(dsn: Dsn): void {
const hasToken = dsn.params.get("token") || dsn.params.get("bearer_token");
if (!hasToken) {
if (!(dsn.username || dsn.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}`
);
}
}
}