-
Notifications
You must be signed in to change notification settings - Fork 10
/
LeapClient.ts
282 lines (235 loc) · 8.67 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
import { ConnectionOptions, TLSSocket, connect, createSecureContext } from 'tls';
import debug from 'debug';
import { EventEmitter } from 'events';
import { Response } from './Messages';
import { ResponseParser } from './ResponseParser';
import TypedEmitter from 'typed-emitter';
import { v4 as uuidv4 } from 'uuid';
const logDebug = debug('leap:protocol');
export type ResponseWithTag = { response: Response; tag: string };
interface Message {
CommuniqueType: string;
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>;
}
interface 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;
constructor(private readonly host: string, private readonly port: number, ca: string, key: string, cert: string) {
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));
}
public async request(
communiqueType: string,
url: string,
body?: Record<string, unknown>,
tag?: string,
): Promise<Response> {
await this.connect();
if (tag === undefined) {
tag = uuidv4();
}
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 timeout = setTimeout(() => {
this.inFlightRequests.delete(tag!);
requestReject(new Error('request with tag' + tag + 'timed out'));
}, 3000);
this.inFlightRequests.set(tag, {
message,
resolve: requestResolve,
reject: requestReject,
timeout,
});
logDebug('added promise to inFlightRequests with tag key', tag);
const msg = JSON.stringify(message);
logDebug('request handler about to write:', msg);
this.socket?.write(msg + '\n', () => {
logDebug('sent request tag', tag, ' successfully');
});
return requestPromise;
}
public connect(): Promise<void> {
if (!this.connected) {
logDebug('needs to connect');
this.connected = new Promise((resolve, reject) => {
logDebug('about to connect');
this.socket = connect(this.port, this.host, this.tlsOptions, () => {
logDebug('connected!');
});
this.socket.once('secureConnect', () => {
logDebug('securely connected');
this._onConnect(resolve);
});
this.socket.once('error', (e) => {
logDebug('connection failed: ', e);
this.connected = null;
reject(e);
});
});
}
return this.connected;
}
public close() {
this.connected = null;
if (this.socket !== undefined) {
this.socket.destroy();
}
}
public async subscribe(
url: string,
callback: (resp: Response) => void,
communiqueType: string,
body?: Record<string, unknown>,
tag?: string,
): Promise<ResponseWithTag> {
const _tag = tag || uuidv4();
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 };
});
}
private _empty() {
this.inFlightRequests.clear();
this.taggedSubscriptions.clear();
}
private _onConnect(next: () => void): void {
logDebug('_onConnect called');
// Clear out event listeners from _connect()
if (this.socket) {
this.socket.removeAllListeners('error');
this.socket.removeAllListeners('connect');
this.socket.removeAllListeners('secureConnect');
}
const socketError = (err: Error): void => {
logDebug('socket error:', err);
this._empty();
if (this.socket) {
this.socket.destroy();
}
this.removeAllListeners('unsolicited');
};
function socketEnd(this: TLSSocket): void {
logDebug('client socket has ended');
if (this) {
// Acknowledge to other end of the connection that the connection is ended.
this.end();
}
}
function socketTimeout(this: TLSSocket): void {
logDebug('client socket has timed out');
if (this) {
// Acknowledge to other end of the connection that the connection is ended.
this.end();
}
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
const clientInstance = this;
function socketClose(this: TLSSocket): void {
logDebug('client socket has closed.');
if (this) {
this.removeListener('error', socketError);
this.removeListener('close', socketClose);
this.removeListener('data', clientInstance.socketDataHandler);
this.removeListener('end', socketEnd);
this.removeListener('timeout', socketTimeout);
}
if (this === clientInstance.socket) {
clientInstance.connected = null;
delete clientInstance.socket;
}
clientInstance._empty();
clientInstance.removeAllListeners('unsolicited');
this.emit('disconnected');
}
if (this.socket) {
this.socket.on('error', socketError);
this.socket.on('close', socketClose);
this.socket.on('data', this.socketDataHandler);
this.socket.on('end', socketEnd);
this.socket.on('timeout', socketTimeout);
}
return next();
}
private readonly 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);
}
}
}