-
Notifications
You must be signed in to change notification settings - Fork 10
/
LeapClient.ts
329 lines (277 loc) · 10.2 KB
/
LeapClient.ts
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
import { ConnectionOptions, TLSSocket, connect, createSecureContext } from 'tls';
import debug from 'debug';
import * as fs from 'fs';
import { EventEmitter } from 'events';
import { CommuniqueType, Response, ResponseWithTag } from './Messages';
import {
BodyType,
Href,
OnePingResponse,
PingResponseDefinition,
ClientSettingDefinition,
OneClientSettingDefinition,
ExceptionDetail,
} from './MessageBodyTypes';
import { ResponseParser } from './ResponseParser';
import TypedEmitter from 'typed-emitter';
import { v4 as uuidv4 } from 'uuid';
const logDebug = debug('leap:protocol:client');
export interface Message {
CommuniqueType: CommuniqueType;
Header: {
ClientTag: string;
Url: string;
};
Body?: Record<string, unknown>;
}
interface MessageDetails {
message: Message;
resolve: (message: Response) => void;
reject: (err: Error) => void;
timeout: ReturnType<typeof setTimeout>;
}
type LeapClientEvents = {
unsolicited: (response: Response) => void;
disconnected: () => void;
};
export class LeapClient extends (EventEmitter as new () => TypedEmitter<LeapClientEvents>) {
private connected: Promise<void> | null;
private socket?: TLSSocket;
private readonly tlsOptions: ConnectionOptions;
private inFlightRequests: Map<string, MessageDetails> = new Map();
private taggedSubscriptions: Map<string, (r: Response) => void> = new Map();
private responseParser: ResponseParser;
private sslKeylogFile?: fs.WriteStream;
constructor(
private readonly host: string,
private readonly port: number,
ca: string,
key: string,
cert: string,
sslKeylogFile?: fs.WriteStream,
) {
super();
logDebug('new LeapClient being constructed');
this.connected = null;
const context = createSecureContext({
ca,
key,
cert,
});
this.tlsOptions = {
secureContext: context,
secureProtocol: 'TLSv1_2_method',
rejectUnauthorized: false,
};
this.responseParser = new ResponseParser();
this.responseParser.on('response', this._handleResponse.bind(this));
if (sslKeylogFile !== undefined) {
this.sslKeylogFile = sslKeylogFile;
}
}
public async retrieve<T extends BodyType>(href: Href, endpoint?: string): Promise<T> {
const resp = await this.request('ReadRequest', href.href + (endpoint !== undefined ? endpoint : ''));
if (resp.Body === undefined) {
throw new Error(`could not get ${href.href}: no body`);
}
if (resp.Body instanceof ExceptionDetail) {
throw new Error(`could not get ${href.href}: ${resp.Body.Message}`);
}
return resp.Body as T;
}
public async request(
communiqueType: CommuniqueType,
url: string,
body?: Record<string, unknown>,
tag?: string,
): Promise<Response> {
logDebug(`request ${communiqueType} for url ${url}`);
await this.connect();
if (tag === undefined) {
tag = uuidv4();
}
if (this.inFlightRequests.has(tag)) {
const ifr = this.inFlightRequests.get(tag)!;
ifr.reject(new Error('Request clobbered due to tag re-use'));
clearTimeout(ifr.timeout);
this.inFlightRequests.delete(tag);
}
let requestResolve: (response: Response) => void = () => {
// this gets replaced
};
let requestReject: (err: Error) => void = () => {
// this gets replaced
};
const requestPromise = new Promise<Response>((resolve, reject) => {
requestResolve = resolve;
requestReject = reject;
});
const message: Message = {
CommuniqueType: communiqueType,
Header: {
ClientTag: tag,
Url: url,
},
};
if (body !== undefined) {
message.Body = body;
}
const msg = JSON.stringify(message);
logDebug('request handler about to write:', msg);
let timeout;
this.socket?.write(msg + '\n', () => {
timeout = setTimeout(() => {
requestReject(new Error('request with tag' + tag + 'timed out'));
}, 5000);
logDebug('sent request tag', tag, ' successfully');
this.inFlightRequests.set(tag!, {
message,
resolve: requestResolve,
reject: requestReject,
timeout,
});
logDebug('added promise to inFlightRequests with tag key', tag);
});
return requestPromise;
}
public connect(): Promise<void> {
if (!this.connected) {
logDebug('needs to connect');
this.connected = new Promise((resolve, reject) => {
this.socket = connect(this.port, this.host, this.tlsOptions, () => {
logDebug('connected!');
});
this.socket.once('secureConnect', () => {
logDebug('securely connected');
this._onConnect(resolve, reject);
});
this.socket.once('error', (e) => {
logDebug('connection failed: ', e);
this.connected = null;
reject(e);
});
if (this.sslKeylogFile !== undefined) {
this.socket.on('keylog', (line) => this.sslKeylogFile!.write(line));
}
});
}
return this.connected;
}
public close() {
// this method does not prevent the client from being used; instead it
// only closes the connection. subsequent requests will trigger this
// client to attempt to reconnect. make sure nobody is going to try to
// use this client before you dispose of it.
this.connected = null;
this.socket?.end();
}
public async subscribe(
url: string,
callback: (resp: Response) => void,
communiqueType?: CommuniqueType | undefined,
body?: Record<string, unknown>,
tag?: string,
): Promise<ResponseWithTag> {
const _tag = tag || uuidv4();
if (communiqueType === undefined) {
communiqueType = 'SubscribeRequest';
}
return await this.request(communiqueType, url, body, _tag).then((response: Response) => {
if (response.Header.StatusCode !== undefined && response.Header.StatusCode.isSuccessful()) {
this.taggedSubscriptions.set(_tag, callback);
logDebug('Subscribed to', url, ' as ', _tag);
}
return { response, tag: _tag };
});
}
public drain() {
this.removeAllListeners('unsolicited');
this.removeAllListeners('disconnected');
// Cancel all pending timeouts if any
for (const tag of this.inFlightRequests.keys()) {
const request = this.inFlightRequests.get(tag)!;
clearTimeout(request.timeout);
}
this._empty();
this.close();
}
private _empty() {
this.inFlightRequests.clear();
this.taggedSubscriptions.clear();
}
private _onConnect(next: () => void, _reject: (reason: any) => void): void {
logDebug('_onConnect called');
const socketErr = (err: Error) => {
logDebug('socket error:', err);
};
const socketEnd = () => {
logDebug('client socket has ended');
this.socket?.end(); // Acknowledge to other end of the connection that the connection is ended.
this.socket?.destroy(); // Prevent writes
};
const socketClose = (sock: TLSSocket): void => {
logDebug('client socket has closed.');
this.connected = null;
this._empty();
this.emit('disconnected');
};
this.socket?.on('error', socketErr);
this.socket?.on('close', socketClose);
this.socket?.on('data', this.socketDataHandler.bind(this));
this.socket?.on('end', socketEnd);
return next();
}
private socketDataHandler(data: Buffer): void {
const s = data.toString();
logDebug('got data from socket:', s);
this.responseParser.handleData(s);
}
private _handleResponse(response: Response): void {
const tag = response.Header.ClientTag;
if (tag !== undefined) {
logDebug('got response to tag', tag);
const arrow: MessageDetails = this.inFlightRequests.get(tag)!;
if (arrow !== undefined) {
logDebug('tag', tag, ' recognized as in-flight');
clearTimeout(arrow.timeout);
this.inFlightRequests.delete(tag);
arrow.resolve(response);
} else {
logDebug('tag', tag, ' not in flight');
const sub = this.taggedSubscriptions.get(tag);
if (sub !== undefined) {
logDebug('tag', tag, ' has a subscription');
sub(response);
} else {
logDebug('ERROR was not expecting tag ', tag);
}
}
} else {
logDebug('got untagged, unsolicited response');
this.emit('unsolicited', response);
}
}
public async setVersion(): Promise<ExceptionDetail | ClientSettingDefinition> {
logDebug('setVersion request');
const resp = await this.request('UpdateRequest', '/clientsetting', {
ClientSetting: {
ClientMajorVersion: 1,
},
});
switch (resp.CommuniqueType) {
case 'ExceptionResponse': {
return resp.Body! as ExceptionDetail;
}
case 'UpdateResponse': {
return (resp.Body! as OneClientSettingDefinition).ClientSetting;
}
default: {
throw new Error('bad communique type');
}
}
}
public async ping(): Promise<PingResponseDefinition> {
const resp = await this.request('ReadRequest', '/server/1/status/ping');
return (resp.Body! as OnePingResponse).PingResponse;
}
}