-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
295 lines (244 loc) · 8.06 KB
/
index.js
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
import axios from 'axios';
const LISTEN_TYPE = 1;
const TASK_TYPE = 2;
if (!window.EventSource) {
let EventSource = require('eventsource');
window.EventSource = EventSource;
}
function getNotificationData(_data) {
let data = _data.charAt(0) === '"'? _data.slice(1,-1) : _data;
// dequote if quoted
let retData;
if (data.indexOf('^') !== -1) {
let dataAry = data.split('^');
retData = {
response: dataAry[0],
info: dataAry[1].charAt(0) === '{'?
JSON.parse(dataAry[1].replace(/\\/g, '')) : dataAry[1]
};
}
else
retData = {response: data, info: null};
return retData;
}
function submitPendingRequest(pendingRequest) {
setTimeout(async ()=>{
let status = await pendingRequest();
if (!status) {
console.error('pendingRequest failed');
}
});
}
class ServerEventClient {
constructor(name, appurl, cb, prefix) {
this.cb = cb;
this.APPURL = appurl;
this.PREFIX = prefix || "/sse/";
this.SSESource = null;
this.myName = name;
this.myID = null,
this.pendingRequests = {};
this.mAxios = axios.create({
baseURL: appurl
});
}
async _queueSubmission(type, name, submissionFunc) {
let status = true;
let rsp;
if (this.SSESource === null || this.SSESource.readyState !== EventSource.OPEN) {
if (this.SSESource === null || this.SSESource.readyState === EventSource.CLOSED)
status = await this.registerServerListener();
if (status)
this.pendingRequests[name] = {type: type, func: submissionFunc};
// can't submit until the registration is complete...
else {
console.error("SSEClient:submitTask, Can't re-register a ServerListener -- bailing");
await this.unregisterServerListener();
}
} else {
status = await submissionFunc();
// registered - go ahead and submit
}
return status;
}
get id() {
return this.myID;
}
get SSEState() {
return this.SSESource.readyState;
}
get SSEStateText() {
return this.SSESource.readyState === EventSource.CLOSED? "Closed" :
this.SSESource.readyState === EventSource.CONNECTING? "Connecting" :
"Open";
}
async makeID() {
try {
let rsp = await this.mAxios.get(this.PREFIX + 'make-id/' + this.myName);
this.myID = rsp.data;
status = true;
} catch(err) {
console.error("SSEClient:makeid, Error: " + err);
status = false;
}
return status;
}
async doSubmitTask(taskname) {
let status = true;
try {
let rsp = await this.mAxios.put(
this.PREFIX + ["submit-task", this.myID, taskname].join('/'));
} catch(err) {
console.error("SSEClient:doSubmitTask: " + err);
status = false;
}
return status;
}
async submitTask(taskname) {
status = await this._queueSubmission(TASK_TYPE, taskname, this.doSubmitTask.bind(this, taskname));
return status;
}
async doListen(listenKey) {
let status = true;
try {
let rsp = await this.mAxios.put(this.PREFIX + ['listen', this.myID, listenKey].join('/'));
} catch(err) {
console.error('SSEClient:listen, Error: ' + err);
}
return status;
}
async listen(listenKey) {
let status = await this._queueSubmission(LISTEN_TYPE, listenKey, this.doListen.bind(this, listenKey));
return status;
}
/**
* Event listeners get bound to an instance at runtime,
* so they have a valid 'this'. Could pull these out of
* the class, but that they are (eventually) bound to an instance
* really makes them dependent on the class definition.
*
* @param {*} evt
*/
static notificationListener(evt) {
let data = getNotificationData(evt.data);
switch(data.response) {
case "notify":
if (this.cb.sseNotify)
this.cb.sseNotify(data.info);
break;
case "completed":
if (this.cb.sseTaskCompleted)
this.cb.sseTaskCompleted(data.info.taskid);
break;
case "registered":
if (this.cb.sseRegistered)
this.cb.sseRegistered(data.info);
break;
default:
console.error("ServerEventClient:response:Unrecognized: " + data.response);
break;
}
}
static openListener(evt) {
// registration is complete when this is called
let pendingKeys = Object.keys(this.pendingRequests), ix, name, pendingReq;
if (this.cb.sseOpened)
this.cb.sseOpened(this.SSESource.readyState, this.SSEStateText);
// notify the caller we received the open event
for (ix = 0; ix < pendingKeys.length; ++ix) {
// if we have submissions pending, we can do them now.
name = pendingKeys[ix];
pendingReq = this.pendingRequests[name];
submitPendingRequest(pendingReq.func);
// if (pendingReq.type === TASK_TYPE)
delete this.pendingRequests[name];
// remove tasks from the pendingRequests map -
// (listen requests will get resubmitted
// if opened again.)
}
}
static errorListener(evt){
if (this.cb.sseError)
this.cb.sseError(this.SSESource.readyState, this.SSEStateText);
}
async registerServerListener() {
let status = false;
if (!!window.EventSource) {
this.SSESource = new EventSource(
this.APPURL + this.PREFIX + 'register-listener/' + this.myID,
{
https: {rejectUnauthorized: false}
});
if (this.SSESource) {
this.notificationListenerCB = ServerEventClient.notificationListener.bind(this);
this.openListenerCB = ServerEventClient.openListener.bind(this);
this.errorListenerCB = ServerEventClient.errorListener.bind(this);
// define member listener funcs bound to 'this', so the
// listeners will have a valid 'this' and they can be removed.
this.SSESource.addEventListener('message', this.notificationListenerCB);
this.SSESource.addEventListener('open', this.openListenerCB);
this.SSESource.addEventListener('error', this.errorListenerCB);
status = true;
}
}
if (!status)
console.error("Error in ServerEventClient:registerListener - SSE Not supported");
return status;
}
async disconnect() {
try {
let status;
let rsp = await this.mAxios.get(
this.PREFIX + 'disconnect-registrant/' + this.myID);
this.SSESource.removeEventListener('message', this.notificationListenerCB);
this.SSESource.removeEventListener('open', this.openListenerCB);
this.SSESource.removeEventListener('error', this.errorListenerCB);
// remove listeners to prevent 'ghost' calls after
// the instance has been assigned to null, but not
// gc'ed, yet.
this.SSESource = null;
// now assign to null
this.cb.sseClosed();
// notify the caller we're disconnected.
status = true;
} catch(err) {
console.error('ServerEventClient:disconnect, error: ' + err);
status = false;
}
return status;
}
async fetchRegistrants() {
let data = null;
try {
let rsp = await this.mAxios.get(this.PREFIX + 'list-registrants');
data = rsp.data;
} catch(err) {
console.error("Error in ServerEventClient:fetchRegistrants: " + err);
}
return data;
}
async triggerCleanup() {
try {
let rsp = await this.mAxios.get(this.PREFIX + 'trigger-cleanup');
} catch(err) {
console.error("Error in ServerEventClient:triggerCleanup");
}
return 'ok';
}
}
class ServerEventClientFactory {
static async create(name, appurl, cb, prefix) {
if (appurl.charAt(appurl.length - 1) === '/')
appurl = appurl.slice(0, -1);
// remove any trailing slashes.
let client = new ServerEventClient(name, appurl, cb, prefix, true);
let status;
status = await client.makeID();
if (status)
status = await client.registerServerListener();
if (!status)
client = null;
return client;
}
}
export default ServerEventClientFactory;