blob: 69bcccdd23fa653427c70181fec966c8ccaac608 [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 */
Jens Geyere02559f2019-10-17 00:11:59 +020049 Version: '0.14.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,
Christian Bürckertf61d9e52019-01-14 14:36:22 +0100441 success: jQuery.makeArray(args).pop(),
442 beforeSend: function (xreq) {
443 Object.keys(thriftTransport.customHeaders).forEach(function (prop) {
444 xreq.setRequestHeader(prop, thriftTransport.customHeaders[prop]);
445 });
446 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200447 });
448
449 return jqXHR;
450 },
451
452 /**
henrique2a7dccc2014-03-07 22:16:51 +0100453 * Sets the buffer to provide the protocol when deserializing.
454 * @param {string} buf - The buffer to supply the protocol.
455 */
456 setRecvBuffer: function(buf) {
457 this.recv_buf = buf;
458 this.recv_buf_sz = this.recv_buf.length;
459 this.wpos = this.recv_buf.length;
460 this.rpos = 0;
461 },
462
463 /**
464 * Returns true if the transport is open, XHR always returns true.
465 * @readonly
466 * @returns {boolean} Always True.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900467 */
henrique2a7dccc2014-03-07 22:16:51 +0100468 isOpen: function() {
469 return true;
470 },
471
472 /**
473 * Opens the transport connection, with XHR this is a nop.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900474 */
henrique2a7dccc2014-03-07 22:16:51 +0100475 open: function() {},
476
477 /**
478 * Closes the transport connection, with XHR this is a nop.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900479 */
henrique2a7dccc2014-03-07 22:16:51 +0100480 close: function() {},
481
482 /**
483 * Returns the specified number of characters from the response
484 * buffer.
485 * @param {number} len - The number of characters to return.
486 * @returns {string} Characters sent by the server.
487 */
488 read: function(len) {
489 var avail = this.wpos - this.rpos;
490
491 if (avail === 0) {
492 return '';
493 }
494
495 var give = len;
496
497 if (avail < len) {
498 give = avail;
499 }
500
501 var ret = this.read_buf.substr(this.rpos, give);
502 this.rpos += give;
503
504 //clear buf when complete?
505 return ret;
506 },
507
508 /**
509 * Returns the entire response buffer.
510 * @returns {string} Characters sent by the server.
511 */
512 readAll: function() {
513 return this.recv_buf;
514 },
515
516 /**
517 * Sets the send buffer to buf.
518 * @param {string} buf - The buffer to send.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900519 */
henrique2a7dccc2014-03-07 22:16:51 +0100520 write: function(buf) {
521 this.send_buf = buf;
522 },
523
524 /**
525 * Returns the send buffer.
526 * @readonly
527 * @returns {string} The send buffer.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900528 */
henrique2a7dccc2014-03-07 22:16:51 +0100529 getSendBuffer: function() {
530 return this.send_buf;
531 }
532
533};
534
535
536/**
537 * Constructor Function for the WebSocket transport.
538 * @constructor
539 * @param {string} [url] - The URL to connect to.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900540 * @classdesc The Apache Thrift Transport layer performs byte level I/O
541 * between RPC clients and servers. The JavaScript TWebSocketTransport object
henrique2a7dccc2014-03-07 22:16:51 +0100542 * uses the WebSocket protocol. Target servers must implement WebSocket.
543 * (see: node.js example server_http.js).
544 * @example
545 * var transport = new Thrift.TWebSocketTransport("http://localhost:8585");
546 */
547Thrift.TWebSocketTransport = function(url) {
548 this.__reset(url);
549};
550
551Thrift.TWebSocketTransport.prototype = {
552 __reset: function(url) {
553 this.url = url; //Where to connect
554 this.socket = null; //The web socket
555 this.callbacks = []; //Pending callbacks
556 this.send_pending = []; //Buffers/Callback pairs waiting to be sent
557 this.send_buf = ''; //Outbound data, immutable until sent
558 this.recv_buf = ''; //Inbound data
559 this.rb_wpos = 0; //Network write position in receive buffer
560 this.rb_rpos = 0; //Client read position in receive buffer
561 },
562
563 /**
Kazuki Matsudab909a382016-02-13 19:36:09 +0900564 * Sends the current WS request and registers callback. The async
565 * parameter is ignored (WS flush is always async) and the callback
henrique2a7dccc2014-03-07 22:16:51 +0100566 * function parameter is required.
567 * @param {object} async - Ignored.
568 * @param {object} callback - The client completion callback.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900569 * @returns {undefined|string} Nothing (undefined)
henrique2a7dccc2014-03-07 22:16:51 +0100570 */
571 flush: function(async, callback) {
572 var self = this;
573 if (this.isOpen()) {
574 //Send data and register a callback to invoke the client callback
Kazuki Matsudab909a382016-02-13 19:36:09 +0900575 this.socket.send(this.send_buf);
henrique2a7dccc2014-03-07 22:16:51 +0100576 this.callbacks.push((function() {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900577 var clientCallback = callback;
henrique2a7dccc2014-03-07 22:16:51 +0100578 return function(msg) {
579 self.setRecvBuffer(msg);
Philip Frank0a84eae2017-12-27 12:54:28 +0100580 if (clientCallback) {
581 clientCallback();
582 }
henrique2a7dccc2014-03-07 22:16:51 +0100583 };
584 }()));
585 } else {
586 //Queue the send to go out __onOpen
587 this.send_pending.push({
588 buf: this.send_buf,
Kazuki Matsudab909a382016-02-13 19:36:09 +0900589 cb: callback
henrique2a7dccc2014-03-07 22:16:51 +0100590 });
591 }
592 },
593
Kazuki Matsudab909a382016-02-13 19:36:09 +0900594 __onOpen: function() {
henrique2a7dccc2014-03-07 22:16:51 +0100595 var self = this;
596 if (this.send_pending.length > 0) {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900597 //If the user made calls before the connection was fully
henrique2a7dccc2014-03-07 22:16:51 +0100598 //open, send them now
599 this.send_pending.forEach(function(elem) {
Philip Frank05a08ce2017-12-04 13:29:58 +0100600 self.socket.send(elem.buf);
601 self.callbacks.push((function() {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900602 var clientCallback = elem.cb;
henrique2a7dccc2014-03-07 22:16:51 +0100603 return function(msg) {
604 self.setRecvBuffer(msg);
605 clientCallback();
606 };
607 }()));
608 });
609 this.send_pending = [];
610 }
611 },
Kazuki Matsudab909a382016-02-13 19:36:09 +0900612
613 __onClose: function(evt) {
henrique2a7dccc2014-03-07 22:16:51 +0100614 this.__reset(this.url);
615 },
Kazuki Matsudab909a382016-02-13 19:36:09 +0900616
henrique2a7dccc2014-03-07 22:16:51 +0100617 __onMessage: function(evt) {
618 if (this.callbacks.length) {
619 this.callbacks.shift()(evt.data);
620 }
621 },
Kazuki Matsudab909a382016-02-13 19:36:09 +0900622
623 __onError: function(evt) {
624 console.log('Thrift WebSocket Error: ' + evt.toString());
henrique2a7dccc2014-03-07 22:16:51 +0100625 this.socket.close();
626 },
627
628 /**
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200629 * Sets the buffer to use when receiving server responses.
630 * @param {string} buf - The buffer to receive server responses.
631 */
632 setRecvBuffer: function(buf) {
633 this.recv_buf = buf;
634 this.recv_buf_sz = this.recv_buf.length;
635 this.wpos = this.recv_buf.length;
636 this.rpos = 0;
637 },
638
639 /**
henrique2a7dccc2014-03-07 22:16:51 +0100640 * Returns true if the transport is open
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200641 * @readonly
Kazuki Matsudab909a382016-02-13 19:36:09 +0900642 * @returns {boolean}
643 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200644 isOpen: function() {
henrique2a7dccc2014-03-07 22:16:51 +0100645 return this.socket && this.socket.readyState == this.socket.OPEN;
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200646 },
647
648 /**
henrique2a7dccc2014-03-07 22:16:51 +0100649 * Opens the transport connection
Kazuki Matsudab909a382016-02-13 19:36:09 +0900650 */
henrique2a7dccc2014-03-07 22:16:51 +0100651 open: function() {
652 //If OPEN/CONNECTING/CLOSING ignore additional opens
653 if (this.socket && this.socket.readyState != this.socket.CLOSED) {
654 return;
655 }
656 //If there is no socket or the socket is closed:
657 this.socket = new WebSocket(this.url);
Kazuki Matsudab909a382016-02-13 19:36:09 +0900658 this.socket.onopen = this.__onOpen.bind(this);
659 this.socket.onmessage = this.__onMessage.bind(this);
660 this.socket.onerror = this.__onError.bind(this);
661 this.socket.onclose = this.__onClose.bind(this);
henrique2a7dccc2014-03-07 22:16:51 +0100662 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200663
664 /**
henrique2a7dccc2014-03-07 22:16:51 +0100665 * Closes the transport connection
Kazuki Matsudab909a382016-02-13 19:36:09 +0900666 */
henrique2a7dccc2014-03-07 22:16:51 +0100667 close: function() {
668 this.socket.close();
669 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200670
671 /**
672 * Returns the specified number of characters from the response
673 * buffer.
674 * @param {number} len - The number of characters to return.
675 * @returns {string} Characters sent by the server.
676 */
677 read: function(len) {
678 var avail = this.wpos - this.rpos;
679
680 if (avail === 0) {
681 return '';
682 }
683
684 var give = len;
685
686 if (avail < len) {
687 give = avail;
688 }
689
690 var ret = this.read_buf.substr(this.rpos, give);
691 this.rpos += give;
692
693 //clear buf when complete?
694 return ret;
695 },
696
697 /**
698 * Returns the entire response buffer.
699 * @returns {string} Characters sent by the server.
700 */
701 readAll: function() {
702 return this.recv_buf;
703 },
704
705 /**
706 * Sets the send buffer to buf.
707 * @param {string} buf - The buffer to send.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900708 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200709 write: function(buf) {
710 this.send_buf = buf;
711 },
712
713 /**
714 * Returns the send buffer.
715 * @readonly
716 * @returns {string} The send buffer.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900717 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200718 getSendBuffer: function() {
719 return this.send_buf;
720 }
721
722};
723
724/**
725 * Initializes a Thrift JSON protocol instance.
726 * @constructor
727 * @param {Thrift.Transport} transport - The transport to serialize to/from.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900728 * @classdesc Apache Thrift Protocols perform serialization which enables cross
729 * language RPC. The Protocol type is the JavaScript browser implementation
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200730 * of the Apache Thrift TJSONProtocol.
731 * @example
732 * var protocol = new Thrift.Protocol(transport);
733 */
Roger Meier52744ee2014-03-12 09:38:42 +0100734Thrift.TJSONProtocol = Thrift.Protocol = function(transport) {
radekg1d305582015-01-01 20:35:01 +0100735 this.tstack = [];
736 this.tpos = [];
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200737 this.transport = transport;
738};
739
740/**
741 * Thrift IDL type Id to string mapping.
742 * @readonly
743 * @see {@link Thrift.Type}
744 */
745Thrift.Protocol.Type = {};
746Thrift.Protocol.Type[Thrift.Type.BOOL] = '"tf"';
747Thrift.Protocol.Type[Thrift.Type.BYTE] = '"i8"';
748Thrift.Protocol.Type[Thrift.Type.I16] = '"i16"';
749Thrift.Protocol.Type[Thrift.Type.I32] = '"i32"';
750Thrift.Protocol.Type[Thrift.Type.I64] = '"i64"';
751Thrift.Protocol.Type[Thrift.Type.DOUBLE] = '"dbl"';
752Thrift.Protocol.Type[Thrift.Type.STRUCT] = '"rec"';
753Thrift.Protocol.Type[Thrift.Type.STRING] = '"str"';
754Thrift.Protocol.Type[Thrift.Type.MAP] = '"map"';
755Thrift.Protocol.Type[Thrift.Type.LIST] = '"lst"';
756Thrift.Protocol.Type[Thrift.Type.SET] = '"set"';
757
758/**
759 * Thrift IDL type string to Id mapping.
760 * @readonly
761 * @see {@link Thrift.Type}
762 */
763Thrift.Protocol.RType = {};
764Thrift.Protocol.RType.tf = Thrift.Type.BOOL;
765Thrift.Protocol.RType.i8 = Thrift.Type.BYTE;
766Thrift.Protocol.RType.i16 = Thrift.Type.I16;
767Thrift.Protocol.RType.i32 = Thrift.Type.I32;
768Thrift.Protocol.RType.i64 = Thrift.Type.I64;
769Thrift.Protocol.RType.dbl = Thrift.Type.DOUBLE;
770Thrift.Protocol.RType.rec = Thrift.Type.STRUCT;
771Thrift.Protocol.RType.str = Thrift.Type.STRING;
772Thrift.Protocol.RType.map = Thrift.Type.MAP;
773Thrift.Protocol.RType.lst = Thrift.Type.LIST;
774Thrift.Protocol.RType.set = Thrift.Type.SET;
775
776/**
777 * The TJSONProtocol version number.
778 * @readonly
779 * @const {number} Version
780 * @memberof Thrift.Protocol
781 */
782 Thrift.Protocol.Version = 1;
783
784Thrift.Protocol.prototype = {
785 /**
786 * Returns the underlying transport.
787 * @readonly
788 * @returns {Thrift.Transport} The underlying transport.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900789 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200790 getTransport: function() {
791 return this.transport;
792 },
793
794 /**
795 * Serializes the beginning of a Thrift RPC message.
796 * @param {string} name - The service method to call.
797 * @param {Thrift.MessageType} messageType - The type of method call.
798 * @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift).
799 */
800 writeMessageBegin: function(name, messageType, seqid) {
801 this.tstack = [];
802 this.tpos = [];
803
804 this.tstack.push([Thrift.Protocol.Version, '"' +
805 name + '"', messageType, seqid]);
806 },
807
808 /**
809 * Serializes the end of a Thrift RPC message.
810 */
811 writeMessageEnd: function() {
812 var obj = this.tstack.pop();
813
814 this.wobj = this.tstack.pop();
815 this.wobj.push(obj);
816
817 this.wbuf = '[' + this.wobj.join(',') + ']';
818
819 this.transport.write(this.wbuf);
820 },
821
822
823 /**
824 * Serializes the beginning of a struct.
825 * @param {string} name - The name of the struct.
826 */
827 writeStructBegin: function(name) {
828 this.tpos.push(this.tstack.length);
829 this.tstack.push({});
830 },
831
832 /**
833 * Serializes the end of a struct.
834 */
835 writeStructEnd: function() {
836
837 var p = this.tpos.pop();
838 var struct = this.tstack[p];
839 var str = '{';
840 var first = true;
841 for (var key in struct) {
842 if (first) {
843 first = false;
844 } else {
845 str += ',';
846 }
847
848 str += key + ':' + struct[key];
849 }
850
851 str += '}';
852 this.tstack[p] = str;
853 },
854
855 /**
856 * Serializes the beginning of a struct field.
857 * @param {string} name - The name of the field.
858 * @param {Thrift.Protocol.Type} fieldType - The data type of the field.
859 * @param {number} fieldId - The field's unique identifier.
860 */
861 writeFieldBegin: function(name, fieldType, fieldId) {
862 this.tpos.push(this.tstack.length);
863 this.tstack.push({ 'fieldId': '"' +
864 fieldId + '"', 'fieldType': Thrift.Protocol.Type[fieldType]
865 });
866
867 },
868
869 /**
870 * Serializes the end of a field.
871 */
872 writeFieldEnd: function() {
873 var value = this.tstack.pop();
874 var fieldInfo = this.tstack.pop();
875
876 this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' +
877 fieldInfo.fieldType + ':' + value + '}';
878 this.tpos.pop();
879 },
880
881 /**
882 * Serializes the end of the set of fields for a struct.
883 */
884 writeFieldStop: function() {
885 //na
886 },
887
888 /**
889 * Serializes the beginning of a map collection.
890 * @param {Thrift.Type} keyType - The data type of the key.
891 * @param {Thrift.Type} valType - The data type of the value.
892 * @param {number} [size] - The number of elements in the map (ignored).
893 */
894 writeMapBegin: function(keyType, valType, size) {
895 this.tpos.push(this.tstack.length);
896 this.tstack.push([Thrift.Protocol.Type[keyType],
897 Thrift.Protocol.Type[valType], 0]);
898 },
899
900 /**
901 * Serializes the end of a map.
902 */
903 writeMapEnd: function() {
904 var p = this.tpos.pop();
905
906 if (p == this.tstack.length) {
907 return;
908 }
909
910 if ((this.tstack.length - p - 1) % 2 !== 0) {
911 this.tstack.push('');
912 }
913
914 var size = (this.tstack.length - p - 1) / 2;
915
916 this.tstack[p][this.tstack[p].length - 1] = size;
917
918 var map = '}';
919 var first = true;
920 while (this.tstack.length > p + 1) {
921 var v = this.tstack.pop();
922 var k = this.tstack.pop();
923 if (first) {
924 first = false;
925 } else {
926 map = ',' + map;
927 }
928
929 if (! isNaN(k)) { k = '"' + k + '"'; } //json "keys" need to be strings
930 map = k + ':' + v + map;
931 }
932 map = '{' + map;
933
934 this.tstack[p].push(map);
935 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
936 },
937
938 /**
939 * Serializes the beginning of a list collection.
940 * @param {Thrift.Type} elemType - The data type of the elements.
941 * @param {number} size - The number of elements in the list.
942 */
943 writeListBegin: function(elemType, size) {
944 this.tpos.push(this.tstack.length);
945 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
946 },
947
948 /**
949 * Serializes the end of a list.
950 */
951 writeListEnd: function() {
952 var p = this.tpos.pop();
953
954 while (this.tstack.length > p + 1) {
955 var tmpVal = this.tstack[p + 1];
956 this.tstack.splice(p + 1, 1);
957 this.tstack[p].push(tmpVal);
958 }
959
960 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
961 },
962
963 /**
964 * Serializes the beginning of a set collection.
965 * @param {Thrift.Type} elemType - The data type of the elements.
966 * @param {number} size - The number of elements in the list.
967 */
968 writeSetBegin: function(elemType, size) {
969 this.tpos.push(this.tstack.length);
970 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
971 },
972
973 /**
974 * Serializes the end of a set.
975 */
976 writeSetEnd: function() {
977 var p = this.tpos.pop();
978
979 while (this.tstack.length > p + 1) {
980 var tmpVal = this.tstack[p + 1];
981 this.tstack.splice(p + 1, 1);
982 this.tstack[p].push(tmpVal);
983 }
984
985 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
986 },
987
988 /** Serializes a boolean */
989 writeBool: function(value) {
990 this.tstack.push(value ? 1 : 0);
991 },
992
993 /** Serializes a number */
994 writeByte: function(i8) {
995 this.tstack.push(i8);
996 },
997
998 /** Serializes a number */
999 writeI16: function(i16) {
1000 this.tstack.push(i16);
1001 },
1002
1003 /** Serializes a number */
1004 writeI32: function(i32) {
1005 this.tstack.push(i32);
1006 },
1007
1008 /** Serializes a number */
1009 writeI64: function(i64) {
Mustafa Senol Cosarf86845e2018-12-05 17:50:18 +03001010 if (typeof i64 === 'number') {
1011 this.tstack.push(i64);
1012 } else {
1013 this.tstack.push(Int64Util.toDecimalString(i64));
1014 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001015 },
1016
1017 /** Serializes a number */
1018 writeDouble: function(dbl) {
1019 this.tstack.push(dbl);
1020 },
1021
1022 /** Serializes a string */
1023 writeString: function(str) {
1024 // We do not encode uri components for wire transfer:
1025 if (str === null) {
1026 this.tstack.push(null);
1027 } else {
1028 // concat may be slower than building a byte buffer
1029 var escapedString = '';
1030 for (var i = 0; i < str.length; i++) {
1031 var ch = str.charAt(i); // a single double quote: "
1032 if (ch === '\"') {
1033 escapedString += '\\\"'; // write out as: \"
Roger Meier52744ee2014-03-12 09:38:42 +01001034 } else if (ch === '\\') { // a single backslash
Kazuki Matsudab909a382016-02-13 19:36:09 +09001035 escapedString += '\\\\'; // write out as double backslash
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001036 } else if (ch === '\b') { // a single backspace: invisible
1037 escapedString += '\\b'; // write out as: \b"
1038 } else if (ch === '\f') { // a single formfeed: invisible
1039 escapedString += '\\f'; // write out as: \f"
1040 } else if (ch === '\n') { // a single newline: invisible
1041 escapedString += '\\n'; // write out as: \n"
1042 } else if (ch === '\r') { // a single return: invisible
1043 escapedString += '\\r'; // write out as: \r"
1044 } else if (ch === '\t') { // a single tab: invisible
1045 escapedString += '\\t'; // write out as: \t"
1046 } else {
1047 escapedString += ch; // Else it need not be escaped
1048 }
1049 }
1050 this.tstack.push('"' + escapedString + '"');
1051 }
1052 },
1053
1054 /** Serializes a string */
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001055 writeBinary: function(binary) {
1056 var str = '';
1057 if (typeof binary == 'string') {
1058 str = binary;
1059 } else if (binary instanceof Uint8Array) {
1060 var arr = binary;
1061 for (var i = 0; i < arr.length; ++i) {
1062 str += String.fromCharCode(arr[i]);
1063 }
1064 } else {
1065 throw new TypeError('writeBinary only accepts String or Uint8Array.');
1066 }
1067 this.tstack.push('"' + btoa(str) + '"');
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001068 },
1069
1070 /**
1071 @class
1072 @name AnonReadMessageBeginReturn
1073 @property {string} fname - The name of the service method.
1074 @property {Thrift.MessageType} mtype - The type of message call.
1075 @property {number} rseqid - The sequence number of the message (0 in Thrift RPC).
1076 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001077 /**
1078 * Deserializes the beginning of a message.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001079 * @returns {AnonReadMessageBeginReturn}
1080 */
1081 readMessageBegin: function() {
1082 this.rstack = [];
1083 this.rpos = [];
1084
Mustafa Senol Cosarf86845e2018-12-05 17:50:18 +03001085 received = this.transport.readAll();
1086
1087 if (typeof JSONInt64 !== 'undefined' && typeof JSONInt64.parse === 'function') {
1088 this.robj = JSONInt64.parse(received);
1089 } else if (typeof JSON !== 'undefined' && typeof JSON.parse === 'function') {
1090 this.robj = JSON.parse(received);
Roger Meier52744ee2014-03-12 09:38:42 +01001091 } else if (typeof jQuery !== 'undefined') {
Mustafa Senol Cosarf86845e2018-12-05 17:50:18 +03001092 this.robj = jQuery.parseJSON(received);
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001093 } else {
Mustafa Senol Cosarf86845e2018-12-05 17:50:18 +03001094 this.robj = eval(received);
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001095 }
1096
1097 var r = {};
1098 var version = this.robj.shift();
1099
1100 if (version != Thrift.Protocol.Version) {
1101 throw 'Wrong thrift protocol version: ' + version;
1102 }
1103
1104 r.fname = this.robj.shift();
1105 r.mtype = this.robj.shift();
1106 r.rseqid = this.robj.shift();
1107
1108
1109 //get to the main obj
1110 this.rstack.push(this.robj.shift());
1111
1112 return r;
1113 },
1114
1115 /** Deserializes the end of a message. */
1116 readMessageEnd: function() {
1117 },
1118
Kazuki Matsudab909a382016-02-13 19:36:09 +09001119 /**
1120 * Deserializes the beginning of a struct.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001121 * @param {string} [name] - The name of the struct (ignored)
1122 * @returns {object} - An object with an empty string fname property
Kazuki Matsudab909a382016-02-13 19:36:09 +09001123 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001124 readStructBegin: function(name) {
1125 var r = {};
1126 r.fname = '';
1127
1128 //incase this is an array of structs
1129 if (this.rstack[this.rstack.length - 1] instanceof Array) {
1130 this.rstack.push(this.rstack[this.rstack.length - 1].shift());
1131 }
1132
1133 return r;
1134 },
1135
1136 /** Deserializes the end of a struct. */
1137 readStructEnd: function() {
1138 if (this.rstack[this.rstack.length - 2] instanceof Array) {
1139 this.rstack.pop();
1140 }
1141 },
1142
1143 /**
1144 @class
1145 @name AnonReadFieldBeginReturn
1146 @property {string} fname - The name of the field (always '').
1147 @property {Thrift.Type} ftype - The data type of the field.
1148 @property {number} fid - The unique identifier of the field.
1149 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001150 /**
1151 * Deserializes the beginning of a field.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001152 * @returns {AnonReadFieldBeginReturn}
1153 */
1154 readFieldBegin: function() {
1155 var r = {};
1156
1157 var fid = -1;
1158 var ftype = Thrift.Type.STOP;
1159
1160 //get a fieldId
1161 for (var f in (this.rstack[this.rstack.length - 1])) {
1162 if (f === null) {
1163 continue;
1164 }
1165
1166 fid = parseInt(f, 10);
1167 this.rpos.push(this.rstack.length);
1168
1169 var field = this.rstack[this.rstack.length - 1][fid];
1170
1171 //remove so we don't see it again
1172 delete this.rstack[this.rstack.length - 1][fid];
1173
1174 this.rstack.push(field);
1175
1176 break;
1177 }
1178
1179 if (fid != -1) {
1180
1181 //should only be 1 of these but this is the only
1182 //way to match a key
1183 for (var i in (this.rstack[this.rstack.length - 1])) {
1184 if (Thrift.Protocol.RType[i] === null) {
1185 continue;
1186 }
1187
1188 ftype = Thrift.Protocol.RType[i];
1189 this.rstack[this.rstack.length - 1] =
1190 this.rstack[this.rstack.length - 1][i];
1191 }
1192 }
1193
1194 r.fname = '';
1195 r.ftype = ftype;
1196 r.fid = fid;
1197
1198 return r;
1199 },
1200
1201 /** Deserializes the end of a field. */
1202 readFieldEnd: function() {
1203 var pos = this.rpos.pop();
1204
1205 //get back to the right place in the stack
1206 while (this.rstack.length > pos) {
1207 this.rstack.pop();
1208 }
1209
1210 },
1211
1212 /**
1213 @class
1214 @name AnonReadMapBeginReturn
1215 @property {Thrift.Type} ktype - The data type of the key.
1216 @property {Thrift.Type} vtype - The data type of the value.
1217 @property {number} size - The number of elements in the map.
1218 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001219 /**
1220 * Deserializes the beginning of a map.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001221 * @returns {AnonReadMapBeginReturn}
1222 */
1223 readMapBegin: function() {
1224 var map = this.rstack.pop();
Liangliang He5d6378f2014-08-19 18:25:37 +08001225 var first = map.shift();
1226 if (first instanceof Array) {
1227 this.rstack.push(map);
1228 map = first;
1229 first = map.shift();
1230 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001231
1232 var r = {};
Liangliang He5d6378f2014-08-19 18:25:37 +08001233 r.ktype = Thrift.Protocol.RType[first];
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001234 r.vtype = Thrift.Protocol.RType[map.shift()];
1235 r.size = map.shift();
1236
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001237 this.rpos.push(this.rstack.length);
1238 this.rstack.push(map.shift());
1239
1240 return r;
1241 },
1242
1243 /** Deserializes the end of a map. */
1244 readMapEnd: function() {
1245 this.readFieldEnd();
1246 },
1247
1248 /**
1249 @class
1250 @name AnonReadColBeginReturn
1251 @property {Thrift.Type} etype - The data type of the element.
1252 @property {number} size - The number of elements in the collection.
1253 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001254 /**
1255 * Deserializes the beginning of a list.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001256 * @returns {AnonReadColBeginReturn}
1257 */
1258 readListBegin: function() {
1259 var list = this.rstack[this.rstack.length - 1];
1260
1261 var r = {};
1262 r.etype = Thrift.Protocol.RType[list.shift()];
1263 r.size = list.shift();
1264
1265 this.rpos.push(this.rstack.length);
Henrique Mendonça15d90422015-06-25 22:31:41 +10001266 this.rstack.push(list.shift());
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001267
1268 return r;
1269 },
1270
1271 /** Deserializes the end of a list. */
1272 readListEnd: function() {
Philip Frank55ddf192018-01-02 09:00:36 +01001273 var pos = this.rpos.pop() - 2;
1274 var st = this.rstack;
1275 st.pop();
1276 if (st instanceof Array && st.length > pos && st[pos].length > 0) {
1277 st.push(st[pos].shift());
1278 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001279 },
1280
Kazuki Matsudab909a382016-02-13 19:36:09 +09001281 /**
1282 * Deserializes the beginning of a set.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001283 * @returns {AnonReadColBeginReturn}
1284 */
1285 readSetBegin: function(elemType, size) {
1286 return this.readListBegin(elemType, size);
1287 },
1288
1289 /** Deserializes the end of a set. */
1290 readSetEnd: function() {
1291 return this.readListEnd();
1292 },
1293
Kazuki Matsudab909a382016-02-13 19:36:09 +09001294 /** Returns an object with a value property set to
1295 * False unless the next number in the protocol buffer
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +01001296 * is 1, in which case the value property is True */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001297 readBool: function() {
1298 var r = this.readI32();
1299
1300 if (r !== null && r.value == '1') {
1301 r.value = true;
1302 } else {
1303 r.value = false;
1304 }
1305
1306 return r;
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 readByte: function() {
1312 return this.readI32();
1313 },
1314
Kazuki Matsudab909a382016-02-13 19:36:09 +09001315 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001316 next value found in the protocol buffer */
1317 readI16: function() {
1318 return this.readI32();
1319 },
1320
Kazuki Matsudab909a382016-02-13 19:36:09 +09001321 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001322 next value found in the protocol buffer */
1323 readI32: function(f) {
1324 if (f === undefined) {
1325 f = this.rstack[this.rstack.length - 1];
1326 }
1327
1328 var r = {};
1329
1330 if (f instanceof Array) {
1331 if (f.length === 0) {
1332 r.value = undefined;
1333 } else {
Drew Ritterc0a5eed2018-06-27 10:28:00 -07001334 if (!f.isReversed) {
1335 f.reverse();
1336 f.isReversed = true;
1337 }
1338 r.value = f.pop();
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001339 }
1340 } else if (f instanceof Object) {
1341 for (var i in f) {
1342 if (i === null) {
1343 continue;
1344 }
1345 this.rstack.push(f[i]);
1346 delete f[i];
1347
1348 r.value = i;
1349 break;
1350 }
1351 } else {
1352 r.value = f;
1353 this.rstack.pop();
1354 }
1355
1356 return r;
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 */
Mustafa Senol Cosarf86845e2018-12-05 17:50:18 +03001361 readI64: function(f) {
1362 if (f === undefined) {
1363 f = this.rstack[this.rstack.length - 1];
1364 }
1365
1366 var r = {};
1367
1368 if (f instanceof Array) {
1369 if (f.length === 0) {
1370 r.value = undefined;
1371 } else {
1372 if (!f.isReversed) {
1373 f.reverse();
1374 f.isReversed = true;
1375 }
1376 r.value = f.pop();
1377 }
1378 } else if (f instanceof Object) {
1379 var int64Object = true;
1380 var objectKeys = Object.keys(f).sort();
1381 var int64Keys = ['buffer', 'offset'];
1382 if (objectKeys.length !== int64Keys.length) {
1383 int64Object = false;
1384 }
1385 for (var it=0; int64Object && it < objectKeys.length; ++it) {
1386 if (objectKeys[it] !== int64Keys[it]) {
1387 int64Object = false;
1388 }
1389 }
1390 if (int64Object) {
1391 r.value = f;
1392 } else {
1393 for (var i in f) {
1394 if (i === null) {
1395 continue;
1396 }
1397 this.rstack.push(f[i]);
1398 delete f[i];
1399
1400 r.value = i;
1401 break;
1402 }
1403 }
1404 } else {
1405 r.value = f;
1406 this.rstack.pop();
1407 }
1408 return r;
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001409 },
1410
Kazuki Matsudab909a382016-02-13 19:36:09 +09001411 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001412 next value found in the protocol buffer */
1413 readDouble: function() {
1414 return this.readI32();
1415 },
1416
Kazuki Matsudab909a382016-02-13 19:36:09 +09001417 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001418 next value found in the protocol buffer */
1419 readString: function() {
1420 var r = this.readI32();
1421 return r;
1422 },
1423
Kazuki Matsudab909a382016-02-13 19:36:09 +09001424 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001425 next value found in the protocol buffer */
1426 readBinary: function() {
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001427 var r = this.readI32();
1428 r.value = atob(r.value);
1429 return r;
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001430 },
1431
Kazuki Matsudab909a382016-02-13 19:36:09 +09001432 /**
Jens Geyer329d59a2014-06-19 22:11:53 +02001433 * Method to arbitrarily skip over data */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001434 skip: function(type) {
Jens Geyer329d59a2014-06-19 22:11:53 +02001435 var ret, i;
1436 switch (type) {
Jens Geyer329d59a2014-06-19 22:11:53 +02001437 case Thrift.Type.BOOL:
1438 return this.readBool();
1439
1440 case Thrift.Type.BYTE:
1441 return this.readByte();
1442
1443 case Thrift.Type.I16:
1444 return this.readI16();
1445
1446 case Thrift.Type.I32:
1447 return this.readI32();
1448
1449 case Thrift.Type.I64:
1450 return this.readI64();
1451
1452 case Thrift.Type.DOUBLE:
1453 return this.readDouble();
1454
1455 case Thrift.Type.STRING:
1456 return this.readString();
1457
1458 case Thrift.Type.STRUCT:
1459 this.readStructBegin();
1460 while (true) {
1461 ret = this.readFieldBegin();
1462 if (ret.ftype == Thrift.Type.STOP) {
1463 break;
1464 }
1465 this.skip(ret.ftype);
1466 this.readFieldEnd();
1467 }
1468 this.readStructEnd();
1469 return null;
1470
1471 case Thrift.Type.MAP:
1472 ret = this.readMapBegin();
1473 for (i = 0; i < ret.size; i++) {
1474 if (i > 0) {
1475 if (this.rstack.length > this.rpos[this.rpos.length - 1] + 1) {
1476 this.rstack.pop();
1477 }
1478 }
1479 this.skip(ret.ktype);
1480 this.skip(ret.vtype);
1481 }
1482 this.readMapEnd();
1483 return null;
1484
1485 case Thrift.Type.SET:
1486 ret = this.readSetBegin();
1487 for (i = 0; i < ret.size; i++) {
1488 this.skip(ret.etype);
1489 }
1490 this.readSetEnd();
1491 return null;
1492
1493 case Thrift.Type.LIST:
1494 ret = this.readListBegin();
1495 for (i = 0; i < ret.size; i++) {
1496 this.skip(ret.etype);
1497 }
1498 this.readListEnd();
1499 return null;
Philip Frank50862912018-03-07 21:21:30 +01001500
1501 default:
1502 throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA);
Jens Geyer329d59a2014-06-19 22:11:53 +02001503 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001504 }
1505};
henrique5ba91f22013-12-20 21:13:13 +01001506
1507
1508/**
1509 * Initializes a MutilplexProtocol Implementation as a Wrapper for Thrift.Protocol
1510 * @constructor
1511 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001512Thrift.MultiplexProtocol = function(srvName, trans, strictRead, strictWrite) {
henrique5ba91f22013-12-20 21:13:13 +01001513 Thrift.Protocol.call(this, trans, strictRead, strictWrite);
1514 this.serviceName = srvName;
1515};
1516Thrift.inherits(Thrift.MultiplexProtocol, Thrift.Protocol, 'multiplexProtocol');
1517
1518/** Override writeMessageBegin method of prototype*/
Kazuki Matsudab909a382016-02-13 19:36:09 +09001519Thrift.MultiplexProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
henrique5ba91f22013-12-20 21:13:13 +01001520
1521 if (type === Thrift.MessageType.CALL || type === Thrift.MessageType.ONEWAY) {
Kazuki Matsudab909a382016-02-13 19:36:09 +09001522 Thrift.Protocol.prototype.writeMessageBegin.call(this, this.serviceName + ':' + name, type, seqid);
henrique5ba91f22013-12-20 21:13:13 +01001523 } else {
1524 Thrift.Protocol.prototype.writeMessageBegin.call(this, name, type, seqid);
1525 }
1526};
1527
Kazuki Matsudab909a382016-02-13 19:36:09 +09001528Thrift.Multiplexer = function() {
henrique5ba91f22013-12-20 21:13:13 +01001529 this.seqid = 0;
1530};
1531
1532/** Instantiates a multiplexed client for a specific service
1533 * @constructor
1534 * @param {String} serviceName - The transport to serialize to/from.
1535 * @param {Thrift.ServiceClient} SCl - The Service Client Class
1536 * @param {Thrift.Transport} transport - Thrift.Transport instance which provides remote host:port
1537 * @example
1538 * var mp = new Thrift.Multiplexer();
1539 * var transport = new Thrift.Transport("http://localhost:9090/foo.thrift");
1540 * var protocol = new Thrift.Protocol(transport);
1541 * var client = mp.createClient('AuthService', AuthServiceClient, transport);
1542*/
Kazuki Matsudab909a382016-02-13 19:36:09 +09001543Thrift.Multiplexer.prototype.createClient = function(serviceName, SCl, transport) {
henrique5ba91f22013-12-20 21:13:13 +01001544 if (SCl.Client) {
1545 SCl = SCl.Client;
1546 }
1547 var self = this;
Kazuki Matsudab909a382016-02-13 19:36:09 +09001548 SCl.prototype.new_seqid = function() {
henrique5ba91f22013-12-20 21:13:13 +01001549 self.seqid += 1;
1550 return self.seqid;
1551 };
1552 var client = new SCl(new Thrift.MultiplexProtocol(serviceName, transport));
1553
1554 return client;
1555};
1556
henriquea2de4102014-02-07 14:12:56 +01001557
henrique2a7dccc2014-03-07 22:16:51 +01001558
Henrique Mendonça15d90422015-06-25 22:31:41 +10001559var copyList, copyMap;
1560
1561copyList = function(lst, types) {
1562
1563 if (!lst) {return lst; }
1564
1565 var type;
1566
1567 if (types.shift === undefined) {
1568 type = types;
1569 }
1570 else {
1571 type = types[0];
1572 }
1573 var Type = type;
1574
1575 var len = lst.length, result = [], i, val;
1576 for (i = 0; i < len; i++) {
1577 val = lst[i];
1578 if (type === null) {
1579 result.push(val);
1580 }
1581 else if (type === copyMap || type === copyList) {
1582 result.push(type(val, types.slice(1)));
1583 }
1584 else {
1585 result.push(new Type(val));
1586 }
1587 }
1588 return result;
1589};
1590
Kazuki Matsudab909a382016-02-13 19:36:09 +09001591copyMap = function(obj, types) {
Henrique Mendonça15d90422015-06-25 22:31:41 +10001592
1593 if (!obj) {return obj; }
1594
1595 var type;
1596
1597 if (types.shift === undefined) {
1598 type = types;
1599 }
1600 else {
1601 type = types[0];
1602 }
1603 var Type = type;
1604
1605 var result = {}, val;
Kazuki Matsudab909a382016-02-13 19:36:09 +09001606 for (var prop in obj) {
1607 if (obj.hasOwnProperty(prop)) {
Henrique Mendonça15d90422015-06-25 22:31:41 +10001608 val = obj[prop];
1609 if (type === null) {
1610 result[prop] = val;
1611 }
1612 else if (type === copyMap || type === copyList) {
1613 result[prop] = type(val, types.slice(1));
1614 }
1615 else {
1616 result[prop] = new Type(val);
1617 }
1618 }
1619 }
1620 return result;
1621};
1622
1623Thrift.copyMap = copyMap;
1624Thrift.copyList = copyList;