-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathwsClient.ts
More file actions
261 lines (234 loc) · 10.4 KB
/
Copy pathwsClient.ts
File metadata and controls
261 lines (234 loc) · 10.4 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
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} from '../common/utils';
import { w3cwebsocket } from 'websocket';
import { 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;
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");
}
}
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,
...(this._timezone && { tz: this._timezone }),
},
};
logger.debug("[wsClient.connect.connMsg]===>" + JSONBig.stringify(connMsg));
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();
logger.error(`connection creation failed, url: ${this._url}, code:${e.code}, msg:${e.message}`);
throw(new TDWebSocketClientError(ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL, `connection creation failed, url: ${this._url}, 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) => {
logger.debug('[wsQueryInterface.query.queryMsg]===>' + 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()
}
logger.debug("ready status ", this._url, this._wsConnector.readyState())
return;
} catch (e: any) {
logger.error(`connection creation failed, url: ${this._url}, code: ${e.code}, message: ${e.message}`);
throw(new TDWebSocketClientError(ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL, `connection creation failed, url: ${this._url}, 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) {
logger.error(`connection creation failed, url: ${this._url}, code: ${e.code}, message: ${e.message}`);
throw(new TDWebSocketClientError(ErrorCode.ERR_WEBSOCKET_CONNECTION_FAIL, `connection creation failed, url: ${this._url}, 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
// this._wsConnector.close();
}
}
checkURL(url: URL) {
// Assert is cloud url
if (!url.searchParams.has('token')) {
if (!(url.username || url.password)) {
throw new WebSocketInterfaceError(ErrorCode.ERR_INVALID_AUTHENTICATION, 'invalid url, password or username needed.');
}
}
}
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}`));
}
}
}