blob: 9418ca37023c48c74cf8294efc2e8b4c701b7264 [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/**
Kazuki Matsudab909a382016-02-13 19:36:09 +090023 * The Thrift namespace houses the Apache Thrift JavaScript library
24 * elements providing JavaScript bindings for the Apache Thrift RPC
25 * system. End users will typically only directly make use of the
26 * Transport (TXHRTransport/TWebSocketTransport) and Protocol
henrique2a7dccc2014-03-07 22:16:51 +010027 * (TJSONPRotocol/TBinaryProtocol) constructors.
Kazuki Matsudab909a382016-02-13 19:36:09 +090028 *
29 * Object methods beginning with a __ (e.g. __onOpen()) are internal
henrique2a7dccc2014-03-07 22:16:51 +010030 * and should not be called outside of the object's own methods.
Kazuki Matsudab909a382016-02-13 19:36:09 +090031 *
henrique2a7dccc2014-03-07 22:16:51 +010032 * 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
Kazuki Matsudab909a382016-02-13 19:36:09 +090037 * var transport = new Thrift.Transport('http://localhost:8585');
Henrique Mendonça095ddb72013-09-20 19:38:03 +020038 * 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 */
jfarrell384647d2018-10-16 22:36:46 -040049 Version: '0.12.0',
Henrique Mendonça095ddb72013-09-20 19:38:03 +020050
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.
Kazuki Matsudab909a382016-02-13 19:36:09 +090058 * @property {number} I08 - Signed 8 bit integer.
Henrique Mendonça095ddb72013-09-20 19:38:03 +020059 * @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: {
Kazuki Matsudab909a382016-02-13 19:36:09 +090073 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
Henrique Mendonça095ddb72013-09-20 19:38:03 +020090 },
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: {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900101 CALL: 1,
102 REPLY: 2,
103 EXCEPTION: 3,
104 ONEWAY: 4
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200105 },
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();
Kazuki Matsudab909a382016-02-13 19:36:09 +0900133 constructor.prototype.name = name || '';
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200134 }
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 = {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900174 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
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200185};
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;
Kazuki Matsudab909a382016-02-13 19:36:09 +0900197 this.code = typeof code === 'number' ? code : 0;
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200198};
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
Liyin Tangf5399b22016-03-05 14:54:53 -0800275Thrift.TProtocolExceptionType = {
276 UNKNOWN: 0,
277 INVALID_DATA: 1,
278 NEGATIVE_SIZE: 2,
279 SIZE_LIMIT: 3,
280 BAD_VERSION: 4,
281 NOT_IMPLEMENTED: 5,
282 DEPTH_LIMIT: 6
283};
284
285Thrift.TProtocolException = function TProtocolException(type, message) {
286 Error.call(this);
287 Error.captureStackTrace(this, this.constructor);
288 this.name = this.constructor.name;
289 this.type = type;
290 this.message = message;
291};
292Thrift.inherits(Thrift.TProtocolException, Thrift.TException, 'TProtocolException');
293
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200294/**
henrique2a7dccc2014-03-07 22:16:51 +0100295 * Constructor Function for the XHR transport.
296 * If you do not specify a url then you must handle XHR operations on
297 * your own. This type can also be constructed using the Transport alias
298 * for backward compatibility.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200299 * @constructor
300 * @param {string} [url] - The URL to connect to.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900301 * @classdesc The Apache Thrift Transport layer performs byte level I/O
302 * between RPC clients and servers. The JavaScript TXHRTransport object
henrique2a7dccc2014-03-07 22:16:51 +0100303 * uses Http[s]/XHR. Target servers must implement the http[s] transport
304 * (see: node.js example server_http.js).
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200305 * @example
henrique2a7dccc2014-03-07 22:16:51 +0100306 * var transport = new Thrift.TXHRTransport("http://localhost:8585");
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200307 */
Roger Meier52744ee2014-03-12 09:38:42 +0100308Thrift.Transport = Thrift.TXHRTransport = function(url, options) {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200309 this.url = url;
310 this.wpos = 0;
311 this.rpos = 0;
Roger Meier52744ee2014-03-12 09:38:42 +0100312 this.useCORS = (options && options.useCORS);
Randy Abernethy3ca89e62016-04-13 06:24:57 -0700313 this.customHeaders = options ? (options.customHeaders ? options.customHeaders : {}): {};
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200314 this.send_buf = '';
315 this.recv_buf = '';
316};
317
henrique2a7dccc2014-03-07 22:16:51 +0100318Thrift.TXHRTransport.prototype = {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200319 /**
320 * Gets the browser specific XmlHttpRequest Object.
321 * @returns {object} the browser XHR interface object
322 */
323 getXmlHttpRequestObject: function() {
324 try { return new XMLHttpRequest(); } catch (e1) { }
325 try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e2) { }
326 try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e3) { }
327
328 throw "Your browser doesn't support XHR.";
329 },
330
331 /**
Kazuki Matsudab909a382016-02-13 19:36:09 +0900332 * Sends the current XRH request if the transport was created with a URL
henrique2a7dccc2014-03-07 22:16:51 +0100333 * and the async parameter is false. If the transport was not created with
Kazuki Matsudab909a382016-02-13 19:36:09 +0900334 * a URL, or the async parameter is True and no callback is provided, or
henrique2a7dccc2014-03-07 22:16:51 +0100335 * the URL is an empty string, the current send buffer is returned.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200336 * @param {object} async - If true the current send buffer is returned.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900337 * @param {object} callback - Optional async completion callback
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200338 * @returns {undefined|string} Nothing or the current send buffer.
339 * @throws {string} If XHR fails.
340 */
henriquea2de4102014-02-07 14:12:56 +0100341 flush: function(async, callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100342 var self = this;
henriquea2de4102014-02-07 14:12:56 +0100343 if ((async && !callback) || this.url === undefined || this.url === '') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200344 return this.send_buf;
345 }
346
347 var xreq = this.getXmlHttpRequestObject();
348
349 if (xreq.overrideMimeType) {
henriqueeec445e2015-05-04 21:37:51 +1000350 xreq.overrideMimeType('application/vnd.apache.thrift.json; charset=utf-8');
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200351 }
352
henriquea2de4102014-02-07 14:12:56 +0100353 if (callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100354 //Ignore XHR callbacks until the data arrives, then call the
355 // client's callback
Kazuki Matsudab909a382016-02-13 19:36:09 +0900356 xreq.onreadystatechange =
henrique2a7dccc2014-03-07 22:16:51 +0100357 (function() {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900358 var clientCallback = callback;
henrique2a7dccc2014-03-07 22:16:51 +0100359 return function() {
360 if (this.readyState == 4 && this.status == 200) {
361 self.setRecvBuffer(this.responseText);
362 clientCallback();
363 }
364 };
365 }());
HIRANO Satoshi84cf3632015-12-07 17:17:15 +0900366
367 // detect net::ERR_CONNECTION_REFUSED and call the callback.
368 xreq.onerror =
369 (function() {
370 var clientCallback = callback;
371 return function() {
372 clientCallback();
373 };
374 }());
375
henriquea2de4102014-02-07 14:12:56 +0100376 }
377
378 xreq.open('POST', this.url, !!async);
henriqueeec445e2015-05-04 21:37:51 +1000379
Randy Abernethy3ca89e62016-04-13 06:24:57 -0700380 // add custom headers
381 Object.keys(self.customHeaders).forEach(function(prop) {
382 xreq.setRequestHeader(prop, self.customHeaders[prop]);
383 });
384
henriqueeec445e2015-05-04 21:37:51 +1000385 if (xreq.setRequestHeader) {
386 xreq.setRequestHeader('Accept', 'application/vnd.apache.thrift.json; charset=utf-8');
387 xreq.setRequestHeader('Content-Type', 'application/vnd.apache.thrift.json; charset=utf-8');
388 }
389
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200390 xreq.send(this.send_buf);
henriquea2de4102014-02-07 14:12:56 +0100391 if (async && callback) {
392 return;
393 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200394
395 if (xreq.readyState != 4) {
396 throw 'encountered an unknown ajax ready state: ' + xreq.readyState;
397 }
398
399 if (xreq.status != 200) {
400 throw 'encountered a unknown request status: ' + xreq.status;
401 }
402
403 this.recv_buf = xreq.responseText;
404 this.recv_buf_sz = this.recv_buf.length;
405 this.wpos = this.recv_buf.length;
406 this.rpos = 0;
407 },
408
409 /**
410 * Creates a jQuery XHR object to be used for a Thrift server call.
411 * @param {object} client - The Thrift Service client object generated by the IDL compiler.
412 * @param {object} postData - The message to send to the server.
henrique2a7dccc2014-03-07 22:16:51 +0100413 * @param {function} args - The original call arguments with the success call back at the end.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200414 * @param {function} recv_method - The Thrift Service Client receive method for the call.
415 * @returns {object} A new jQuery XHR object.
416 * @throws {string} If the jQuery version is prior to 1.5 or if jQuery is not found.
417 */
418 jqRequest: function(client, postData, args, recv_method) {
419 if (typeof jQuery === 'undefined' ||
420 typeof jQuery.Deferred === 'undefined') {
421 throw 'Thrift.js requires jQuery 1.5+ to use asynchronous requests';
422 }
423
424 var thriftTransport = this;
425
426 var jqXHR = jQuery.ajax({
427 url: this.url,
428 data: postData,
429 type: 'POST',
430 cache: false,
henriqueeec445e2015-05-04 21:37:51 +1000431 contentType: 'application/vnd.apache.thrift.json; charset=utf-8',
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200432 dataType: 'text thrift',
433 converters: {
434 'text thrift' : function(responseData) {
435 thriftTransport.setRecvBuffer(responseData);
436 var value = recv_method.call(client);
437 return value;
438 }
439 },
440 context: client,
441 success: jQuery.makeArray(args).pop()
442 });
443
444 return jqXHR;
445 },
446
447 /**
henrique2a7dccc2014-03-07 22:16:51 +0100448 * Sets the buffer to provide the protocol when deserializing.
449 * @param {string} buf - The buffer to supply the protocol.
450 */
451 setRecvBuffer: function(buf) {
452 this.recv_buf = buf;
453 this.recv_buf_sz = this.recv_buf.length;
454 this.wpos = this.recv_buf.length;
455 this.rpos = 0;
456 },
457
458 /**
459 * Returns true if the transport is open, XHR always returns true.
460 * @readonly
461 * @returns {boolean} Always True.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900462 */
henrique2a7dccc2014-03-07 22:16:51 +0100463 isOpen: function() {
464 return true;
465 },
466
467 /**
468 * Opens the transport connection, with XHR this is a nop.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900469 */
henrique2a7dccc2014-03-07 22:16:51 +0100470 open: function() {},
471
472 /**
473 * Closes the transport connection, with XHR this is a nop.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900474 */
henrique2a7dccc2014-03-07 22:16:51 +0100475 close: function() {},
476
477 /**
478 * Returns the specified number of characters from the response
479 * buffer.
480 * @param {number} len - The number of characters to return.
481 * @returns {string} Characters sent by the server.
482 */
483 read: function(len) {
484 var avail = this.wpos - this.rpos;
485
486 if (avail === 0) {
487 return '';
488 }
489
490 var give = len;
491
492 if (avail < len) {
493 give = avail;
494 }
495
496 var ret = this.read_buf.substr(this.rpos, give);
497 this.rpos += give;
498
499 //clear buf when complete?
500 return ret;
501 },
502
503 /**
504 * Returns the entire response buffer.
505 * @returns {string} Characters sent by the server.
506 */
507 readAll: function() {
508 return this.recv_buf;
509 },
510
511 /**
512 * Sets the send buffer to buf.
513 * @param {string} buf - The buffer to send.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900514 */
henrique2a7dccc2014-03-07 22:16:51 +0100515 write: function(buf) {
516 this.send_buf = buf;
517 },
518
519 /**
520 * Returns the send buffer.
521 * @readonly
522 * @returns {string} The send buffer.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900523 */
henrique2a7dccc2014-03-07 22:16:51 +0100524 getSendBuffer: function() {
525 return this.send_buf;
526 }
527
528};
529
530
531/**
532 * Constructor Function for the WebSocket transport.
533 * @constructor
534 * @param {string} [url] - The URL to connect to.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900535 * @classdesc The Apache Thrift Transport layer performs byte level I/O
536 * between RPC clients and servers. The JavaScript TWebSocketTransport object
henrique2a7dccc2014-03-07 22:16:51 +0100537 * uses the WebSocket protocol. Target servers must implement WebSocket.
538 * (see: node.js example server_http.js).
539 * @example
540 * var transport = new Thrift.TWebSocketTransport("http://localhost:8585");
541 */
542Thrift.TWebSocketTransport = function(url) {
543 this.__reset(url);
544};
545
546Thrift.TWebSocketTransport.prototype = {
547 __reset: function(url) {
548 this.url = url; //Where to connect
549 this.socket = null; //The web socket
550 this.callbacks = []; //Pending callbacks
551 this.send_pending = []; //Buffers/Callback pairs waiting to be sent
552 this.send_buf = ''; //Outbound data, immutable until sent
553 this.recv_buf = ''; //Inbound data
554 this.rb_wpos = 0; //Network write position in receive buffer
555 this.rb_rpos = 0; //Client read position in receive buffer
556 },
557
558 /**
Kazuki Matsudab909a382016-02-13 19:36:09 +0900559 * Sends the current WS request and registers callback. The async
560 * parameter is ignored (WS flush is always async) and the callback
henrique2a7dccc2014-03-07 22:16:51 +0100561 * function parameter is required.
562 * @param {object} async - Ignored.
563 * @param {object} callback - The client completion callback.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900564 * @returns {undefined|string} Nothing (undefined)
henrique2a7dccc2014-03-07 22:16:51 +0100565 */
566 flush: function(async, callback) {
567 var self = this;
568 if (this.isOpen()) {
569 //Send data and register a callback to invoke the client callback
Kazuki Matsudab909a382016-02-13 19:36:09 +0900570 this.socket.send(this.send_buf);
henrique2a7dccc2014-03-07 22:16:51 +0100571 this.callbacks.push((function() {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900572 var clientCallback = callback;
henrique2a7dccc2014-03-07 22:16:51 +0100573 return function(msg) {
574 self.setRecvBuffer(msg);
Philip Frank0a84eae2017-12-27 12:54:28 +0100575 if (clientCallback) {
576 clientCallback();
577 }
henrique2a7dccc2014-03-07 22:16:51 +0100578 };
579 }()));
580 } else {
581 //Queue the send to go out __onOpen
582 this.send_pending.push({
583 buf: this.send_buf,
Kazuki Matsudab909a382016-02-13 19:36:09 +0900584 cb: callback
henrique2a7dccc2014-03-07 22:16:51 +0100585 });
586 }
587 },
588
Kazuki Matsudab909a382016-02-13 19:36:09 +0900589 __onOpen: function() {
henrique2a7dccc2014-03-07 22:16:51 +0100590 var self = this;
591 if (this.send_pending.length > 0) {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900592 //If the user made calls before the connection was fully
henrique2a7dccc2014-03-07 22:16:51 +0100593 //open, send them now
594 this.send_pending.forEach(function(elem) {
Philip Frank05a08ce2017-12-04 13:29:58 +0100595 self.socket.send(elem.buf);
596 self.callbacks.push((function() {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900597 var clientCallback = elem.cb;
henrique2a7dccc2014-03-07 22:16:51 +0100598 return function(msg) {
599 self.setRecvBuffer(msg);
600 clientCallback();
601 };
602 }()));
603 });
604 this.send_pending = [];
605 }
606 },
Kazuki Matsudab909a382016-02-13 19:36:09 +0900607
608 __onClose: function(evt) {
henrique2a7dccc2014-03-07 22:16:51 +0100609 this.__reset(this.url);
610 },
Kazuki Matsudab909a382016-02-13 19:36:09 +0900611
henrique2a7dccc2014-03-07 22:16:51 +0100612 __onMessage: function(evt) {
613 if (this.callbacks.length) {
614 this.callbacks.shift()(evt.data);
615 }
616 },
Kazuki Matsudab909a382016-02-13 19:36:09 +0900617
618 __onError: function(evt) {
619 console.log('Thrift WebSocket Error: ' + evt.toString());
henrique2a7dccc2014-03-07 22:16:51 +0100620 this.socket.close();
621 },
622
623 /**
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200624 * Sets the buffer to use when receiving server responses.
625 * @param {string} buf - The buffer to receive server responses.
626 */
627 setRecvBuffer: function(buf) {
628 this.recv_buf = buf;
629 this.recv_buf_sz = this.recv_buf.length;
630 this.wpos = this.recv_buf.length;
631 this.rpos = 0;
632 },
633
634 /**
henrique2a7dccc2014-03-07 22:16:51 +0100635 * Returns true if the transport is open
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200636 * @readonly
Kazuki Matsudab909a382016-02-13 19:36:09 +0900637 * @returns {boolean}
638 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200639 isOpen: function() {
henrique2a7dccc2014-03-07 22:16:51 +0100640 return this.socket && this.socket.readyState == this.socket.OPEN;
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200641 },
642
643 /**
henrique2a7dccc2014-03-07 22:16:51 +0100644 * Opens the transport connection
Kazuki Matsudab909a382016-02-13 19:36:09 +0900645 */
henrique2a7dccc2014-03-07 22:16:51 +0100646 open: function() {
647 //If OPEN/CONNECTING/CLOSING ignore additional opens
648 if (this.socket && this.socket.readyState != this.socket.CLOSED) {
649 return;
650 }
651 //If there is no socket or the socket is closed:
652 this.socket = new WebSocket(this.url);
Kazuki Matsudab909a382016-02-13 19:36:09 +0900653 this.socket.onopen = this.__onOpen.bind(this);
654 this.socket.onmessage = this.__onMessage.bind(this);
655 this.socket.onerror = this.__onError.bind(this);
656 this.socket.onclose = this.__onClose.bind(this);
henrique2a7dccc2014-03-07 22:16:51 +0100657 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200658
659 /**
henrique2a7dccc2014-03-07 22:16:51 +0100660 * Closes the transport connection
Kazuki Matsudab909a382016-02-13 19:36:09 +0900661 */
henrique2a7dccc2014-03-07 22:16:51 +0100662 close: function() {
663 this.socket.close();
664 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200665
666 /**
667 * Returns the specified number of characters from the response
668 * buffer.
669 * @param {number} len - The number of characters to return.
670 * @returns {string} Characters sent by the server.
671 */
672 read: function(len) {
673 var avail = this.wpos - this.rpos;
674
675 if (avail === 0) {
676 return '';
677 }
678
679 var give = len;
680
681 if (avail < len) {
682 give = avail;
683 }
684
685 var ret = this.read_buf.substr(this.rpos, give);
686 this.rpos += give;
687
688 //clear buf when complete?
689 return ret;
690 },
691
692 /**
693 * Returns the entire response buffer.
694 * @returns {string} Characters sent by the server.
695 */
696 readAll: function() {
697 return this.recv_buf;
698 },
699
700 /**
701 * Sets the send buffer to buf.
702 * @param {string} buf - The buffer to send.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900703 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200704 write: function(buf) {
705 this.send_buf = buf;
706 },
707
708 /**
709 * Returns the send buffer.
710 * @readonly
711 * @returns {string} The send buffer.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900712 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200713 getSendBuffer: function() {
714 return this.send_buf;
715 }
716
717};
718
719/**
720 * Initializes a Thrift JSON protocol instance.
721 * @constructor
722 * @param {Thrift.Transport} transport - The transport to serialize to/from.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900723 * @classdesc Apache Thrift Protocols perform serialization which enables cross
724 * language RPC. The Protocol type is the JavaScript browser implementation
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200725 * of the Apache Thrift TJSONProtocol.
726 * @example
727 * var protocol = new Thrift.Protocol(transport);
728 */
Roger Meier52744ee2014-03-12 09:38:42 +0100729Thrift.TJSONProtocol = Thrift.Protocol = function(transport) {
radekg1d305582015-01-01 20:35:01 +0100730 this.tstack = [];
731 this.tpos = [];
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200732 this.transport = transport;
733};
734
735/**
736 * Thrift IDL type Id to string mapping.
737 * @readonly
738 * @see {@link Thrift.Type}
739 */
740Thrift.Protocol.Type = {};
741Thrift.Protocol.Type[Thrift.Type.BOOL] = '"tf"';
742Thrift.Protocol.Type[Thrift.Type.BYTE] = '"i8"';
743Thrift.Protocol.Type[Thrift.Type.I16] = '"i16"';
744Thrift.Protocol.Type[Thrift.Type.I32] = '"i32"';
745Thrift.Protocol.Type[Thrift.Type.I64] = '"i64"';
746Thrift.Protocol.Type[Thrift.Type.DOUBLE] = '"dbl"';
747Thrift.Protocol.Type[Thrift.Type.STRUCT] = '"rec"';
748Thrift.Protocol.Type[Thrift.Type.STRING] = '"str"';
749Thrift.Protocol.Type[Thrift.Type.MAP] = '"map"';
750Thrift.Protocol.Type[Thrift.Type.LIST] = '"lst"';
751Thrift.Protocol.Type[Thrift.Type.SET] = '"set"';
752
753/**
754 * Thrift IDL type string to Id mapping.
755 * @readonly
756 * @see {@link Thrift.Type}
757 */
758Thrift.Protocol.RType = {};
759Thrift.Protocol.RType.tf = Thrift.Type.BOOL;
760Thrift.Protocol.RType.i8 = Thrift.Type.BYTE;
761Thrift.Protocol.RType.i16 = Thrift.Type.I16;
762Thrift.Protocol.RType.i32 = Thrift.Type.I32;
763Thrift.Protocol.RType.i64 = Thrift.Type.I64;
764Thrift.Protocol.RType.dbl = Thrift.Type.DOUBLE;
765Thrift.Protocol.RType.rec = Thrift.Type.STRUCT;
766Thrift.Protocol.RType.str = Thrift.Type.STRING;
767Thrift.Protocol.RType.map = Thrift.Type.MAP;
768Thrift.Protocol.RType.lst = Thrift.Type.LIST;
769Thrift.Protocol.RType.set = Thrift.Type.SET;
770
771/**
772 * The TJSONProtocol version number.
773 * @readonly
774 * @const {number} Version
775 * @memberof Thrift.Protocol
776 */
777 Thrift.Protocol.Version = 1;
778
779Thrift.Protocol.prototype = {
780 /**
781 * Returns the underlying transport.
782 * @readonly
783 * @returns {Thrift.Transport} The underlying transport.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900784 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200785 getTransport: function() {
786 return this.transport;
787 },
788
789 /**
790 * Serializes the beginning of a Thrift RPC message.
791 * @param {string} name - The service method to call.
792 * @param {Thrift.MessageType} messageType - The type of method call.
793 * @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift).
794 */
795 writeMessageBegin: function(name, messageType, seqid) {
796 this.tstack = [];
797 this.tpos = [];
798
799 this.tstack.push([Thrift.Protocol.Version, '"' +
800 name + '"', messageType, seqid]);
801 },
802
803 /**
804 * Serializes the end of a Thrift RPC message.
805 */
806 writeMessageEnd: function() {
807 var obj = this.tstack.pop();
808
809 this.wobj = this.tstack.pop();
810 this.wobj.push(obj);
811
812 this.wbuf = '[' + this.wobj.join(',') + ']';
813
814 this.transport.write(this.wbuf);
815 },
816
817
818 /**
819 * Serializes the beginning of a struct.
820 * @param {string} name - The name of the struct.
821 */
822 writeStructBegin: function(name) {
823 this.tpos.push(this.tstack.length);
824 this.tstack.push({});
825 },
826
827 /**
828 * Serializes the end of a struct.
829 */
830 writeStructEnd: function() {
831
832 var p = this.tpos.pop();
833 var struct = this.tstack[p];
834 var str = '{';
835 var first = true;
836 for (var key in struct) {
837 if (first) {
838 first = false;
839 } else {
840 str += ',';
841 }
842
843 str += key + ':' + struct[key];
844 }
845
846 str += '}';
847 this.tstack[p] = str;
848 },
849
850 /**
851 * Serializes the beginning of a struct field.
852 * @param {string} name - The name of the field.
853 * @param {Thrift.Protocol.Type} fieldType - The data type of the field.
854 * @param {number} fieldId - The field's unique identifier.
855 */
856 writeFieldBegin: function(name, fieldType, fieldId) {
857 this.tpos.push(this.tstack.length);
858 this.tstack.push({ 'fieldId': '"' +
859 fieldId + '"', 'fieldType': Thrift.Protocol.Type[fieldType]
860 });
861
862 },
863
864 /**
865 * Serializes the end of a field.
866 */
867 writeFieldEnd: function() {
868 var value = this.tstack.pop();
869 var fieldInfo = this.tstack.pop();
870
871 this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' +
872 fieldInfo.fieldType + ':' + value + '}';
873 this.tpos.pop();
874 },
875
876 /**
877 * Serializes the end of the set of fields for a struct.
878 */
879 writeFieldStop: function() {
880 //na
881 },
882
883 /**
884 * Serializes the beginning of a map collection.
885 * @param {Thrift.Type} keyType - The data type of the key.
886 * @param {Thrift.Type} valType - The data type of the value.
887 * @param {number} [size] - The number of elements in the map (ignored).
888 */
889 writeMapBegin: function(keyType, valType, size) {
890 this.tpos.push(this.tstack.length);
891 this.tstack.push([Thrift.Protocol.Type[keyType],
892 Thrift.Protocol.Type[valType], 0]);
893 },
894
895 /**
896 * Serializes the end of a map.
897 */
898 writeMapEnd: function() {
899 var p = this.tpos.pop();
900
901 if (p == this.tstack.length) {
902 return;
903 }
904
905 if ((this.tstack.length - p - 1) % 2 !== 0) {
906 this.tstack.push('');
907 }
908
909 var size = (this.tstack.length - p - 1) / 2;
910
911 this.tstack[p][this.tstack[p].length - 1] = size;
912
913 var map = '}';
914 var first = true;
915 while (this.tstack.length > p + 1) {
916 var v = this.tstack.pop();
917 var k = this.tstack.pop();
918 if (first) {
919 first = false;
920 } else {
921 map = ',' + map;
922 }
923
924 if (! isNaN(k)) { k = '"' + k + '"'; } //json "keys" need to be strings
925 map = k + ':' + v + map;
926 }
927 map = '{' + map;
928
929 this.tstack[p].push(map);
930 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
931 },
932
933 /**
934 * Serializes the beginning of a list collection.
935 * @param {Thrift.Type} elemType - The data type of the elements.
936 * @param {number} size - The number of elements in the list.
937 */
938 writeListBegin: function(elemType, size) {
939 this.tpos.push(this.tstack.length);
940 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
941 },
942
943 /**
944 * Serializes the end of a list.
945 */
946 writeListEnd: function() {
947 var p = this.tpos.pop();
948
949 while (this.tstack.length > p + 1) {
950 var tmpVal = this.tstack[p + 1];
951 this.tstack.splice(p + 1, 1);
952 this.tstack[p].push(tmpVal);
953 }
954
955 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
956 },
957
958 /**
959 * Serializes the beginning of a set collection.
960 * @param {Thrift.Type} elemType - The data type of the elements.
961 * @param {number} size - The number of elements in the list.
962 */
963 writeSetBegin: function(elemType, size) {
964 this.tpos.push(this.tstack.length);
965 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
966 },
967
968 /**
969 * Serializes the end of a set.
970 */
971 writeSetEnd: function() {
972 var p = this.tpos.pop();
973
974 while (this.tstack.length > p + 1) {
975 var tmpVal = this.tstack[p + 1];
976 this.tstack.splice(p + 1, 1);
977 this.tstack[p].push(tmpVal);
978 }
979
980 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
981 },
982
983 /** Serializes a boolean */
984 writeBool: function(value) {
985 this.tstack.push(value ? 1 : 0);
986 },
987
988 /** Serializes a number */
989 writeByte: function(i8) {
990 this.tstack.push(i8);
991 },
992
993 /** Serializes a number */
994 writeI16: function(i16) {
995 this.tstack.push(i16);
996 },
997
998 /** Serializes a number */
999 writeI32: function(i32) {
1000 this.tstack.push(i32);
1001 },
1002
1003 /** Serializes a number */
1004 writeI64: function(i64) {
1005 this.tstack.push(i64);
1006 },
1007
1008 /** Serializes a number */
1009 writeDouble: function(dbl) {
1010 this.tstack.push(dbl);
1011 },
1012
1013 /** Serializes a string */
1014 writeString: function(str) {
1015 // We do not encode uri components for wire transfer:
1016 if (str === null) {
1017 this.tstack.push(null);
1018 } else {
1019 // concat may be slower than building a byte buffer
1020 var escapedString = '';
1021 for (var i = 0; i < str.length; i++) {
1022 var ch = str.charAt(i); // a single double quote: "
1023 if (ch === '\"') {
1024 escapedString += '\\\"'; // write out as: \"
Roger Meier52744ee2014-03-12 09:38:42 +01001025 } else if (ch === '\\') { // a single backslash
Kazuki Matsudab909a382016-02-13 19:36:09 +09001026 escapedString += '\\\\'; // write out as double backslash
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001027 } else if (ch === '\b') { // a single backspace: invisible
1028 escapedString += '\\b'; // write out as: \b"
1029 } else if (ch === '\f') { // a single formfeed: invisible
1030 escapedString += '\\f'; // write out as: \f"
1031 } else if (ch === '\n') { // a single newline: invisible
1032 escapedString += '\\n'; // write out as: \n"
1033 } else if (ch === '\r') { // a single return: invisible
1034 escapedString += '\\r'; // write out as: \r"
1035 } else if (ch === '\t') { // a single tab: invisible
1036 escapedString += '\\t'; // write out as: \t"
1037 } else {
1038 escapedString += ch; // Else it need not be escaped
1039 }
1040 }
1041 this.tstack.push('"' + escapedString + '"');
1042 }
1043 },
1044
1045 /** Serializes a string */
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001046 writeBinary: function(binary) {
1047 var str = '';
1048 if (typeof binary == 'string') {
1049 str = binary;
1050 } else if (binary instanceof Uint8Array) {
1051 var arr = binary;
1052 for (var i = 0; i < arr.length; ++i) {
1053 str += String.fromCharCode(arr[i]);
1054 }
1055 } else {
1056 throw new TypeError('writeBinary only accepts String or Uint8Array.');
1057 }
1058 this.tstack.push('"' + btoa(str) + '"');
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001059 },
1060
1061 /**
1062 @class
1063 @name AnonReadMessageBeginReturn
1064 @property {string} fname - The name of the service method.
1065 @property {Thrift.MessageType} mtype - The type of message call.
1066 @property {number} rseqid - The sequence number of the message (0 in Thrift RPC).
1067 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001068 /**
1069 * Deserializes the beginning of a message.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001070 * @returns {AnonReadMessageBeginReturn}
1071 */
1072 readMessageBegin: function() {
1073 this.rstack = [];
1074 this.rpos = [];
1075
Roger Meier52744ee2014-03-12 09:38:42 +01001076 if (typeof JSON !== 'undefined' && typeof JSON.parse === 'function') {
1077 this.robj = JSON.parse(this.transport.readAll());
1078 } else if (typeof jQuery !== 'undefined') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001079 this.robj = jQuery.parseJSON(this.transport.readAll());
1080 } else {
1081 this.robj = eval(this.transport.readAll());
1082 }
1083
1084 var r = {};
1085 var version = this.robj.shift();
1086
1087 if (version != Thrift.Protocol.Version) {
1088 throw 'Wrong thrift protocol version: ' + version;
1089 }
1090
1091 r.fname = this.robj.shift();
1092 r.mtype = this.robj.shift();
1093 r.rseqid = this.robj.shift();
1094
1095
1096 //get to the main obj
1097 this.rstack.push(this.robj.shift());
1098
1099 return r;
1100 },
1101
1102 /** Deserializes the end of a message. */
1103 readMessageEnd: function() {
1104 },
1105
Kazuki Matsudab909a382016-02-13 19:36:09 +09001106 /**
1107 * Deserializes the beginning of a struct.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001108 * @param {string} [name] - The name of the struct (ignored)
1109 * @returns {object} - An object with an empty string fname property
Kazuki Matsudab909a382016-02-13 19:36:09 +09001110 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001111 readStructBegin: function(name) {
1112 var r = {};
1113 r.fname = '';
1114
1115 //incase this is an array of structs
1116 if (this.rstack[this.rstack.length - 1] instanceof Array) {
1117 this.rstack.push(this.rstack[this.rstack.length - 1].shift());
1118 }
1119
1120 return r;
1121 },
1122
1123 /** Deserializes the end of a struct. */
1124 readStructEnd: function() {
1125 if (this.rstack[this.rstack.length - 2] instanceof Array) {
1126 this.rstack.pop();
1127 }
1128 },
1129
1130 /**
1131 @class
1132 @name AnonReadFieldBeginReturn
1133 @property {string} fname - The name of the field (always '').
1134 @property {Thrift.Type} ftype - The data type of the field.
1135 @property {number} fid - The unique identifier of the field.
1136 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001137 /**
1138 * Deserializes the beginning of a field.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001139 * @returns {AnonReadFieldBeginReturn}
1140 */
1141 readFieldBegin: function() {
1142 var r = {};
1143
1144 var fid = -1;
1145 var ftype = Thrift.Type.STOP;
1146
1147 //get a fieldId
1148 for (var f in (this.rstack[this.rstack.length - 1])) {
1149 if (f === null) {
1150 continue;
1151 }
1152
1153 fid = parseInt(f, 10);
1154 this.rpos.push(this.rstack.length);
1155
1156 var field = this.rstack[this.rstack.length - 1][fid];
1157
1158 //remove so we don't see it again
1159 delete this.rstack[this.rstack.length - 1][fid];
1160
1161 this.rstack.push(field);
1162
1163 break;
1164 }
1165
1166 if (fid != -1) {
1167
1168 //should only be 1 of these but this is the only
1169 //way to match a key
1170 for (var i in (this.rstack[this.rstack.length - 1])) {
1171 if (Thrift.Protocol.RType[i] === null) {
1172 continue;
1173 }
1174
1175 ftype = Thrift.Protocol.RType[i];
1176 this.rstack[this.rstack.length - 1] =
1177 this.rstack[this.rstack.length - 1][i];
1178 }
1179 }
1180
1181 r.fname = '';
1182 r.ftype = ftype;
1183 r.fid = fid;
1184
1185 return r;
1186 },
1187
1188 /** Deserializes the end of a field. */
1189 readFieldEnd: function() {
1190 var pos = this.rpos.pop();
1191
1192 //get back to the right place in the stack
1193 while (this.rstack.length > pos) {
1194 this.rstack.pop();
1195 }
1196
1197 },
1198
1199 /**
1200 @class
1201 @name AnonReadMapBeginReturn
1202 @property {Thrift.Type} ktype - The data type of the key.
1203 @property {Thrift.Type} vtype - The data type of the value.
1204 @property {number} size - The number of elements in the map.
1205 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001206 /**
1207 * Deserializes the beginning of a map.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001208 * @returns {AnonReadMapBeginReturn}
1209 */
1210 readMapBegin: function() {
1211 var map = this.rstack.pop();
Liangliang He5d6378f2014-08-19 18:25:37 +08001212 var first = map.shift();
1213 if (first instanceof Array) {
1214 this.rstack.push(map);
1215 map = first;
1216 first = map.shift();
1217 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001218
1219 var r = {};
Liangliang He5d6378f2014-08-19 18:25:37 +08001220 r.ktype = Thrift.Protocol.RType[first];
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001221 r.vtype = Thrift.Protocol.RType[map.shift()];
1222 r.size = map.shift();
1223
1224
1225 this.rpos.push(this.rstack.length);
1226 this.rstack.push(map.shift());
1227
1228 return r;
1229 },
1230
1231 /** Deserializes the end of a map. */
1232 readMapEnd: function() {
1233 this.readFieldEnd();
1234 },
1235
1236 /**
1237 @class
1238 @name AnonReadColBeginReturn
1239 @property {Thrift.Type} etype - The data type of the element.
1240 @property {number} size - The number of elements in the collection.
1241 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001242 /**
1243 * Deserializes the beginning of a list.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001244 * @returns {AnonReadColBeginReturn}
1245 */
1246 readListBegin: function() {
1247 var list = this.rstack[this.rstack.length - 1];
1248
1249 var r = {};
1250 r.etype = Thrift.Protocol.RType[list.shift()];
1251 r.size = list.shift();
1252
1253 this.rpos.push(this.rstack.length);
Henrique Mendonça15d90422015-06-25 22:31:41 +10001254 this.rstack.push(list.shift());
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001255
1256 return r;
1257 },
1258
1259 /** Deserializes the end of a list. */
1260 readListEnd: function() {
Philip Frank55ddf192018-01-02 09:00:36 +01001261 var pos = this.rpos.pop() - 2;
1262 var st = this.rstack;
1263 st.pop();
1264 if (st instanceof Array && st.length > pos && st[pos].length > 0) {
1265 st.push(st[pos].shift());
1266 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001267 },
1268
Kazuki Matsudab909a382016-02-13 19:36:09 +09001269 /**
1270 * Deserializes the beginning of a set.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001271 * @returns {AnonReadColBeginReturn}
1272 */
1273 readSetBegin: function(elemType, size) {
1274 return this.readListBegin(elemType, size);
1275 },
1276
1277 /** Deserializes the end of a set. */
1278 readSetEnd: function() {
1279 return this.readListEnd();
1280 },
1281
Kazuki Matsudab909a382016-02-13 19:36:09 +09001282 /** Returns an object with a value property set to
1283 * False unless the next number in the protocol buffer
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +01001284 * is 1, in which case the value property is True */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001285 readBool: function() {
1286 var r = this.readI32();
1287
1288 if (r !== null && r.value == '1') {
1289 r.value = true;
1290 } else {
1291 r.value = false;
1292 }
1293
1294 return r;
1295 },
1296
Kazuki Matsudab909a382016-02-13 19:36:09 +09001297 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001298 next value found in the protocol buffer */
1299 readByte: function() {
1300 return this.readI32();
1301 },
1302
Kazuki Matsudab909a382016-02-13 19:36:09 +09001303 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001304 next value found in the protocol buffer */
1305 readI16: function() {
1306 return this.readI32();
1307 },
1308
Kazuki Matsudab909a382016-02-13 19:36:09 +09001309 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001310 next value found in the protocol buffer */
1311 readI32: function(f) {
1312 if (f === undefined) {
1313 f = this.rstack[this.rstack.length - 1];
1314 }
1315
1316 var r = {};
1317
1318 if (f instanceof Array) {
1319 if (f.length === 0) {
1320 r.value = undefined;
1321 } else {
Drew Ritterc0a5eed2018-06-27 10:28:00 -07001322 if (!f.isReversed) {
1323 f.reverse();
1324 f.isReversed = true;
1325 }
1326 r.value = f.pop();
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001327 }
1328 } else if (f instanceof Object) {
1329 for (var i in f) {
1330 if (i === null) {
1331 continue;
1332 }
1333 this.rstack.push(f[i]);
1334 delete f[i];
1335
1336 r.value = i;
1337 break;
1338 }
1339 } else {
1340 r.value = f;
1341 this.rstack.pop();
1342 }
1343
1344 return r;
1345 },
1346
Kazuki Matsudab909a382016-02-13 19:36:09 +09001347 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001348 next value found in the protocol buffer */
1349 readI64: function() {
1350 return this.readI32();
1351 },
1352
Kazuki Matsudab909a382016-02-13 19:36:09 +09001353 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001354 next value found in the protocol buffer */
1355 readDouble: function() {
1356 return this.readI32();
1357 },
1358
Kazuki Matsudab909a382016-02-13 19:36:09 +09001359 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001360 next value found in the protocol buffer */
1361 readString: function() {
1362 var r = this.readI32();
1363 return r;
1364 },
1365
Kazuki Matsudab909a382016-02-13 19:36:09 +09001366 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001367 next value found in the protocol buffer */
1368 readBinary: function() {
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001369 var r = this.readI32();
1370 r.value = atob(r.value);
1371 return r;
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001372 },
1373
Kazuki Matsudab909a382016-02-13 19:36:09 +09001374 /**
Jens Geyer329d59a2014-06-19 22:11:53 +02001375 * Method to arbitrarily skip over data */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001376 skip: function(type) {
Jens Geyer329d59a2014-06-19 22:11:53 +02001377 var ret, i;
1378 switch (type) {
1379 case Thrift.Type.STOP:
1380 return null;
1381
1382 case Thrift.Type.BOOL:
1383 return this.readBool();
1384
1385 case Thrift.Type.BYTE:
1386 return this.readByte();
1387
1388 case Thrift.Type.I16:
1389 return this.readI16();
1390
1391 case Thrift.Type.I32:
1392 return this.readI32();
1393
1394 case Thrift.Type.I64:
1395 return this.readI64();
1396
1397 case Thrift.Type.DOUBLE:
1398 return this.readDouble();
1399
1400 case Thrift.Type.STRING:
1401 return this.readString();
1402
1403 case Thrift.Type.STRUCT:
1404 this.readStructBegin();
1405 while (true) {
1406 ret = this.readFieldBegin();
1407 if (ret.ftype == Thrift.Type.STOP) {
1408 break;
1409 }
1410 this.skip(ret.ftype);
1411 this.readFieldEnd();
1412 }
1413 this.readStructEnd();
1414 return null;
1415
1416 case Thrift.Type.MAP:
1417 ret = this.readMapBegin();
1418 for (i = 0; i < ret.size; i++) {
1419 if (i > 0) {
1420 if (this.rstack.length > this.rpos[this.rpos.length - 1] + 1) {
1421 this.rstack.pop();
1422 }
1423 }
1424 this.skip(ret.ktype);
1425 this.skip(ret.vtype);
1426 }
1427 this.readMapEnd();
1428 return null;
1429
1430 case Thrift.Type.SET:
1431 ret = this.readSetBegin();
1432 for (i = 0; i < ret.size; i++) {
1433 this.skip(ret.etype);
1434 }
1435 this.readSetEnd();
1436 return null;
1437
1438 case Thrift.Type.LIST:
1439 ret = this.readListBegin();
1440 for (i = 0; i < ret.size; i++) {
1441 this.skip(ret.etype);
1442 }
1443 this.readListEnd();
1444 return null;
Philip Frank50862912018-03-07 21:21:30 +01001445
1446 default:
1447 throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA);
Jens Geyer329d59a2014-06-19 22:11:53 +02001448 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001449 }
1450};
henrique5ba91f22013-12-20 21:13:13 +01001451
1452
1453/**
1454 * Initializes a MutilplexProtocol Implementation as a Wrapper for Thrift.Protocol
1455 * @constructor
1456 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001457Thrift.MultiplexProtocol = function(srvName, trans, strictRead, strictWrite) {
henrique5ba91f22013-12-20 21:13:13 +01001458 Thrift.Protocol.call(this, trans, strictRead, strictWrite);
1459 this.serviceName = srvName;
1460};
1461Thrift.inherits(Thrift.MultiplexProtocol, Thrift.Protocol, 'multiplexProtocol');
1462
1463/** Override writeMessageBegin method of prototype*/
Kazuki Matsudab909a382016-02-13 19:36:09 +09001464Thrift.MultiplexProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
henrique5ba91f22013-12-20 21:13:13 +01001465
1466 if (type === Thrift.MessageType.CALL || type === Thrift.MessageType.ONEWAY) {
Kazuki Matsudab909a382016-02-13 19:36:09 +09001467 Thrift.Protocol.prototype.writeMessageBegin.call(this, this.serviceName + ':' + name, type, seqid);
henrique5ba91f22013-12-20 21:13:13 +01001468 } else {
1469 Thrift.Protocol.prototype.writeMessageBegin.call(this, name, type, seqid);
1470 }
1471};
1472
Kazuki Matsudab909a382016-02-13 19:36:09 +09001473Thrift.Multiplexer = function() {
henrique5ba91f22013-12-20 21:13:13 +01001474 this.seqid = 0;
1475};
1476
1477/** Instantiates a multiplexed client for a specific service
1478 * @constructor
1479 * @param {String} serviceName - The transport to serialize to/from.
1480 * @param {Thrift.ServiceClient} SCl - The Service Client Class
1481 * @param {Thrift.Transport} transport - Thrift.Transport instance which provides remote host:port
1482 * @example
1483 * var mp = new Thrift.Multiplexer();
1484 * var transport = new Thrift.Transport("http://localhost:9090/foo.thrift");
1485 * var protocol = new Thrift.Protocol(transport);
1486 * var client = mp.createClient('AuthService', AuthServiceClient, transport);
1487*/
Kazuki Matsudab909a382016-02-13 19:36:09 +09001488Thrift.Multiplexer.prototype.createClient = function(serviceName, SCl, transport) {
henrique5ba91f22013-12-20 21:13:13 +01001489 if (SCl.Client) {
1490 SCl = SCl.Client;
1491 }
1492 var self = this;
Kazuki Matsudab909a382016-02-13 19:36:09 +09001493 SCl.prototype.new_seqid = function() {
henrique5ba91f22013-12-20 21:13:13 +01001494 self.seqid += 1;
1495 return self.seqid;
1496 };
1497 var client = new SCl(new Thrift.MultiplexProtocol(serviceName, transport));
1498
1499 return client;
1500};
1501
henriquea2de4102014-02-07 14:12:56 +01001502
henrique2a7dccc2014-03-07 22:16:51 +01001503
Henrique Mendonça15d90422015-06-25 22:31:41 +10001504var copyList, copyMap;
1505
1506copyList = function(lst, types) {
1507
1508 if (!lst) {return lst; }
1509
1510 var type;
1511
1512 if (types.shift === undefined) {
1513 type = types;
1514 }
1515 else {
1516 type = types[0];
1517 }
1518 var Type = type;
1519
1520 var len = lst.length, result = [], i, val;
1521 for (i = 0; i < len; i++) {
1522 val = lst[i];
1523 if (type === null) {
1524 result.push(val);
1525 }
1526 else if (type === copyMap || type === copyList) {
1527 result.push(type(val, types.slice(1)));
1528 }
1529 else {
1530 result.push(new Type(val));
1531 }
1532 }
1533 return result;
1534};
1535
Kazuki Matsudab909a382016-02-13 19:36:09 +09001536copyMap = function(obj, types) {
Henrique Mendonça15d90422015-06-25 22:31:41 +10001537
1538 if (!obj) {return obj; }
1539
1540 var type;
1541
1542 if (types.shift === undefined) {
1543 type = types;
1544 }
1545 else {
1546 type = types[0];
1547 }
1548 var Type = type;
1549
1550 var result = {}, val;
Kazuki Matsudab909a382016-02-13 19:36:09 +09001551 for (var prop in obj) {
1552 if (obj.hasOwnProperty(prop)) {
Henrique Mendonça15d90422015-06-25 22:31:41 +10001553 val = obj[prop];
1554 if (type === null) {
1555 result[prop] = val;
1556 }
1557 else if (type === copyMap || type === copyList) {
1558 result[prop] = type(val, types.slice(1));
1559 }
1560 else {
1561 result[prop] = new Type(val);
1562 }
1563 }
1564 }
1565 return result;
1566};
1567
1568Thrift.copyMap = copyMap;
1569Thrift.copyList = copyList;