blob: 7a18206b38de3590c9098952de69e01013b8c785 [file] [log] [blame]
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20/*jshint evil:true*/
21
22/**
23 * The Thrift namespace houses the Apache Thrift JavaScript library
24 * elements providing JavaScript bindings for the Apache Thrift RPC
henrique2a7dccc2014-03-07 22:16:51 +010025 * system. End users will typically only directly make use of the
26 * Transport (TXHRTransport/TWebSocketTransport) and Protocol
27 * (TJSONPRotocol/TBinaryProtocol) constructors.
28 *
29 * Object methods beginning with a __ (e.g. __onOpen()) are internal
30 * and should not be called outside of the object's own methods.
31 *
32 * This library creates one global object: Thrift
33 * Code in this library must never create additional global identifiers,
34 * all features must be scoped within the Thrift namespace.
Henrique Mendonça095ddb72013-09-20 19:38:03 +020035 * @namespace
36 * @example
37 * var transport = new Thrift.Transport("http://localhost:8585");
38 * var protocol = new Thrift.Protocol(transport);
39 * var client = new MyThriftSvcClient(protocol);
40 * var result = client.MyMethod();
41 */
42var Thrift = {
43 /**
44 * Thrift JavaScript library version.
45 * @readonly
46 * @const {string} Version
47 * @memberof Thrift
48 */
49 Version: '1.0.0-dev',
50
51 /**
52 * Thrift IDL type string to Id mapping.
53 * @readonly
54 * @property {number} STOP - End of a set of fields.
55 * @property {number} VOID - No value (only legal for return types).
56 * @property {number} BOOL - True/False integer.
57 * @property {number} BYTE - Signed 8 bit integer.
58 * @property {number} I08 - Signed 8 bit integer.
59 * @property {number} DOUBLE - 64 bit IEEE 854 floating point.
60 * @property {number} I16 - Signed 16 bit integer.
61 * @property {number} I32 - Signed 32 bit integer.
62 * @property {number} I64 - Signed 64 bit integer.
63 * @property {number} STRING - Array of bytes representing a string of characters.
64 * @property {number} UTF7 - Array of bytes representing a string of UTF7 encoded characters.
65 * @property {number} STRUCT - A multifield type.
66 * @property {number} MAP - A collection type (map/associative-array/dictionary).
67 * @property {number} SET - A collection type (unordered and without repeated values).
68 * @property {number} LIST - A collection type (unordered).
69 * @property {number} UTF8 - Array of bytes representing a string of UTF8 encoded characters.
70 * @property {number} UTF16 - Array of bytes representing a string of UTF16 encoded characters.
71 */
72 Type: {
73 'STOP' : 0,
74 'VOID' : 1,
75 'BOOL' : 2,
76 'BYTE' : 3,
77 'I08' : 3,
78 'DOUBLE' : 4,
79 'I16' : 6,
80 'I32' : 8,
81 'I64' : 10,
82 'STRING' : 11,
83 'UTF7' : 11,
84 'STRUCT' : 12,
85 'MAP' : 13,
86 'SET' : 14,
87 'LIST' : 15,
88 'UTF8' : 16,
89 'UTF16' : 17
90 },
91
92 /**
93 * Thrift RPC message type string to Id mapping.
94 * @readonly
95 * @property {number} CALL - RPC call sent from client to server.
96 * @property {number} REPLY - RPC call normal response from server to client.
97 * @property {number} EXCEPTION - RPC call exception response from server to client.
98 * @property {number} ONEWAY - Oneway RPC call from client to server with no response.
99 */
100 MessageType: {
101 'CALL' : 1,
102 'REPLY' : 2,
103 'EXCEPTION' : 3,
104 'ONEWAY' : 4
105 },
106
107 /**
108 * Utility function returning the count of an object's own properties.
109 * @param {object} obj - Object to test.
110 * @returns {number} number of object's own properties
111 */
112 objectLength: function(obj) {
113 var length = 0;
114 for (var k in obj) {
115 if (obj.hasOwnProperty(k)) {
116 length++;
117 }
118 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200119 return length;
120 },
121
122 /**
123 * Utility function to establish prototype inheritance.
124 * @see {@link http://javascript.crockford.com/prototypal.html|Prototypal Inheritance}
125 * @param {function} constructor - Contstructor function to set as derived.
126 * @param {function} superConstructor - Contstructor function to set as base.
127 * @param {string} [name] - Type name to set as name property in derived prototype.
128 */
129 inherits: function(constructor, superConstructor, name) {
130 function F() {}
131 F.prototype = superConstructor.prototype;
132 constructor.prototype = new F();
133 constructor.prototype.name = name || "";
134 }
135};
136
137/**
138 * Initializes a Thrift TException instance.
139 * @constructor
140 * @augments Error
141 * @param {string} message - The TException message (distinct from the Error message).
142 * @classdesc TException is the base class for all Thrift exceptions types.
143 */
144Thrift.TException = function(message) {
145 this.message = message;
146};
147Thrift.inherits(Thrift.TException, Error, 'TException');
148
149/**
150 * Returns the message set on the exception.
151 * @readonly
152 * @returns {string} exception message
153 */
154Thrift.TException.prototype.getMessage = function() {
155 return this.message;
156};
157
158/**
159 * Thrift Application Exception type string to Id mapping.
160 * @readonly
161 * @property {number} UNKNOWN - Unknown/undefined.
162 * @property {number} UNKNOWN_METHOD - Client attempted to call a method unknown to the server.
163 * @property {number} INVALID_MESSAGE_TYPE - Client passed an unknown/unsupported MessageType.
164 * @property {number} WRONG_METHOD_NAME - Unused.
165 * @property {number} BAD_SEQUENCE_ID - Unused in Thrift RPC, used to flag proprietary sequence number errors.
166 * @property {number} MISSING_RESULT - Raised by a server processor if a handler fails to supply the required return result.
167 * @property {number} INTERNAL_ERROR - Something bad happened.
168 * @property {number} PROTOCOL_ERROR - The protocol layer failed to serialize or deserialize data.
169 * @property {number} INVALID_TRANSFORM - Unused.
170 * @property {number} INVALID_PROTOCOL - The protocol (or version) is not supported.
171 * @property {number} UNSUPPORTED_CLIENT_TYPE - Unused.
172 */
173Thrift.TApplicationExceptionType = {
174 'UNKNOWN' : 0,
175 'UNKNOWN_METHOD' : 1,
176 'INVALID_MESSAGE_TYPE' : 2,
177 'WRONG_METHOD_NAME' : 3,
178 'BAD_SEQUENCE_ID' : 4,
179 'MISSING_RESULT' : 5,
180 'INTERNAL_ERROR' : 6,
181 'PROTOCOL_ERROR' : 7,
182 'INVALID_TRANSFORM' : 8,
183 'INVALID_PROTOCOL' : 9,
184 'UNSUPPORTED_CLIENT_TYPE' : 10
185};
186
187/**
188 * Initializes a Thrift TApplicationException instance.
189 * @constructor
190 * @augments Thrift.TException
191 * @param {string} message - The TApplicationException message (distinct from the Error message).
192 * @param {Thrift.TApplicationExceptionType} [code] - The TApplicationExceptionType code.
193 * @classdesc TApplicationException is the exception class used to propagate exceptions from an RPC server back to a calling client.
194*/
195Thrift.TApplicationException = function(message, code) {
196 this.message = message;
197 this.code = typeof code === "number" ? code : 0;
198};
199Thrift.inherits(Thrift.TApplicationException, Thrift.TException, 'TApplicationException');
200
201/**
202 * Read a TApplicationException from the supplied protocol.
203 * @param {object} input - The input protocol to read from.
204 */
205Thrift.TApplicationException.prototype.read = function(input) {
206 while (1) {
207 var ret = input.readFieldBegin();
208
209 if (ret.ftype == Thrift.Type.STOP) {
210 break;
211 }
212
213 var fid = ret.fid;
214
215 switch (fid) {
216 case 1:
217 if (ret.ftype == Thrift.Type.STRING) {
218 ret = input.readString();
219 this.message = ret.value;
220 } else {
221 ret = input.skip(ret.ftype);
222 }
223 break;
224 case 2:
225 if (ret.ftype == Thrift.Type.I32) {
226 ret = input.readI32();
227 this.code = ret.value;
228 } else {
229 ret = input.skip(ret.ftype);
230 }
231 break;
232 default:
233 ret = input.skip(ret.ftype);
234 break;
235 }
236
237 input.readFieldEnd();
238 }
239
240 input.readStructEnd();
241};
242
243/**
244 * Wite a TApplicationException to the supplied protocol.
245 * @param {object} output - The output protocol to write to.
246 */
247Thrift.TApplicationException.prototype.write = function(output) {
248 output.writeStructBegin('TApplicationException');
249
250 if (this.message) {
251 output.writeFieldBegin('message', Thrift.Type.STRING, 1);
252 output.writeString(this.getMessage());
253 output.writeFieldEnd();
254 }
255
256 if (this.code) {
257 output.writeFieldBegin('type', Thrift.Type.I32, 2);
258 output.writeI32(this.code);
259 output.writeFieldEnd();
260 }
261
262 output.writeFieldStop();
263 output.writeStructEnd();
264};
265
266/**
267 * Returns the application exception code set on the exception.
268 * @readonly
269 * @returns {Thrift.TApplicationExceptionType} exception code
270 */
271Thrift.TApplicationException.prototype.getCode = function() {
272 return this.code;
273};
274
275/**
henrique2a7dccc2014-03-07 22:16:51 +0100276 * Constructor Function for the XHR transport.
277 * If you do not specify a url then you must handle XHR operations on
278 * your own. This type can also be constructed using the Transport alias
279 * for backward compatibility.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200280 * @constructor
281 * @param {string} [url] - The URL to connect to.
henrique2a7dccc2014-03-07 22:16:51 +0100282 * @classdesc The Apache Thrift Transport layer performs byte level I/O
283 * between RPC clients and servers. The JavaScript TXHRTransport object
284 * uses Http[s]/XHR. Target servers must implement the http[s] transport
285 * (see: node.js example server_http.js).
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200286 * @example
henrique2a7dccc2014-03-07 22:16:51 +0100287 * var transport = new Thrift.TXHRTransport("http://localhost:8585");
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200288 */
Roger Meier52744ee2014-03-12 09:38:42 +0100289Thrift.Transport = Thrift.TXHRTransport = function(url, options) {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200290 this.url = url;
291 this.wpos = 0;
292 this.rpos = 0;
Roger Meier52744ee2014-03-12 09:38:42 +0100293 this.useCORS = (options && options.useCORS);
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200294 this.send_buf = '';
295 this.recv_buf = '';
296};
297
henrique2a7dccc2014-03-07 22:16:51 +0100298Thrift.TXHRTransport.prototype = {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200299 /**
300 * Gets the browser specific XmlHttpRequest Object.
301 * @returns {object} the browser XHR interface object
302 */
303 getXmlHttpRequestObject: function() {
304 try { return new XMLHttpRequest(); } catch (e1) { }
305 try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e2) { }
306 try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e3) { }
307
308 throw "Your browser doesn't support XHR.";
309 },
310
311 /**
henrique2a7dccc2014-03-07 22:16:51 +0100312 * Sends the current XRH request if the transport was created with a URL
313 * and the async parameter is false. If the transport was not created with
314 * a URL, or the async parameter is True and no callback is provided, or
315 * the URL is an empty string, the current send buffer is returned.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200316 * @param {object} async - If true the current send buffer is returned.
henrique2a7dccc2014-03-07 22:16:51 +0100317 * @param {object} callback - Optional async completion callback
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200318 * @returns {undefined|string} Nothing or the current send buffer.
319 * @throws {string} If XHR fails.
320 */
henriquea2de4102014-02-07 14:12:56 +0100321 flush: function(async, callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100322 var self = this;
henriquea2de4102014-02-07 14:12:56 +0100323 if ((async && !callback) || this.url === undefined || this.url === '') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200324 return this.send_buf;
325 }
326
327 var xreq = this.getXmlHttpRequestObject();
328
329 if (xreq.overrideMimeType) {
330 xreq.overrideMimeType('application/json');
331 }
332
henriquea2de4102014-02-07 14:12:56 +0100333 if (callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100334 //Ignore XHR callbacks until the data arrives, then call the
335 // client's callback
336 xreq.onreadystatechange =
337 (function() {
338 var clientCallback = callback;
339 return function() {
340 if (this.readyState == 4 && this.status == 200) {
341 self.setRecvBuffer(this.responseText);
342 clientCallback();
343 }
344 };
345 }());
henriquea2de4102014-02-07 14:12:56 +0100346 }
347
348 xreq.open('POST', this.url, !!async);
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200349 xreq.send(this.send_buf);
henriquea2de4102014-02-07 14:12:56 +0100350 if (async && callback) {
351 return;
352 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200353
354 if (xreq.readyState != 4) {
355 throw 'encountered an unknown ajax ready state: ' + xreq.readyState;
356 }
357
358 if (xreq.status != 200) {
359 throw 'encountered a unknown request status: ' + xreq.status;
360 }
361
362 this.recv_buf = xreq.responseText;
363 this.recv_buf_sz = this.recv_buf.length;
364 this.wpos = this.recv_buf.length;
365 this.rpos = 0;
366 },
367
368 /**
369 * Creates a jQuery XHR object to be used for a Thrift server call.
370 * @param {object} client - The Thrift Service client object generated by the IDL compiler.
371 * @param {object} postData - The message to send to the server.
henrique2a7dccc2014-03-07 22:16:51 +0100372 * @param {function} args - The original call arguments with the success call back at the end.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200373 * @param {function} recv_method - The Thrift Service Client receive method for the call.
374 * @returns {object} A new jQuery XHR object.
375 * @throws {string} If the jQuery version is prior to 1.5 or if jQuery is not found.
376 */
377 jqRequest: function(client, postData, args, recv_method) {
378 if (typeof jQuery === 'undefined' ||
379 typeof jQuery.Deferred === 'undefined') {
380 throw 'Thrift.js requires jQuery 1.5+ to use asynchronous requests';
381 }
382
383 var thriftTransport = this;
384
385 var jqXHR = jQuery.ajax({
386 url: this.url,
387 data: postData,
388 type: 'POST',
389 cache: false,
390 contentType: 'application/json',
391 dataType: 'text thrift',
392 converters: {
393 'text thrift' : function(responseData) {
394 thriftTransport.setRecvBuffer(responseData);
395 var value = recv_method.call(client);
396 return value;
397 }
398 },
399 context: client,
400 success: jQuery.makeArray(args).pop()
401 });
402
403 return jqXHR;
404 },
405
406 /**
henrique2a7dccc2014-03-07 22:16:51 +0100407 * Sets the buffer to provide the protocol when deserializing.
408 * @param {string} buf - The buffer to supply the protocol.
409 */
410 setRecvBuffer: function(buf) {
411 this.recv_buf = buf;
412 this.recv_buf_sz = this.recv_buf.length;
413 this.wpos = this.recv_buf.length;
414 this.rpos = 0;
415 },
416
417 /**
418 * Returns true if the transport is open, XHR always returns true.
419 * @readonly
420 * @returns {boolean} Always True.
421 */
422 isOpen: function() {
423 return true;
424 },
425
426 /**
427 * Opens the transport connection, with XHR this is a nop.
428 */
429 open: function() {},
430
431 /**
432 * Closes the transport connection, with XHR this is a nop.
433 */
434 close: function() {},
435
436 /**
437 * Returns the specified number of characters from the response
438 * buffer.
439 * @param {number} len - The number of characters to return.
440 * @returns {string} Characters sent by the server.
441 */
442 read: function(len) {
443 var avail = this.wpos - this.rpos;
444
445 if (avail === 0) {
446 return '';
447 }
448
449 var give = len;
450
451 if (avail < len) {
452 give = avail;
453 }
454
455 var ret = this.read_buf.substr(this.rpos, give);
456 this.rpos += give;
457
458 //clear buf when complete?
459 return ret;
460 },
461
462 /**
463 * Returns the entire response buffer.
464 * @returns {string} Characters sent by the server.
465 */
466 readAll: function() {
467 return this.recv_buf;
468 },
469
470 /**
471 * Sets the send buffer to buf.
472 * @param {string} buf - The buffer to send.
473 */
474 write: function(buf) {
475 this.send_buf = buf;
476 },
477
478 /**
479 * Returns the send buffer.
480 * @readonly
481 * @returns {string} The send buffer.
482 */
483 getSendBuffer: function() {
484 return this.send_buf;
485 }
486
487};
488
489
490/**
491 * Constructor Function for the WebSocket transport.
492 * @constructor
493 * @param {string} [url] - The URL to connect to.
494 * @classdesc The Apache Thrift Transport layer performs byte level I/O
495 * between RPC clients and servers. The JavaScript TWebSocketTransport object
496 * uses the WebSocket protocol. Target servers must implement WebSocket.
497 * (see: node.js example server_http.js).
498 * @example
499 * var transport = new Thrift.TWebSocketTransport("http://localhost:8585");
500 */
501Thrift.TWebSocketTransport = function(url) {
502 this.__reset(url);
503};
504
505Thrift.TWebSocketTransport.prototype = {
506 __reset: function(url) {
507 this.url = url; //Where to connect
508 this.socket = null; //The web socket
509 this.callbacks = []; //Pending callbacks
510 this.send_pending = []; //Buffers/Callback pairs waiting to be sent
511 this.send_buf = ''; //Outbound data, immutable until sent
512 this.recv_buf = ''; //Inbound data
513 this.rb_wpos = 0; //Network write position in receive buffer
514 this.rb_rpos = 0; //Client read position in receive buffer
515 },
516
517 /**
518 * Sends the current WS request and registers callback. The async
519 * parameter is ignored (WS flush is always async) and the callback
520 * function parameter is required.
521 * @param {object} async - Ignored.
522 * @param {object} callback - The client completion callback.
523 * @returns {undefined|string} Nothing (undefined)
524 */
525 flush: function(async, callback) {
526 var self = this;
527 if (this.isOpen()) {
528 //Send data and register a callback to invoke the client callback
529 this.socket.send(this.send_buf);
530 this.callbacks.push((function() {
531 var clientCallback = callback;
532 return function(msg) {
533 self.setRecvBuffer(msg);
534 clientCallback();
535 };
536 }()));
537 } else {
538 //Queue the send to go out __onOpen
539 this.send_pending.push({
540 buf: this.send_buf,
541 cb: callback
542 });
543 }
544 },
545
546 __onOpen: function() {
547 var self = this;
548 if (this.send_pending.length > 0) {
549 //If the user made calls before the connection was fully
550 //open, send them now
551 this.send_pending.forEach(function(elem) {
552 this.socket.send(elem.buf);
553 this.callbacks.push((function() {
554 var clientCallback = elem.cb;
555 return function(msg) {
556 self.setRecvBuffer(msg);
557 clientCallback();
558 };
559 }()));
560 });
561 this.send_pending = [];
562 }
563 },
564
565 __onClose: function(evt) {
566 this.__reset(this.url);
567 },
568
569 __onMessage: function(evt) {
570 if (this.callbacks.length) {
571 this.callbacks.shift()(evt.data);
572 }
573 },
574
575 __onError: function(evt) {
576 console.log("Thrift WebSocket Error: " + evt.toString());
577 this.socket.close();
578 },
579
580 /**
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200581 * Sets the buffer to use when receiving server responses.
582 * @param {string} buf - The buffer to receive server responses.
583 */
584 setRecvBuffer: function(buf) {
585 this.recv_buf = buf;
586 this.recv_buf_sz = this.recv_buf.length;
587 this.wpos = this.recv_buf.length;
588 this.rpos = 0;
589 },
590
591 /**
henrique2a7dccc2014-03-07 22:16:51 +0100592 * Returns true if the transport is open
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200593 * @readonly
henrique2a7dccc2014-03-07 22:16:51 +0100594 * @returns {boolean}
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200595 */
596 isOpen: function() {
henrique2a7dccc2014-03-07 22:16:51 +0100597 return this.socket && this.socket.readyState == this.socket.OPEN;
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200598 },
599
600 /**
henrique2a7dccc2014-03-07 22:16:51 +0100601 * Opens the transport connection
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200602 */
henrique2a7dccc2014-03-07 22:16:51 +0100603 open: function() {
604 //If OPEN/CONNECTING/CLOSING ignore additional opens
605 if (this.socket && this.socket.readyState != this.socket.CLOSED) {
606 return;
607 }
608 //If there is no socket or the socket is closed:
609 this.socket = new WebSocket(this.url);
610 this.socket.onopen = this.__onOpen.bind(this);
611 this.socket.onmessage = this.__onMessage.bind(this);
612 this.socket.onerror = this.__onError.bind(this);
613 this.socket.onclose = this.__onClose.bind(this);
614 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200615
616 /**
henrique2a7dccc2014-03-07 22:16:51 +0100617 * Closes the transport connection
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200618 */
henrique2a7dccc2014-03-07 22:16:51 +0100619 close: function() {
620 this.socket.close();
621 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200622
623 /**
624 * Returns the specified number of characters from the response
625 * buffer.
626 * @param {number} len - The number of characters to return.
627 * @returns {string} Characters sent by the server.
628 */
629 read: function(len) {
630 var avail = this.wpos - this.rpos;
631
632 if (avail === 0) {
633 return '';
634 }
635
636 var give = len;
637
638 if (avail < len) {
639 give = avail;
640 }
641
642 var ret = this.read_buf.substr(this.rpos, give);
643 this.rpos += give;
644
645 //clear buf when complete?
646 return ret;
647 },
648
649 /**
650 * Returns the entire response buffer.
651 * @returns {string} Characters sent by the server.
652 */
653 readAll: function() {
654 return this.recv_buf;
655 },
656
657 /**
658 * Sets the send buffer to buf.
659 * @param {string} buf - The buffer to send.
660 */
661 write: function(buf) {
662 this.send_buf = buf;
663 },
664
665 /**
666 * Returns the send buffer.
667 * @readonly
668 * @returns {string} The send buffer.
669 */
670 getSendBuffer: function() {
671 return this.send_buf;
672 }
673
674};
675
676/**
677 * Initializes a Thrift JSON protocol instance.
678 * @constructor
679 * @param {Thrift.Transport} transport - The transport to serialize to/from.
680 * @classdesc Apache Thrift Protocols perform serialization which enables cross
681 * language RPC. The Protocol type is the JavaScript browser implementation
682 * of the Apache Thrift TJSONProtocol.
683 * @example
684 * var protocol = new Thrift.Protocol(transport);
685 */
Roger Meier52744ee2014-03-12 09:38:42 +0100686Thrift.TJSONProtocol = Thrift.Protocol = function(transport) {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200687 this.transport = transport;
688};
689
690/**
691 * Thrift IDL type Id to string mapping.
692 * @readonly
693 * @see {@link Thrift.Type}
694 */
695Thrift.Protocol.Type = {};
696Thrift.Protocol.Type[Thrift.Type.BOOL] = '"tf"';
697Thrift.Protocol.Type[Thrift.Type.BYTE] = '"i8"';
698Thrift.Protocol.Type[Thrift.Type.I16] = '"i16"';
699Thrift.Protocol.Type[Thrift.Type.I32] = '"i32"';
700Thrift.Protocol.Type[Thrift.Type.I64] = '"i64"';
701Thrift.Protocol.Type[Thrift.Type.DOUBLE] = '"dbl"';
702Thrift.Protocol.Type[Thrift.Type.STRUCT] = '"rec"';
703Thrift.Protocol.Type[Thrift.Type.STRING] = '"str"';
704Thrift.Protocol.Type[Thrift.Type.MAP] = '"map"';
705Thrift.Protocol.Type[Thrift.Type.LIST] = '"lst"';
706Thrift.Protocol.Type[Thrift.Type.SET] = '"set"';
707
708/**
709 * Thrift IDL type string to Id mapping.
710 * @readonly
711 * @see {@link Thrift.Type}
712 */
713Thrift.Protocol.RType = {};
714Thrift.Protocol.RType.tf = Thrift.Type.BOOL;
715Thrift.Protocol.RType.i8 = Thrift.Type.BYTE;
716Thrift.Protocol.RType.i16 = Thrift.Type.I16;
717Thrift.Protocol.RType.i32 = Thrift.Type.I32;
718Thrift.Protocol.RType.i64 = Thrift.Type.I64;
719Thrift.Protocol.RType.dbl = Thrift.Type.DOUBLE;
720Thrift.Protocol.RType.rec = Thrift.Type.STRUCT;
721Thrift.Protocol.RType.str = Thrift.Type.STRING;
722Thrift.Protocol.RType.map = Thrift.Type.MAP;
723Thrift.Protocol.RType.lst = Thrift.Type.LIST;
724Thrift.Protocol.RType.set = Thrift.Type.SET;
725
726/**
727 * The TJSONProtocol version number.
728 * @readonly
729 * @const {number} Version
730 * @memberof Thrift.Protocol
731 */
732 Thrift.Protocol.Version = 1;
733
734Thrift.Protocol.prototype = {
735 /**
736 * Returns the underlying transport.
737 * @readonly
738 * @returns {Thrift.Transport} The underlying transport.
739 */
740 getTransport: function() {
741 return this.transport;
742 },
743
744 /**
745 * Serializes the beginning of a Thrift RPC message.
746 * @param {string} name - The service method to call.
747 * @param {Thrift.MessageType} messageType - The type of method call.
748 * @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift).
749 */
750 writeMessageBegin: function(name, messageType, seqid) {
751 this.tstack = [];
752 this.tpos = [];
753
754 this.tstack.push([Thrift.Protocol.Version, '"' +
755 name + '"', messageType, seqid]);
756 },
757
758 /**
759 * Serializes the end of a Thrift RPC message.
760 */
761 writeMessageEnd: function() {
762 var obj = this.tstack.pop();
763
764 this.wobj = this.tstack.pop();
765 this.wobj.push(obj);
766
767 this.wbuf = '[' + this.wobj.join(',') + ']';
768
769 this.transport.write(this.wbuf);
770 },
771
772
773 /**
774 * Serializes the beginning of a struct.
775 * @param {string} name - The name of the struct.
776 */
777 writeStructBegin: function(name) {
778 this.tpos.push(this.tstack.length);
779 this.tstack.push({});
780 },
781
782 /**
783 * Serializes the end of a struct.
784 */
785 writeStructEnd: function() {
786
787 var p = this.tpos.pop();
788 var struct = this.tstack[p];
789 var str = '{';
790 var first = true;
791 for (var key in struct) {
792 if (first) {
793 first = false;
794 } else {
795 str += ',';
796 }
797
798 str += key + ':' + struct[key];
799 }
800
801 str += '}';
802 this.tstack[p] = str;
803 },
804
805 /**
806 * Serializes the beginning of a struct field.
807 * @param {string} name - The name of the field.
808 * @param {Thrift.Protocol.Type} fieldType - The data type of the field.
809 * @param {number} fieldId - The field's unique identifier.
810 */
811 writeFieldBegin: function(name, fieldType, fieldId) {
812 this.tpos.push(this.tstack.length);
813 this.tstack.push({ 'fieldId': '"' +
814 fieldId + '"', 'fieldType': Thrift.Protocol.Type[fieldType]
815 });
816
817 },
818
819 /**
820 * Serializes the end of a field.
821 */
822 writeFieldEnd: function() {
823 var value = this.tstack.pop();
824 var fieldInfo = this.tstack.pop();
825
826 this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' +
827 fieldInfo.fieldType + ':' + value + '}';
828 this.tpos.pop();
829 },
830
831 /**
832 * Serializes the end of the set of fields for a struct.
833 */
834 writeFieldStop: function() {
835 //na
836 },
837
838 /**
839 * Serializes the beginning of a map collection.
840 * @param {Thrift.Type} keyType - The data type of the key.
841 * @param {Thrift.Type} valType - The data type of the value.
842 * @param {number} [size] - The number of elements in the map (ignored).
843 */
844 writeMapBegin: function(keyType, valType, size) {
845 this.tpos.push(this.tstack.length);
846 this.tstack.push([Thrift.Protocol.Type[keyType],
847 Thrift.Protocol.Type[valType], 0]);
848 },
849
850 /**
851 * Serializes the end of a map.
852 */
853 writeMapEnd: function() {
854 var p = this.tpos.pop();
855
856 if (p == this.tstack.length) {
857 return;
858 }
859
860 if ((this.tstack.length - p - 1) % 2 !== 0) {
861 this.tstack.push('');
862 }
863
864 var size = (this.tstack.length - p - 1) / 2;
865
866 this.tstack[p][this.tstack[p].length - 1] = size;
867
868 var map = '}';
869 var first = true;
870 while (this.tstack.length > p + 1) {
871 var v = this.tstack.pop();
872 var k = this.tstack.pop();
873 if (first) {
874 first = false;
875 } else {
876 map = ',' + map;
877 }
878
879 if (! isNaN(k)) { k = '"' + k + '"'; } //json "keys" need to be strings
880 map = k + ':' + v + map;
881 }
882 map = '{' + map;
883
884 this.tstack[p].push(map);
885 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
886 },
887
888 /**
889 * Serializes the beginning of a list collection.
890 * @param {Thrift.Type} elemType - The data type of the elements.
891 * @param {number} size - The number of elements in the list.
892 */
893 writeListBegin: function(elemType, size) {
894 this.tpos.push(this.tstack.length);
895 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
896 },
897
898 /**
899 * Serializes the end of a list.
900 */
901 writeListEnd: function() {
902 var p = this.tpos.pop();
903
904 while (this.tstack.length > p + 1) {
905 var tmpVal = this.tstack[p + 1];
906 this.tstack.splice(p + 1, 1);
907 this.tstack[p].push(tmpVal);
908 }
909
910 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
911 },
912
913 /**
914 * Serializes the beginning of a set collection.
915 * @param {Thrift.Type} elemType - The data type of the elements.
916 * @param {number} size - The number of elements in the list.
917 */
918 writeSetBegin: function(elemType, size) {
919 this.tpos.push(this.tstack.length);
920 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
921 },
922
923 /**
924 * Serializes the end of a set.
925 */
926 writeSetEnd: function() {
927 var p = this.tpos.pop();
928
929 while (this.tstack.length > p + 1) {
930 var tmpVal = this.tstack[p + 1];
931 this.tstack.splice(p + 1, 1);
932 this.tstack[p].push(tmpVal);
933 }
934
935 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
936 },
937
938 /** Serializes a boolean */
939 writeBool: function(value) {
940 this.tstack.push(value ? 1 : 0);
941 },
942
943 /** Serializes a number */
944 writeByte: function(i8) {
945 this.tstack.push(i8);
946 },
947
948 /** Serializes a number */
949 writeI16: function(i16) {
950 this.tstack.push(i16);
951 },
952
953 /** Serializes a number */
954 writeI32: function(i32) {
955 this.tstack.push(i32);
956 },
957
958 /** Serializes a number */
959 writeI64: function(i64) {
960 this.tstack.push(i64);
961 },
962
963 /** Serializes a number */
964 writeDouble: function(dbl) {
965 this.tstack.push(dbl);
966 },
967
968 /** Serializes a string */
969 writeString: function(str) {
970 // We do not encode uri components for wire transfer:
971 if (str === null) {
972 this.tstack.push(null);
973 } else {
974 // concat may be slower than building a byte buffer
975 var escapedString = '';
976 for (var i = 0; i < str.length; i++) {
977 var ch = str.charAt(i); // a single double quote: "
978 if (ch === '\"') {
979 escapedString += '\\\"'; // write out as: \"
Roger Meier52744ee2014-03-12 09:38:42 +0100980 } else if (ch === '\\') { // a single backslash
981 escapedString += '\\\\'; // write out as double backslash
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200982 } else if (ch === '\b') { // a single backspace: invisible
983 escapedString += '\\b'; // write out as: \b"
984 } else if (ch === '\f') { // a single formfeed: invisible
985 escapedString += '\\f'; // write out as: \f"
986 } else if (ch === '\n') { // a single newline: invisible
987 escapedString += '\\n'; // write out as: \n"
988 } else if (ch === '\r') { // a single return: invisible
989 escapedString += '\\r'; // write out as: \r"
990 } else if (ch === '\t') { // a single tab: invisible
991 escapedString += '\\t'; // write out as: \t"
992 } else {
993 escapedString += ch; // Else it need not be escaped
994 }
995 }
996 this.tstack.push('"' + escapedString + '"');
997 }
998 },
999
1000 /** Serializes a string */
1001 writeBinary: function(str) {
1002 this.writeString(str);
1003 },
1004
1005 /**
1006 @class
1007 @name AnonReadMessageBeginReturn
1008 @property {string} fname - The name of the service method.
1009 @property {Thrift.MessageType} mtype - The type of message call.
1010 @property {number} rseqid - The sequence number of the message (0 in Thrift RPC).
1011 */
1012 /**
1013 * Deserializes the beginning of a message.
1014 * @returns {AnonReadMessageBeginReturn}
1015 */
1016 readMessageBegin: function() {
1017 this.rstack = [];
1018 this.rpos = [];
1019
Roger Meier52744ee2014-03-12 09:38:42 +01001020 if (typeof JSON !== 'undefined' && typeof JSON.parse === 'function') {
1021 this.robj = JSON.parse(this.transport.readAll());
1022 } else if (typeof jQuery !== 'undefined') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001023 this.robj = jQuery.parseJSON(this.transport.readAll());
1024 } else {
1025 this.robj = eval(this.transport.readAll());
1026 }
1027
1028 var r = {};
1029 var version = this.robj.shift();
1030
1031 if (version != Thrift.Protocol.Version) {
1032 throw 'Wrong thrift protocol version: ' + version;
1033 }
1034
1035 r.fname = this.robj.shift();
1036 r.mtype = this.robj.shift();
1037 r.rseqid = this.robj.shift();
1038
1039
1040 //get to the main obj
1041 this.rstack.push(this.robj.shift());
1042
1043 return r;
1044 },
1045
1046 /** Deserializes the end of a message. */
1047 readMessageEnd: function() {
1048 },
1049
1050 /**
1051 * Deserializes the beginning of a struct.
1052 * @param {string} [name] - The name of the struct (ignored)
1053 * @returns {object} - An object with an empty string fname property
1054 */
1055 readStructBegin: function(name) {
1056 var r = {};
1057 r.fname = '';
1058
1059 //incase this is an array of structs
1060 if (this.rstack[this.rstack.length - 1] instanceof Array) {
1061 this.rstack.push(this.rstack[this.rstack.length - 1].shift());
1062 }
1063
1064 return r;
1065 },
1066
1067 /** Deserializes the end of a struct. */
1068 readStructEnd: function() {
1069 if (this.rstack[this.rstack.length - 2] instanceof Array) {
1070 this.rstack.pop();
1071 }
1072 },
1073
1074 /**
1075 @class
1076 @name AnonReadFieldBeginReturn
1077 @property {string} fname - The name of the field (always '').
1078 @property {Thrift.Type} ftype - The data type of the field.
1079 @property {number} fid - The unique identifier of the field.
1080 */
1081 /**
1082 * Deserializes the beginning of a field.
1083 * @returns {AnonReadFieldBeginReturn}
1084 */
1085 readFieldBegin: function() {
1086 var r = {};
1087
1088 var fid = -1;
1089 var ftype = Thrift.Type.STOP;
1090
1091 //get a fieldId
1092 for (var f in (this.rstack[this.rstack.length - 1])) {
1093 if (f === null) {
1094 continue;
1095 }
1096
1097 fid = parseInt(f, 10);
1098 this.rpos.push(this.rstack.length);
1099
1100 var field = this.rstack[this.rstack.length - 1][fid];
1101
1102 //remove so we don't see it again
1103 delete this.rstack[this.rstack.length - 1][fid];
1104
1105 this.rstack.push(field);
1106
1107 break;
1108 }
1109
1110 if (fid != -1) {
1111
1112 //should only be 1 of these but this is the only
1113 //way to match a key
1114 for (var i in (this.rstack[this.rstack.length - 1])) {
1115 if (Thrift.Protocol.RType[i] === null) {
1116 continue;
1117 }
1118
1119 ftype = Thrift.Protocol.RType[i];
1120 this.rstack[this.rstack.length - 1] =
1121 this.rstack[this.rstack.length - 1][i];
1122 }
1123 }
1124
1125 r.fname = '';
1126 r.ftype = ftype;
1127 r.fid = fid;
1128
1129 return r;
1130 },
1131
1132 /** Deserializes the end of a field. */
1133 readFieldEnd: function() {
1134 var pos = this.rpos.pop();
1135
1136 //get back to the right place in the stack
1137 while (this.rstack.length > pos) {
1138 this.rstack.pop();
1139 }
1140
1141 },
1142
1143 /**
1144 @class
1145 @name AnonReadMapBeginReturn
1146 @property {Thrift.Type} ktype - The data type of the key.
1147 @property {Thrift.Type} vtype - The data type of the value.
1148 @property {number} size - The number of elements in the map.
1149 */
1150 /**
1151 * Deserializes the beginning of a map.
1152 * @returns {AnonReadMapBeginReturn}
1153 */
1154 readMapBegin: function() {
1155 var map = this.rstack.pop();
Liangliang He5d6378f2014-08-19 18:25:37 +08001156 var first = map.shift();
1157 if (first instanceof Array) {
1158 this.rstack.push(map);
1159 map = first;
1160 first = map.shift();
1161 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001162
1163 var r = {};
Liangliang He5d6378f2014-08-19 18:25:37 +08001164 r.ktype = Thrift.Protocol.RType[first];
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001165 r.vtype = Thrift.Protocol.RType[map.shift()];
1166 r.size = map.shift();
1167
1168
1169 this.rpos.push(this.rstack.length);
1170 this.rstack.push(map.shift());
1171
1172 return r;
1173 },
1174
1175 /** Deserializes the end of a map. */
1176 readMapEnd: function() {
1177 this.readFieldEnd();
1178 },
1179
1180 /**
1181 @class
1182 @name AnonReadColBeginReturn
1183 @property {Thrift.Type} etype - The data type of the element.
1184 @property {number} size - The number of elements in the collection.
1185 */
1186 /**
1187 * Deserializes the beginning of a list.
1188 * @returns {AnonReadColBeginReturn}
1189 */
1190 readListBegin: function() {
1191 var list = this.rstack[this.rstack.length - 1];
1192
1193 var r = {};
1194 r.etype = Thrift.Protocol.RType[list.shift()];
1195 r.size = list.shift();
1196
1197 this.rpos.push(this.rstack.length);
1198 this.rstack.push(list);
1199
1200 return r;
1201 },
1202
1203 /** Deserializes the end of a list. */
1204 readListEnd: function() {
1205 this.readFieldEnd();
1206 },
1207
1208 /**
1209 * Deserializes the beginning of a set.
1210 * @returns {AnonReadColBeginReturn}
1211 */
1212 readSetBegin: function(elemType, size) {
1213 return this.readListBegin(elemType, size);
1214 },
1215
1216 /** Deserializes the end of a set. */
1217 readSetEnd: function() {
1218 return this.readListEnd();
1219 },
1220
1221 /** Returns an object with a value property set to
1222 * False unless the next number in the protocol buffer
1223 * is 1, in which case teh value property is True */
1224 readBool: function() {
1225 var r = this.readI32();
1226
1227 if (r !== null && r.value == '1') {
1228 r.value = true;
1229 } else {
1230 r.value = false;
1231 }
1232
1233 return r;
1234 },
1235
1236 /** Returns the an object with a value property set to the
1237 next value found in the protocol buffer */
1238 readByte: function() {
1239 return this.readI32();
1240 },
1241
1242 /** Returns the an object with a value property set to the
1243 next value found in the protocol buffer */
1244 readI16: function() {
1245 return this.readI32();
1246 },
1247
1248 /** Returns the an object with a value property set to the
1249 next value found in the protocol buffer */
1250 readI32: function(f) {
1251 if (f === undefined) {
1252 f = this.rstack[this.rstack.length - 1];
1253 }
1254
1255 var r = {};
1256
1257 if (f instanceof Array) {
1258 if (f.length === 0) {
1259 r.value = undefined;
1260 } else {
1261 r.value = f.shift();
1262 }
1263 } else if (f instanceof Object) {
1264 for (var i in f) {
1265 if (i === null) {
1266 continue;
1267 }
1268 this.rstack.push(f[i]);
1269 delete f[i];
1270
1271 r.value = i;
1272 break;
1273 }
1274 } else {
1275 r.value = f;
1276 this.rstack.pop();
1277 }
1278
1279 return r;
1280 },
1281
1282 /** Returns the an object with a value property set to the
1283 next value found in the protocol buffer */
1284 readI64: function() {
1285 return this.readI32();
1286 },
1287
1288 /** Returns the an object with a value property set to the
1289 next value found in the protocol buffer */
1290 readDouble: function() {
1291 return this.readI32();
1292 },
1293
1294 /** Returns the an object with a value property set to the
1295 next value found in the protocol buffer */
1296 readString: function() {
1297 var r = this.readI32();
1298 return r;
1299 },
1300
1301 /** Returns the an object with a value property set to the
1302 next value found in the protocol buffer */
1303 readBinary: function() {
1304 return this.readString();
1305 },
1306
1307 /**
Jens Geyer329d59a2014-06-19 22:11:53 +02001308 * Method to arbitrarily skip over data */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001309 skip: function(type) {
Jens Geyer329d59a2014-06-19 22:11:53 +02001310 var ret, i;
1311 switch (type) {
1312 case Thrift.Type.STOP:
1313 return null;
1314
1315 case Thrift.Type.BOOL:
1316 return this.readBool();
1317
1318 case Thrift.Type.BYTE:
1319 return this.readByte();
1320
1321 case Thrift.Type.I16:
1322 return this.readI16();
1323
1324 case Thrift.Type.I32:
1325 return this.readI32();
1326
1327 case Thrift.Type.I64:
1328 return this.readI64();
1329
1330 case Thrift.Type.DOUBLE:
1331 return this.readDouble();
1332
1333 case Thrift.Type.STRING:
1334 return this.readString();
1335
1336 case Thrift.Type.STRUCT:
1337 this.readStructBegin();
1338 while (true) {
1339 ret = this.readFieldBegin();
1340 if (ret.ftype == Thrift.Type.STOP) {
1341 break;
1342 }
1343 this.skip(ret.ftype);
1344 this.readFieldEnd();
1345 }
1346 this.readStructEnd();
1347 return null;
1348
1349 case Thrift.Type.MAP:
1350 ret = this.readMapBegin();
1351 for (i = 0; i < ret.size; i++) {
1352 if (i > 0) {
1353 if (this.rstack.length > this.rpos[this.rpos.length - 1] + 1) {
1354 this.rstack.pop();
1355 }
1356 }
1357 this.skip(ret.ktype);
1358 this.skip(ret.vtype);
1359 }
1360 this.readMapEnd();
1361 return null;
1362
1363 case Thrift.Type.SET:
1364 ret = this.readSetBegin();
1365 for (i = 0; i < ret.size; i++) {
1366 this.skip(ret.etype);
1367 }
1368 this.readSetEnd();
1369 return null;
1370
1371 case Thrift.Type.LIST:
1372 ret = this.readListBegin();
1373 for (i = 0; i < ret.size; i++) {
1374 this.skip(ret.etype);
1375 }
1376 this.readListEnd();
1377 return null;
1378 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001379 }
1380};
henrique5ba91f22013-12-20 21:13:13 +01001381
1382
1383/**
1384 * Initializes a MutilplexProtocol Implementation as a Wrapper for Thrift.Protocol
1385 * @constructor
1386 */
1387Thrift.MultiplexProtocol = function (srvName, trans, strictRead, strictWrite) {
1388 Thrift.Protocol.call(this, trans, strictRead, strictWrite);
1389 this.serviceName = srvName;
1390};
1391Thrift.inherits(Thrift.MultiplexProtocol, Thrift.Protocol, 'multiplexProtocol');
1392
1393/** Override writeMessageBegin method of prototype*/
1394Thrift.MultiplexProtocol.prototype.writeMessageBegin = function (name, type, seqid) {
1395
1396 if (type === Thrift.MessageType.CALL || type === Thrift.MessageType.ONEWAY) {
1397 Thrift.Protocol.prototype.writeMessageBegin.call(this, this.serviceName + ":" + name, type, seqid);
1398 } else {
1399 Thrift.Protocol.prototype.writeMessageBegin.call(this, name, type, seqid);
1400 }
1401};
1402
1403Thrift.Multiplexer = function () {
1404 this.seqid = 0;
1405};
1406
1407/** Instantiates a multiplexed client for a specific service
1408 * @constructor
1409 * @param {String} serviceName - The transport to serialize to/from.
1410 * @param {Thrift.ServiceClient} SCl - The Service Client Class
1411 * @param {Thrift.Transport} transport - Thrift.Transport instance which provides remote host:port
1412 * @example
1413 * var mp = new Thrift.Multiplexer();
1414 * var transport = new Thrift.Transport("http://localhost:9090/foo.thrift");
1415 * var protocol = new Thrift.Protocol(transport);
1416 * var client = mp.createClient('AuthService', AuthServiceClient, transport);
1417*/
1418Thrift.Multiplexer.prototype.createClient = function (serviceName, SCl, transport) {
1419 if (SCl.Client) {
1420 SCl = SCl.Client;
1421 }
1422 var self = this;
1423 SCl.prototype.new_seqid = function () {
1424 self.seqid += 1;
1425 return self.seqid;
1426 };
1427 var client = new SCl(new Thrift.MultiplexProtocol(serviceName, transport));
1428
1429 return client;
1430};
1431
henriquea2de4102014-02-07 14:12:56 +01001432
henrique2a7dccc2014-03-07 22:16:51 +01001433