forked from zaheerm/flumotion-extra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stomp.js
524 lines (455 loc) · 15.1 KB
/
stomp.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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
/* stomp.js
*
* JavaScript implementation of the STOMP (Streaming Text Oriented Protocol)
* for use with TCPConnection or a facsimile
*
* Frank Salim ([email protected]) (c) 2008 Orbited (orbited.org)
* Rui Lopes (ruilopes.com)
*/
STOMP_DEBUG = false;
if (STOMP_DEBUG) {
function getStompLogger(name) {
return {
debug: function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(name, ": ");
console.debug.apply(console, args);
},
dir: function() {
console.debug(name, ":");
console.dir.apply(console, arguments);
}
};
}
} else {
function getStompLogger(name) {
return {
debug: function() {},
dir: function() {}
};
}
}
// NB: This is loosly based on twisted.protocols.basic.LineReceiver
// See http://twistedmatrix.com/documents/8.1.0/api/twisted.protocols.basic.LineReceiver.html
// XXX this assumes the lines are UTF-8 encoded.
// XXX this assumes the lines are terminated with a single NL ("\n") character.
LineProtocol = function(transport) {
var log = getStompLogger("LineProtocol");
var self = this;
var buffer = null;
var isLineMode = true;
//
// Transport callbacks implementation.
//
transport.onopen = function() {
buffer = "";
isLineMode = true;
self.onopen();
};
transport.onclose = function(code) {
buffer = null;
self.onclose(code);
};
transport.onerror = function(error) {
self.onerror(error);
};
transport.onread = function(data) {
log.debug("transport.onread: enter isLineMode=", isLineMode, " buffer[", buffer.length, "]=", buffer, " data[", data.length, "]=", data);
if (isLineMode) {
buffer += data;
data = "";
var start = 0;
var end;
while ((end = buffer.indexOf("\n", start)) >= 0 && isLineMode) {
// TODO it would be nice that decode received the
// start and end indexes, if it did, we didn't
// need the slice copy.
var bytes = buffer.slice(start, end);
// TODO do not depend on Orbited.
var line = Orbited.utf8.decode(bytes)[0];
log.debug("fire onlinereceived line[", line.length, "]=", line);
self.onlinereceived(line);
start = end + 1;
}
// remove the portion (head) of the array we've processed.
buffer = buffer.slice(start);
if (isLineMode) {
// TODO if this buffer length is above a given threshold, we should
// send an alert "max line length exceeded" and empty buffer
// or even abort.
} else {
// we've left the line mode and what remains in buffer is raw data.
data = buffer;
buffer = "";
}
}
if (data.length > 0) {
log.debug("fire onrawdatareceived data[", data.length, "]=", data);
self.onrawdatareceived(data);
}
log.debug("transport.onread: leave");
};
//
// Protocol implementation.
//
self.setRawMode = function() {
log.debug("setRawMode");
isLineMode = false;
};
// TODO although this is a nice interface, it will do a extra copy
// of the data, a probable better alternative would be to
// make onrawdatareceived return the number of consumed bytes
// (instead of making it comsume all the given data).
self.setLineMode = function(extra) {
log.debug("setLineMode: extra=", extra);
isLineMode = true;
if (extra && extra.length > 0)
transport.onread(extra);
};
self.send = function(data) {
log.debug("send: data=", data);
return transport.send(data);
};
self.open = function(host, port, isBinary) {
log.debug("open: host=", host, ':', port, ' isBinary=', isBinary);
transport.open(host, port, isBinary);
};
self.close = function() {
log.debug("close");
transport.close();
};
self.reset = function() {
transport.reset();
}
//
// callbacks for the events generated by this
//
// XXX these callbacks names should be camelCased
self.onopen = function() {};
self.onclose = function() {};
self.onerror = function(error) {};
self.onlinereceived = function(line) {};
self.onrawdatareceived = function(data) {};
};
// TODO propose to rename this to BaseStompClient
// See the comment in the callbacks zone bellow.
// TODO add ";" to all lines (where it makes sense).
// TODO remove deprecated stuff.
//
// Deprecated attributes:
//
// user : string
// the user name used to login into the STOMP server.
//
//
// Methods:
//
// connect(domain : string, port : int, user : string, password : string)
// connects to the given STOMP server.
//
// the connection is established after ``onconnected'' is received.
//
// disconnect()
// disconnects from current STOMP server.
//
// the connection is disconnected after ``onclose'' is received.
//
// TODO: implement ``ondisconnect''.
//
// send(message : string, destination : string, extraHeaders : {}|undefined)
// sends the given message to destination.
//
// subscribe(destination : string)
// starts receiving messages from the given destination.
//
// unsubscribe(destination : string)
// stops receiving messages from the given destination.
//
//
// Callbacks:
//
// onopen()
// underline transport is openned.
//
// onclose()
// underline transport is closed.
//
// onerror(error : Error)
// there was an error.
//
// onframe(frame : Frame)
// received a STOMP frame.
//
// this will dispatch for a specific method based on the frame
// type, eg. when frame.type is "MESSAGE" this calls
// onmessageframe(frame).
//
// frame is an object with the following properties:
//
// type : string
// headers : {string: string}
// body : string
//
// onconnectedframe(frame : Frame)
// received a CONNECTED STOMP frame.
//
// onmessageframe(frame : Frame)
// received a MESSAGE STOMP frame.
//
// onreceiptframe(frame : Frame)
// received a RECEIPT STOMP frame.
//
// onerrorframe(frame : Frame)
// received a ERROR STOMP frame.
//
//
// Deprecated callbacks:
//
// onmessage(frame)
// use ``onmessageframe'' instead.
//
// received a MESSAGE STOMP frame.
//
STOMPClient = function() {
var log = getStompLogger("STOMPClient");
var self = this;
var protocol = null;
var buffer = "";
var type = null;
var headers = null;
var remainingBodyLength = null;
// Deprecated attributes:
self.user = null;
// TODO probably this function should be move into a common base...
function trim(str) {
// See http://blog.stevenlevithan.com/archives/faster-trim-javascript
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function mergeObject(dst, src) {
for (var k in src) {
dst[k] = src[k];
}
return dst;
}
//
// LineProtocol implementation.
//
function protocol_onLineReceived(line) {
log.debug("protocol_onLineReceived: line=", line);
if (line.length == 0) {
// ignore empty lines before the type line.
if (type === null)
return;
// we reached the end headers.
log.debug("onLineReceived: all headers:");
log.dir(headers);
if ('content-length' in headers) {
// NB: content-length does not include the trailing NUL,
// but we need to account it.
remainingBodyLength = parseInt(headers['content-length']) + 1;
} else {
remainingBodyLength = null;
}
protocol.setRawMode();
return;
}
if (type === null) {
log.debug("onLineReceived: begin ", line, " frame");
type = line;
headers = {};
buffer = "";
remainingBodyLength = null;
return;
}
var sep = line.search(":");
var key = trim(line.slice(0, sep));
var value = trim(line.slice(sep + 1));
headers[key] = value;
log.debug("onLineReceived: found header ", key, "=", value);
}
if (STOMP_DEBUG) {
function dumpStringAsIntArray(title, data) {
var bytes = [];
for (var n = 0; n < data.length; ++n) {
bytes.push(data.charCodeAt(n));
}
log.debug(title);
log.debug('length=', bytes.length, " bytes=", bytes);
}
} else {
function dumpStringAsIntArray() {}
}
function protocol_onRawDataReceived(data) {
log.debug("protocol_onRawDataReceived");
dumpStringAsIntArray("buffer", buffer);
dumpStringAsIntArray("data", data);
if (remainingBodyLength === null) {
// we're doing a message parsing without knowing the exact
// body length.
buffer += data;
var end = buffer.indexOf("\0");
if (end >= 0) {
// split into head (bytes) and tail (buffer).
var bytes = buffer.slice(0, end);
buffer = buffer.slice(end + 1);
doDispatch(bytes, buffer);
}
} else {
// we're doing a message parsing knowing the exact body
// length.
var toRead = Math.min(data.length, remainingBodyLength);
remainingBodyLength -= toRead;
// split into head (bytes) and tail (data).
if (remainingBodyLength === 0) {
var bytes = data.slice(0, toRead - 1);
} else {
var bytes = data.slice(0, toRead);
}
data = data.slice(toRead);
// buffer will contain the whole message body.
buffer += bytes;
if (remainingBodyLength === 0) {
doDispatch(buffer, data);
}
}
}
function doDispatch(bytes, extra) {
log.debug("doDispatch: bytes[", bytes.length, "]=", bytes, " extra[", extra.length, "]=", extra);
dumpStringAsIntArray("bytes", bytes);
dumpStringAsIntArray("extra", extra);
var frame = {
type: type,
headers: headers,
// TODO stop assuming the body is UTF8 encoded.
body: Orbited.utf8.decode(bytes)[0]
};
log.debug("doDispatch: end frame; body.length=", frame.body.length);
log.dir(frame);
self.onframe(frame);
buffer = "";
type = null;
headers = {};
remainingBodyLength = null;
protocol.setLineMode(extra);
}
//
// Callbacks
//
function Ignored() {}
self.onopen = Ignored;
self.onclose = Ignored;
self.onerror = Ignored;
self.onframe = function(frame) {
switch (frame.type) {
case 'CONNECTED':
self.onconnectedframe(frame);
break;
case 'MESSAGE':
self.onmessageframe(frame);
break;
case 'RECEIPT':
self.onreceiptframe(frame);
break;
case 'ERROR':
self.onerrorframe(frame);
break;
default:
self.onerror("Unknown STOMP frame type " + frame.type);
}
};
self.onconnectedframe = Ignored;
self.onreceiptframe = Ignored;
self.onmessageframe = function(frame) {
// TODO stop calling deprecated onmessage.
if (this.onmessage)
this.onmessage(frame);
};
self.onerrorframe = Ignored;
// Deprecated callbacks
self.onmessage = Ignored;
//
// Methods
//
self.sendFrame = function(type, headers, body) {
var head = [type];
var ignoreHeaders = {};
if (body && headers['content-length'] === undefined) {
if (headers["content-type"] === undefined) {
head.push("content-type:text/plain");
ignoreHeaders["content-type"] = true;
}
if (headers["content-encoding"] === undefined) {
head.push("content-encoding:utf-8");
ignoreHeaders["content-encoding"] = true;
body = Orbited.utf8.encode(body);
}
head.push("content-length:" + body.length);
ignoreHeaders["content-length"] = true;
}
for (var key in headers) {
if (!(key in ignoreHeaders))
head.push(key + ":" + headers[key]);
}
head.push("\n");
var bytes = Orbited.utf8.encode(head.join("\n"));
if (body) {
bytes += body;
}
bytes += "\x00";
protocol.send(bytes);
};
// TODO Deprecated
self.send_frame = self.sendFrame;
self.connect = function(domain, port, user, password) {
// TODO deprecated
self.user = user;
function onopen() {
self.sendFrame("CONNECT", {'login':user, 'passcode':password});
self.onopen();
}
protocol = self._createProtocol();
protocol.onopen = onopen;
// XXX even though we are connecting to onclose, this never gets fired
// after we shutdown orbited.
protocol.onclose = self.onclose;
// TODO what should we do when there is a protocol error?
protocol.onerror = self.onerror;
protocol.onlinereceived = protocol_onLineReceived;
protocol.onrawdatareceived = protocol_onRawDataReceived;
protocol.open(domain, port, true);
};
// NB: this is needed for the unit tests.
self._createProtocol = function() {
return new LineProtocol(new TCPSocket());
};
self.disconnect = function() {
// NB: after we send a DISCONNECT frame, the STOMP server
// should automatically close the transport, which will
// trigger an "onclose" event.
self.sendFrame("DISCONNECT");
};
self.reset = function() {
protocol.reset();
}
self.send = function(message, destination, extraHeaders) {
self.sendFrame("SEND", mergeObject({destination:destination}, extraHeaders), message);
};
self.subscribe = function(destination, extraHeaders) {
self.sendFrame("SUBSCRIBE", mergeObject({destination:destination}, extraHeaders));
};
self.unsubscribe = function(destination, extraHeaders) {
self.sendFrame("UNSUBSCRIBE", mergeObject({destination:destination}, extraHeaders));
};
self.begin = function(id) {
self.sendFrame("BEGIN", {"transaction": id});
};
self.commit = function(id) {
self.sendFrame("COMMIT", {"transaction": id});
};
self.abort = function(id) {
self.sendFrame("ABORT", {"transaction": id});
};
self.ack = function(message_id, transaction_id) {
// TODO implement
};
}