blob: fad24d68ef4f5bfeb8f27b25e4af11c8a01c244c [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 */
James E. King IIIc3375d92018-12-30 11:06:00 -050049 Version: '1.0.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) {
1010 this.tstack.push(i64);
1011 },
1012
1013 /** Serializes a number */
1014 writeDouble: function(dbl) {
1015 this.tstack.push(dbl);
1016 },
1017
1018 /** Serializes a string */
1019 writeString: function(str) {
1020 // We do not encode uri components for wire transfer:
1021 if (str === null) {
1022 this.tstack.push(null);
1023 } else {
1024 // concat may be slower than building a byte buffer
1025 var escapedString = '';
1026 for (var i = 0; i < str.length; i++) {
1027 var ch = str.charAt(i); // a single double quote: "
1028 if (ch === '\"') {
1029 escapedString += '\\\"'; // write out as: \"
Roger Meier52744ee2014-03-12 09:38:42 +01001030 } else if (ch === '\\') { // a single backslash
Kazuki Matsudab909a382016-02-13 19:36:09 +09001031 escapedString += '\\\\'; // write out as double backslash
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001032 } else if (ch === '\b') { // a single backspace: invisible
1033 escapedString += '\\b'; // write out as: \b"
1034 } else if (ch === '\f') { // a single formfeed: invisible
1035 escapedString += '\\f'; // write out as: \f"
1036 } else if (ch === '\n') { // a single newline: invisible
1037 escapedString += '\\n'; // write out as: \n"
1038 } else if (ch === '\r') { // a single return: invisible
1039 escapedString += '\\r'; // write out as: \r"
1040 } else if (ch === '\t') { // a single tab: invisible
1041 escapedString += '\\t'; // write out as: \t"
1042 } else {
1043 escapedString += ch; // Else it need not be escaped
1044 }
1045 }
1046 this.tstack.push('"' + escapedString + '"');
1047 }
1048 },
1049
1050 /** Serializes a string */
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001051 writeBinary: function(binary) {
1052 var str = '';
1053 if (typeof binary == 'string') {
1054 str = binary;
1055 } else if (binary instanceof Uint8Array) {
1056 var arr = binary;
1057 for (var i = 0; i < arr.length; ++i) {
1058 str += String.fromCharCode(arr[i]);
1059 }
1060 } else {
1061 throw new TypeError('writeBinary only accepts String or Uint8Array.');
1062 }
1063 this.tstack.push('"' + btoa(str) + '"');
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001064 },
1065
1066 /**
1067 @class
1068 @name AnonReadMessageBeginReturn
1069 @property {string} fname - The name of the service method.
1070 @property {Thrift.MessageType} mtype - The type of message call.
1071 @property {number} rseqid - The sequence number of the message (0 in Thrift RPC).
1072 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001073 /**
1074 * Deserializes the beginning of a message.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001075 * @returns {AnonReadMessageBeginReturn}
1076 */
1077 readMessageBegin: function() {
1078 this.rstack = [];
1079 this.rpos = [];
1080
Roger Meier52744ee2014-03-12 09:38:42 +01001081 if (typeof JSON !== 'undefined' && typeof JSON.parse === 'function') {
1082 this.robj = JSON.parse(this.transport.readAll());
1083 } else if (typeof jQuery !== 'undefined') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001084 this.robj = jQuery.parseJSON(this.transport.readAll());
1085 } else {
1086 this.robj = eval(this.transport.readAll());
1087 }
1088
1089 var r = {};
1090 var version = this.robj.shift();
1091
1092 if (version != Thrift.Protocol.Version) {
1093 throw 'Wrong thrift protocol version: ' + version;
1094 }
1095
1096 r.fname = this.robj.shift();
1097 r.mtype = this.robj.shift();
1098 r.rseqid = this.robj.shift();
1099
1100
1101 //get to the main obj
1102 this.rstack.push(this.robj.shift());
1103
1104 return r;
1105 },
1106
1107 /** Deserializes the end of a message. */
1108 readMessageEnd: function() {
1109 },
1110
Kazuki Matsudab909a382016-02-13 19:36:09 +09001111 /**
1112 * Deserializes the beginning of a struct.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001113 * @param {string} [name] - The name of the struct (ignored)
1114 * @returns {object} - An object with an empty string fname property
Kazuki Matsudab909a382016-02-13 19:36:09 +09001115 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001116 readStructBegin: function(name) {
1117 var r = {};
1118 r.fname = '';
1119
1120 //incase this is an array of structs
1121 if (this.rstack[this.rstack.length - 1] instanceof Array) {
1122 this.rstack.push(this.rstack[this.rstack.length - 1].shift());
1123 }
1124
1125 return r;
1126 },
1127
1128 /** Deserializes the end of a struct. */
1129 readStructEnd: function() {
1130 if (this.rstack[this.rstack.length - 2] instanceof Array) {
1131 this.rstack.pop();
1132 }
1133 },
1134
1135 /**
1136 @class
1137 @name AnonReadFieldBeginReturn
1138 @property {string} fname - The name of the field (always '').
1139 @property {Thrift.Type} ftype - The data type of the field.
1140 @property {number} fid - The unique identifier of the field.
1141 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001142 /**
1143 * Deserializes the beginning of a field.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001144 * @returns {AnonReadFieldBeginReturn}
1145 */
1146 readFieldBegin: function() {
1147 var r = {};
1148
1149 var fid = -1;
1150 var ftype = Thrift.Type.STOP;
1151
1152 //get a fieldId
1153 for (var f in (this.rstack[this.rstack.length - 1])) {
1154 if (f === null) {
1155 continue;
1156 }
1157
1158 fid = parseInt(f, 10);
1159 this.rpos.push(this.rstack.length);
1160
1161 var field = this.rstack[this.rstack.length - 1][fid];
1162
1163 //remove so we don't see it again
1164 delete this.rstack[this.rstack.length - 1][fid];
1165
1166 this.rstack.push(field);
1167
1168 break;
1169 }
1170
1171 if (fid != -1) {
1172
1173 //should only be 1 of these but this is the only
1174 //way to match a key
1175 for (var i in (this.rstack[this.rstack.length - 1])) {
1176 if (Thrift.Protocol.RType[i] === null) {
1177 continue;
1178 }
1179
1180 ftype = Thrift.Protocol.RType[i];
1181 this.rstack[this.rstack.length - 1] =
1182 this.rstack[this.rstack.length - 1][i];
1183 }
1184 }
1185
1186 r.fname = '';
1187 r.ftype = ftype;
1188 r.fid = fid;
1189
1190 return r;
1191 },
1192
1193 /** Deserializes the end of a field. */
1194 readFieldEnd: function() {
1195 var pos = this.rpos.pop();
1196
1197 //get back to the right place in the stack
1198 while (this.rstack.length > pos) {
1199 this.rstack.pop();
1200 }
1201
1202 },
1203
1204 /**
1205 @class
1206 @name AnonReadMapBeginReturn
1207 @property {Thrift.Type} ktype - The data type of the key.
1208 @property {Thrift.Type} vtype - The data type of the value.
1209 @property {number} size - The number of elements in the map.
1210 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001211 /**
1212 * Deserializes the beginning of a map.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001213 * @returns {AnonReadMapBeginReturn}
1214 */
1215 readMapBegin: function() {
1216 var map = this.rstack.pop();
Liangliang He5d6378f2014-08-19 18:25:37 +08001217 var first = map.shift();
1218 if (first instanceof Array) {
1219 this.rstack.push(map);
1220 map = first;
1221 first = map.shift();
1222 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001223
1224 var r = {};
Liangliang He5d6378f2014-08-19 18:25:37 +08001225 r.ktype = Thrift.Protocol.RType[first];
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001226 r.vtype = Thrift.Protocol.RType[map.shift()];
1227 r.size = map.shift();
1228
1229
1230 this.rpos.push(this.rstack.length);
1231 this.rstack.push(map.shift());
1232
1233 return r;
1234 },
1235
1236 /** Deserializes the end of a map. */
1237 readMapEnd: function() {
1238 this.readFieldEnd();
1239 },
1240
1241 /**
1242 @class
1243 @name AnonReadColBeginReturn
1244 @property {Thrift.Type} etype - The data type of the element.
1245 @property {number} size - The number of elements in the collection.
1246 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001247 /**
1248 * Deserializes the beginning of a list.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001249 * @returns {AnonReadColBeginReturn}
1250 */
1251 readListBegin: function() {
1252 var list = this.rstack[this.rstack.length - 1];
1253
1254 var r = {};
1255 r.etype = Thrift.Protocol.RType[list.shift()];
1256 r.size = list.shift();
1257
1258 this.rpos.push(this.rstack.length);
Henrique Mendonça15d90422015-06-25 22:31:41 +10001259 this.rstack.push(list.shift());
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001260
1261 return r;
1262 },
1263
1264 /** Deserializes the end of a list. */
1265 readListEnd: function() {
Philip Frank55ddf192018-01-02 09:00:36 +01001266 var pos = this.rpos.pop() - 2;
1267 var st = this.rstack;
1268 st.pop();
1269 if (st instanceof Array && st.length > pos && st[pos].length > 0) {
1270 st.push(st[pos].shift());
1271 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001272 },
1273
Kazuki Matsudab909a382016-02-13 19:36:09 +09001274 /**
1275 * Deserializes the beginning of a set.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001276 * @returns {AnonReadColBeginReturn}
1277 */
1278 readSetBegin: function(elemType, size) {
1279 return this.readListBegin(elemType, size);
1280 },
1281
1282 /** Deserializes the end of a set. */
1283 readSetEnd: function() {
1284 return this.readListEnd();
1285 },
1286
Kazuki Matsudab909a382016-02-13 19:36:09 +09001287 /** Returns an object with a value property set to
1288 * False unless the next number in the protocol buffer
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +01001289 * is 1, in which case the value property is True */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001290 readBool: function() {
1291 var r = this.readI32();
1292
1293 if (r !== null && r.value == '1') {
1294 r.value = true;
1295 } else {
1296 r.value = false;
1297 }
1298
1299 return r;
1300 },
1301
Kazuki Matsudab909a382016-02-13 19:36:09 +09001302 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001303 next value found in the protocol buffer */
1304 readByte: function() {
1305 return this.readI32();
1306 },
1307
Kazuki Matsudab909a382016-02-13 19:36:09 +09001308 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001309 next value found in the protocol buffer */
1310 readI16: function() {
1311 return this.readI32();
1312 },
1313
Kazuki Matsudab909a382016-02-13 19:36:09 +09001314 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001315 next value found in the protocol buffer */
1316 readI32: function(f) {
1317 if (f === undefined) {
1318 f = this.rstack[this.rstack.length - 1];
1319 }
1320
1321 var r = {};
1322
1323 if (f instanceof Array) {
1324 if (f.length === 0) {
1325 r.value = undefined;
1326 } else {
Drew Ritterc0a5eed2018-06-27 10:28:00 -07001327 if (!f.isReversed) {
1328 f.reverse();
1329 f.isReversed = true;
1330 }
1331 r.value = f.pop();
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001332 }
1333 } else if (f instanceof Object) {
1334 for (var i in f) {
1335 if (i === null) {
1336 continue;
1337 }
1338 this.rstack.push(f[i]);
1339 delete f[i];
1340
1341 r.value = i;
1342 break;
1343 }
1344 } else {
1345 r.value = f;
1346 this.rstack.pop();
1347 }
1348
1349 return r;
1350 },
1351
Kazuki Matsudab909a382016-02-13 19:36:09 +09001352 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001353 next value found in the protocol buffer */
1354 readI64: function() {
1355 return this.readI32();
1356 },
1357
Kazuki Matsudab909a382016-02-13 19:36:09 +09001358 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001359 next value found in the protocol buffer */
1360 readDouble: function() {
1361 return this.readI32();
1362 },
1363
Kazuki Matsudab909a382016-02-13 19:36:09 +09001364 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001365 next value found in the protocol buffer */
1366 readString: function() {
1367 var r = this.readI32();
1368 return r;
1369 },
1370
Kazuki Matsudab909a382016-02-13 19:36:09 +09001371 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001372 next value found in the protocol buffer */
1373 readBinary: function() {
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001374 var r = this.readI32();
1375 r.value = atob(r.value);
1376 return r;
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001377 },
1378
Kazuki Matsudab909a382016-02-13 19:36:09 +09001379 /**
Jens Geyer329d59a2014-06-19 22:11:53 +02001380 * Method to arbitrarily skip over data */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001381 skip: function(type) {
Jens Geyer329d59a2014-06-19 22:11:53 +02001382 var ret, i;
1383 switch (type) {
1384 case Thrift.Type.STOP:
1385 return null;
1386
1387 case Thrift.Type.BOOL:
1388 return this.readBool();
1389
1390 case Thrift.Type.BYTE:
1391 return this.readByte();
1392
1393 case Thrift.Type.I16:
1394 return this.readI16();
1395
1396 case Thrift.Type.I32:
1397 return this.readI32();
1398
1399 case Thrift.Type.I64:
1400 return this.readI64();
1401
1402 case Thrift.Type.DOUBLE:
1403 return this.readDouble();
1404
1405 case Thrift.Type.STRING:
1406 return this.readString();
1407
1408 case Thrift.Type.STRUCT:
1409 this.readStructBegin();
1410 while (true) {
1411 ret = this.readFieldBegin();
1412 if (ret.ftype == Thrift.Type.STOP) {
1413 break;
1414 }
1415 this.skip(ret.ftype);
1416 this.readFieldEnd();
1417 }
1418 this.readStructEnd();
1419 return null;
1420
1421 case Thrift.Type.MAP:
1422 ret = this.readMapBegin();
1423 for (i = 0; i < ret.size; i++) {
1424 if (i > 0) {
1425 if (this.rstack.length > this.rpos[this.rpos.length - 1] + 1) {
1426 this.rstack.pop();
1427 }
1428 }
1429 this.skip(ret.ktype);
1430 this.skip(ret.vtype);
1431 }
1432 this.readMapEnd();
1433 return null;
1434
1435 case Thrift.Type.SET:
1436 ret = this.readSetBegin();
1437 for (i = 0; i < ret.size; i++) {
1438 this.skip(ret.etype);
1439 }
1440 this.readSetEnd();
1441 return null;
1442
1443 case Thrift.Type.LIST:
1444 ret = this.readListBegin();
1445 for (i = 0; i < ret.size; i++) {
1446 this.skip(ret.etype);
1447 }
1448 this.readListEnd();
1449 return null;
Philip Frank50862912018-03-07 21:21:30 +01001450
1451 default:
1452 throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA);
Jens Geyer329d59a2014-06-19 22:11:53 +02001453 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001454 }
1455};
henrique5ba91f22013-12-20 21:13:13 +01001456
1457
1458/**
1459 * Initializes a MutilplexProtocol Implementation as a Wrapper for Thrift.Protocol
1460 * @constructor
1461 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001462Thrift.MultiplexProtocol = function(srvName, trans, strictRead, strictWrite) {
henrique5ba91f22013-12-20 21:13:13 +01001463 Thrift.Protocol.call(this, trans, strictRead, strictWrite);
1464 this.serviceName = srvName;
1465};
1466Thrift.inherits(Thrift.MultiplexProtocol, Thrift.Protocol, 'multiplexProtocol');
1467
1468/** Override writeMessageBegin method of prototype*/
Kazuki Matsudab909a382016-02-13 19:36:09 +09001469Thrift.MultiplexProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
henrique5ba91f22013-12-20 21:13:13 +01001470
1471 if (type === Thrift.MessageType.CALL || type === Thrift.MessageType.ONEWAY) {
Kazuki Matsudab909a382016-02-13 19:36:09 +09001472 Thrift.Protocol.prototype.writeMessageBegin.call(this, this.serviceName + ':' + name, type, seqid);
henrique5ba91f22013-12-20 21:13:13 +01001473 } else {
1474 Thrift.Protocol.prototype.writeMessageBegin.call(this, name, type, seqid);
1475 }
1476};
1477
Kazuki Matsudab909a382016-02-13 19:36:09 +09001478Thrift.Multiplexer = function() {
henrique5ba91f22013-12-20 21:13:13 +01001479 this.seqid = 0;
1480};
1481
1482/** Instantiates a multiplexed client for a specific service
1483 * @constructor
1484 * @param {String} serviceName - The transport to serialize to/from.
1485 * @param {Thrift.ServiceClient} SCl - The Service Client Class
1486 * @param {Thrift.Transport} transport - Thrift.Transport instance which provides remote host:port
1487 * @example
1488 * var mp = new Thrift.Multiplexer();
1489 * var transport = new Thrift.Transport("http://localhost:9090/foo.thrift");
1490 * var protocol = new Thrift.Protocol(transport);
1491 * var client = mp.createClient('AuthService', AuthServiceClient, transport);
1492*/
Kazuki Matsudab909a382016-02-13 19:36:09 +09001493Thrift.Multiplexer.prototype.createClient = function(serviceName, SCl, transport) {
henrique5ba91f22013-12-20 21:13:13 +01001494 if (SCl.Client) {
1495 SCl = SCl.Client;
1496 }
1497 var self = this;
Kazuki Matsudab909a382016-02-13 19:36:09 +09001498 SCl.prototype.new_seqid = function() {
henrique5ba91f22013-12-20 21:13:13 +01001499 self.seqid += 1;
1500 return self.seqid;
1501 };
1502 var client = new SCl(new Thrift.MultiplexProtocol(serviceName, transport));
1503
1504 return client;
1505};
1506
henriquea2de4102014-02-07 14:12:56 +01001507
henrique2a7dccc2014-03-07 22:16:51 +01001508
Henrique Mendonça15d90422015-06-25 22:31:41 +10001509var copyList, copyMap;
1510
1511copyList = function(lst, types) {
1512
1513 if (!lst) {return lst; }
1514
1515 var type;
1516
1517 if (types.shift === undefined) {
1518 type = types;
1519 }
1520 else {
1521 type = types[0];
1522 }
1523 var Type = type;
1524
1525 var len = lst.length, result = [], i, val;
1526 for (i = 0; i < len; i++) {
1527 val = lst[i];
1528 if (type === null) {
1529 result.push(val);
1530 }
1531 else if (type === copyMap || type === copyList) {
1532 result.push(type(val, types.slice(1)));
1533 }
1534 else {
1535 result.push(new Type(val));
1536 }
1537 }
1538 return result;
1539};
1540
Kazuki Matsudab909a382016-02-13 19:36:09 +09001541copyMap = function(obj, types) {
Henrique Mendonça15d90422015-06-25 22:31:41 +10001542
1543 if (!obj) {return obj; }
1544
1545 var type;
1546
1547 if (types.shift === undefined) {
1548 type = types;
1549 }
1550 else {
1551 type = types[0];
1552 }
1553 var Type = type;
1554
1555 var result = {}, val;
Kazuki Matsudab909a382016-02-13 19:36:09 +09001556 for (var prop in obj) {
1557 if (obj.hasOwnProperty(prop)) {
Henrique Mendonça15d90422015-06-25 22:31:41 +10001558 val = obj[prop];
1559 if (type === null) {
1560 result[prop] = val;
1561 }
1562 else if (type === copyMap || type === copyList) {
1563 result[prop] = type(val, types.slice(1));
1564 }
1565 else {
1566 result[prop] = new Type(val);
1567 }
1568 }
1569 }
1570 return result;
1571};
1572
1573Thrift.copyMap = copyMap;
1574Thrift.copyList = copyList;