blob: 1a11871f3a0a1c67682645fd7cfb3a5bfca5087c [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 */
49 Version: '1.0.0-dev',
50
51 /**
52 * Thrift IDL type string to Id mapping.
53 * @readonly
54 * @property {number} STOP - End of a set of fields.
55 * @property {number} VOID - No value (only legal for return types).
56 * @property {number} BOOL - True/False integer.
57 * @property {number} BYTE - Signed 8 bit integer.
Kazuki Matsudab909a382016-02-13 19:36:09 +090058 * @property {number} I08 - Signed 8 bit integer.
Henrique Mendonça095ddb72013-09-20 19:38:03 +020059 * @property {number} DOUBLE - 64 bit IEEE 854 floating point.
60 * @property {number} I16 - Signed 16 bit integer.
61 * @property {number} I32 - Signed 32 bit integer.
62 * @property {number} I64 - Signed 64 bit integer.
63 * @property {number} STRING - Array of bytes representing a string of characters.
64 * @property {number} UTF7 - Array of bytes representing a string of UTF7 encoded characters.
65 * @property {number} STRUCT - A multifield type.
66 * @property {number} MAP - A collection type (map/associative-array/dictionary).
67 * @property {number} SET - A collection type (unordered and without repeated values).
68 * @property {number} LIST - A collection type (unordered).
69 * @property {number} UTF8 - Array of bytes representing a string of UTF8 encoded characters.
70 * @property {number} UTF16 - Array of bytes representing a string of UTF16 encoded characters.
71 */
72 Type: {
Kazuki Matsudab909a382016-02-13 19:36:09 +090073 STOP: 0,
74 VOID: 1,
75 BOOL: 2,
76 BYTE: 3,
77 I08: 3,
78 DOUBLE: 4,
79 I16: 6,
80 I32: 8,
81 I64: 10,
82 STRING: 11,
83 UTF7: 11,
84 STRUCT: 12,
85 MAP: 13,
86 SET: 14,
87 LIST: 15,
88 UTF8: 16,
89 UTF16: 17
Henrique Mendonça095ddb72013-09-20 19:38:03 +020090 },
91
92 /**
93 * Thrift RPC message type string to Id mapping.
94 * @readonly
95 * @property {number} CALL - RPC call sent from client to server.
96 * @property {number} REPLY - RPC call normal response from server to client.
97 * @property {number} EXCEPTION - RPC call exception response from server to client.
98 * @property {number} ONEWAY - Oneway RPC call from client to server with no response.
99 */
100 MessageType: {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900101 CALL: 1,
102 REPLY: 2,
103 EXCEPTION: 3,
104 ONEWAY: 4
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200105 },
106
107 /**
108 * Utility function returning the count of an object's own properties.
109 * @param {object} obj - Object to test.
110 * @returns {number} number of object's own properties
111 */
112 objectLength: function(obj) {
113 var length = 0;
114 for (var k in obj) {
115 if (obj.hasOwnProperty(k)) {
116 length++;
117 }
118 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200119 return length;
120 },
121
122 /**
123 * Utility function to establish prototype inheritance.
124 * @see {@link http://javascript.crockford.com/prototypal.html|Prototypal Inheritance}
125 * @param {function} constructor - Contstructor function to set as derived.
126 * @param {function} superConstructor - Contstructor function to set as base.
127 * @param {string} [name] - Type name to set as name property in derived prototype.
128 */
129 inherits: function(constructor, superConstructor, name) {
130 function F() {}
131 F.prototype = superConstructor.prototype;
132 constructor.prototype = new F();
Kazuki Matsudab909a382016-02-13 19:36:09 +0900133 constructor.prototype.name = name || '';
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200134 }
135};
136
137/**
138 * Initializes a Thrift TException instance.
139 * @constructor
140 * @augments Error
141 * @param {string} message - The TException message (distinct from the Error message).
142 * @classdesc TException is the base class for all Thrift exceptions types.
143 */
144Thrift.TException = function(message) {
145 this.message = message;
146};
147Thrift.inherits(Thrift.TException, Error, 'TException');
148
149/**
150 * Returns the message set on the exception.
151 * @readonly
152 * @returns {string} exception message
153 */
154Thrift.TException.prototype.getMessage = function() {
155 return this.message;
156};
157
158/**
159 * Thrift Application Exception type string to Id mapping.
160 * @readonly
161 * @property {number} UNKNOWN - Unknown/undefined.
162 * @property {number} UNKNOWN_METHOD - Client attempted to call a method unknown to the server.
163 * @property {number} INVALID_MESSAGE_TYPE - Client passed an unknown/unsupported MessageType.
164 * @property {number} WRONG_METHOD_NAME - Unused.
165 * @property {number} BAD_SEQUENCE_ID - Unused in Thrift RPC, used to flag proprietary sequence number errors.
166 * @property {number} MISSING_RESULT - Raised by a server processor if a handler fails to supply the required return result.
167 * @property {number} INTERNAL_ERROR - Something bad happened.
168 * @property {number} PROTOCOL_ERROR - The protocol layer failed to serialize or deserialize data.
169 * @property {number} INVALID_TRANSFORM - Unused.
170 * @property {number} INVALID_PROTOCOL - The protocol (or version) is not supported.
171 * @property {number} UNSUPPORTED_CLIENT_TYPE - Unused.
172 */
173Thrift.TApplicationExceptionType = {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900174 UNKNOWN: 0,
175 UNKNOWN_METHOD: 1,
176 INVALID_MESSAGE_TYPE: 2,
177 WRONG_METHOD_NAME: 3,
178 BAD_SEQUENCE_ID: 4,
179 MISSING_RESULT: 5,
180 INTERNAL_ERROR: 6,
181 PROTOCOL_ERROR: 7,
182 INVALID_TRANSFORM: 8,
183 INVALID_PROTOCOL: 9,
184 UNSUPPORTED_CLIENT_TYPE: 10
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200185};
186
187/**
188 * Initializes a Thrift TApplicationException instance.
189 * @constructor
190 * @augments Thrift.TException
191 * @param {string} message - The TApplicationException message (distinct from the Error message).
192 * @param {Thrift.TApplicationExceptionType} [code] - The TApplicationExceptionType code.
193 * @classdesc TApplicationException is the exception class used to propagate exceptions from an RPC server back to a calling client.
194*/
195Thrift.TApplicationException = function(message, code) {
196 this.message = message;
Kazuki Matsudab909a382016-02-13 19:36:09 +0900197 this.code = typeof code === 'number' ? code : 0;
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200198};
199Thrift.inherits(Thrift.TApplicationException, Thrift.TException, 'TApplicationException');
200
201/**
202 * Read a TApplicationException from the supplied protocol.
203 * @param {object} input - The input protocol to read from.
204 */
205Thrift.TApplicationException.prototype.read = function(input) {
206 while (1) {
207 var ret = input.readFieldBegin();
208
209 if (ret.ftype == Thrift.Type.STOP) {
210 break;
211 }
212
213 var fid = ret.fid;
214
215 switch (fid) {
216 case 1:
217 if (ret.ftype == Thrift.Type.STRING) {
218 ret = input.readString();
219 this.message = ret.value;
220 } else {
221 ret = input.skip(ret.ftype);
222 }
223 break;
224 case 2:
225 if (ret.ftype == Thrift.Type.I32) {
226 ret = input.readI32();
227 this.code = ret.value;
228 } else {
229 ret = input.skip(ret.ftype);
230 }
231 break;
232 default:
233 ret = input.skip(ret.ftype);
234 break;
235 }
236
237 input.readFieldEnd();
238 }
239
240 input.readStructEnd();
241};
242
243/**
244 * Wite a TApplicationException to the supplied protocol.
245 * @param {object} output - The output protocol to write to.
246 */
247Thrift.TApplicationException.prototype.write = function(output) {
248 output.writeStructBegin('TApplicationException');
249
250 if (this.message) {
251 output.writeFieldBegin('message', Thrift.Type.STRING, 1);
252 output.writeString(this.getMessage());
253 output.writeFieldEnd();
254 }
255
256 if (this.code) {
257 output.writeFieldBegin('type', Thrift.Type.I32, 2);
258 output.writeI32(this.code);
259 output.writeFieldEnd();
260 }
261
262 output.writeFieldStop();
263 output.writeStructEnd();
264};
265
266/**
267 * Returns the application exception code set on the exception.
268 * @readonly
269 * @returns {Thrift.TApplicationExceptionType} exception code
270 */
271Thrift.TApplicationException.prototype.getCode = function() {
272 return this.code;
273};
274
Liyin Tangf5399b22016-03-05 14:54:53 -0800275Thrift.TProtocolExceptionType = {
276 UNKNOWN: 0,
277 INVALID_DATA: 1,
278 NEGATIVE_SIZE: 2,
279 SIZE_LIMIT: 3,
280 BAD_VERSION: 4,
281 NOT_IMPLEMENTED: 5,
282 DEPTH_LIMIT: 6
283};
284
285Thrift.TProtocolException = function TProtocolException(type, message) {
286 Error.call(this);
287 Error.captureStackTrace(this, this.constructor);
288 this.name = this.constructor.name;
289 this.type = type;
290 this.message = message;
291};
292Thrift.inherits(Thrift.TProtocolException, Thrift.TException, 'TProtocolException');
293
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200294/**
henrique2a7dccc2014-03-07 22:16:51 +0100295 * Constructor Function for the XHR transport.
296 * If you do not specify a url then you must handle XHR operations on
297 * your own. This type can also be constructed using the Transport alias
298 * for backward compatibility.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200299 * @constructor
300 * @param {string} [url] - The URL to connect to.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900301 * @classdesc The Apache Thrift Transport layer performs byte level I/O
302 * between RPC clients and servers. The JavaScript TXHRTransport object
henrique2a7dccc2014-03-07 22:16:51 +0100303 * uses Http[s]/XHR. Target servers must implement the http[s] transport
304 * (see: node.js example server_http.js).
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200305 * @example
henrique2a7dccc2014-03-07 22:16:51 +0100306 * var transport = new Thrift.TXHRTransport("http://localhost:8585");
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200307 */
Roger Meier52744ee2014-03-12 09:38:42 +0100308Thrift.Transport = Thrift.TXHRTransport = function(url, options) {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200309 this.url = url;
310 this.wpos = 0;
311 this.rpos = 0;
Roger Meier52744ee2014-03-12 09:38:42 +0100312 this.useCORS = (options && options.useCORS);
Randy Abernethy3ca89e62016-04-13 06:24:57 -0700313 this.customHeaders = options ? (options.customHeaders ? options.customHeaders : {}): {};
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200314 this.send_buf = '';
315 this.recv_buf = '';
316};
317
henrique2a7dccc2014-03-07 22:16:51 +0100318Thrift.TXHRTransport.prototype = {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200319 /**
320 * Gets the browser specific XmlHttpRequest Object.
321 * @returns {object} the browser XHR interface object
322 */
323 getXmlHttpRequestObject: function() {
324 try { return new XMLHttpRequest(); } catch (e1) { }
325 try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e2) { }
326 try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e3) { }
327
328 throw "Your browser doesn't support XHR.";
329 },
330
331 /**
Kazuki Matsudab909a382016-02-13 19:36:09 +0900332 * Sends the current XRH request if the transport was created with a URL
henrique2a7dccc2014-03-07 22:16:51 +0100333 * and the async parameter is false. If the transport was not created with
Kazuki Matsudab909a382016-02-13 19:36:09 +0900334 * a URL, or the async parameter is True and no callback is provided, or
henrique2a7dccc2014-03-07 22:16:51 +0100335 * the URL is an empty string, the current send buffer is returned.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200336 * @param {object} async - If true the current send buffer is returned.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900337 * @param {object} callback - Optional async completion callback
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200338 * @returns {undefined|string} Nothing or the current send buffer.
339 * @throws {string} If XHR fails.
340 */
henriquea2de4102014-02-07 14:12:56 +0100341 flush: function(async, callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100342 var self = this;
henriquea2de4102014-02-07 14:12:56 +0100343 if ((async && !callback) || this.url === undefined || this.url === '') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200344 return this.send_buf;
345 }
346
347 var xreq = this.getXmlHttpRequestObject();
348
349 if (xreq.overrideMimeType) {
henriqueeec445e2015-05-04 21:37:51 +1000350 xreq.overrideMimeType('application/vnd.apache.thrift.json; charset=utf-8');
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200351 }
352
henriquea2de4102014-02-07 14:12:56 +0100353 if (callback) {
henrique2a7dccc2014-03-07 22:16:51 +0100354 //Ignore XHR callbacks until the data arrives, then call the
355 // client's callback
Kazuki Matsudab909a382016-02-13 19:36:09 +0900356 xreq.onreadystatechange =
henrique2a7dccc2014-03-07 22:16:51 +0100357 (function() {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900358 var clientCallback = callback;
henrique2a7dccc2014-03-07 22:16:51 +0100359 return function() {
360 if (this.readyState == 4 && this.status == 200) {
361 self.setRecvBuffer(this.responseText);
362 clientCallback();
363 }
364 };
365 }());
HIRANO Satoshi84cf3632015-12-07 17:17:15 +0900366
367 // detect net::ERR_CONNECTION_REFUSED and call the callback.
368 xreq.onerror =
369 (function() {
370 var clientCallback = callback;
371 return function() {
372 clientCallback();
373 };
374 }());
375
henriquea2de4102014-02-07 14:12:56 +0100376 }
377
378 xreq.open('POST', this.url, !!async);
henriqueeec445e2015-05-04 21:37:51 +1000379
Randy Abernethy3ca89e62016-04-13 06:24:57 -0700380 // add custom headers
381 Object.keys(self.customHeaders).forEach(function(prop) {
382 xreq.setRequestHeader(prop, self.customHeaders[prop]);
383 });
384
henriqueeec445e2015-05-04 21:37:51 +1000385 if (xreq.setRequestHeader) {
386 xreq.setRequestHeader('Accept', 'application/vnd.apache.thrift.json; charset=utf-8');
387 xreq.setRequestHeader('Content-Type', 'application/vnd.apache.thrift.json; charset=utf-8');
388 }
389
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200390 xreq.send(this.send_buf);
henriquea2de4102014-02-07 14:12:56 +0100391 if (async && callback) {
392 return;
393 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200394
395 if (xreq.readyState != 4) {
396 throw 'encountered an unknown ajax ready state: ' + xreq.readyState;
397 }
398
399 if (xreq.status != 200) {
400 throw 'encountered a unknown request status: ' + xreq.status;
401 }
402
403 this.recv_buf = xreq.responseText;
404 this.recv_buf_sz = this.recv_buf.length;
405 this.wpos = this.recv_buf.length;
406 this.rpos = 0;
407 },
408
409 /**
410 * Creates a jQuery XHR object to be used for a Thrift server call.
411 * @param {object} client - The Thrift Service client object generated by the IDL compiler.
412 * @param {object} postData - The message to send to the server.
henrique2a7dccc2014-03-07 22:16:51 +0100413 * @param {function} args - The original call arguments with the success call back at the end.
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200414 * @param {function} recv_method - The Thrift Service Client receive method for the call.
415 * @returns {object} A new jQuery XHR object.
416 * @throws {string} If the jQuery version is prior to 1.5 or if jQuery is not found.
417 */
418 jqRequest: function(client, postData, args, recv_method) {
419 if (typeof jQuery === 'undefined' ||
420 typeof jQuery.Deferred === 'undefined') {
421 throw 'Thrift.js requires jQuery 1.5+ to use asynchronous requests';
422 }
423
424 var thriftTransport = this;
425
426 var jqXHR = jQuery.ajax({
427 url: this.url,
428 data: postData,
429 type: 'POST',
430 cache: false,
henriqueeec445e2015-05-04 21:37:51 +1000431 contentType: 'application/vnd.apache.thrift.json; charset=utf-8',
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200432 dataType: 'text thrift',
433 converters: {
434 'text thrift' : function(responseData) {
435 thriftTransport.setRecvBuffer(responseData);
436 var value = recv_method.call(client);
437 return value;
438 }
439 },
440 context: client,
441 success: jQuery.makeArray(args).pop()
442 });
443
444 return jqXHR;
445 },
446
447 /**
henrique2a7dccc2014-03-07 22:16:51 +0100448 * Sets the buffer to provide the protocol when deserializing.
449 * @param {string} buf - The buffer to supply the protocol.
450 */
451 setRecvBuffer: function(buf) {
452 this.recv_buf = buf;
453 this.recv_buf_sz = this.recv_buf.length;
454 this.wpos = this.recv_buf.length;
455 this.rpos = 0;
456 },
457
458 /**
459 * Returns true if the transport is open, XHR always returns true.
460 * @readonly
461 * @returns {boolean} Always True.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900462 */
henrique2a7dccc2014-03-07 22:16:51 +0100463 isOpen: function() {
464 return true;
465 },
466
467 /**
468 * Opens the transport connection, with XHR this is a nop.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900469 */
henrique2a7dccc2014-03-07 22:16:51 +0100470 open: function() {},
471
472 /**
473 * Closes the transport connection, with XHR this is a nop.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900474 */
henrique2a7dccc2014-03-07 22:16:51 +0100475 close: function() {},
476
477 /**
478 * Returns the specified number of characters from the response
479 * buffer.
480 * @param {number} len - The number of characters to return.
481 * @returns {string} Characters sent by the server.
482 */
483 read: function(len) {
484 var avail = this.wpos - this.rpos;
485
486 if (avail === 0) {
487 return '';
488 }
489
490 var give = len;
491
492 if (avail < len) {
493 give = avail;
494 }
495
496 var ret = this.read_buf.substr(this.rpos, give);
497 this.rpos += give;
498
499 //clear buf when complete?
500 return ret;
501 },
502
503 /**
504 * Returns the entire response buffer.
505 * @returns {string} Characters sent by the server.
506 */
507 readAll: function() {
508 return this.recv_buf;
509 },
510
511 /**
512 * Sets the send buffer to buf.
513 * @param {string} buf - The buffer to send.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900514 */
henrique2a7dccc2014-03-07 22:16:51 +0100515 write: function(buf) {
516 this.send_buf = buf;
517 },
518
519 /**
520 * Returns the send buffer.
521 * @readonly
522 * @returns {string} The send buffer.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900523 */
henrique2a7dccc2014-03-07 22:16:51 +0100524 getSendBuffer: function() {
525 return this.send_buf;
526 }
527
528};
529
530
531/**
532 * Constructor Function for the WebSocket transport.
533 * @constructor
534 * @param {string} [url] - The URL to connect to.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900535 * @classdesc The Apache Thrift Transport layer performs byte level I/O
536 * between RPC clients and servers. The JavaScript TWebSocketTransport object
henrique2a7dccc2014-03-07 22:16:51 +0100537 * uses the WebSocket protocol. Target servers must implement WebSocket.
538 * (see: node.js example server_http.js).
539 * @example
540 * var transport = new Thrift.TWebSocketTransport("http://localhost:8585");
541 */
542Thrift.TWebSocketTransport = function(url) {
543 this.__reset(url);
544};
545
546Thrift.TWebSocketTransport.prototype = {
547 __reset: function(url) {
548 this.url = url; //Where to connect
549 this.socket = null; //The web socket
550 this.callbacks = []; //Pending callbacks
551 this.send_pending = []; //Buffers/Callback pairs waiting to be sent
552 this.send_buf = ''; //Outbound data, immutable until sent
553 this.recv_buf = ''; //Inbound data
554 this.rb_wpos = 0; //Network write position in receive buffer
555 this.rb_rpos = 0; //Client read position in receive buffer
556 },
557
558 /**
Kazuki Matsudab909a382016-02-13 19:36:09 +0900559 * Sends the current WS request and registers callback. The async
560 * parameter is ignored (WS flush is always async) and the callback
henrique2a7dccc2014-03-07 22:16:51 +0100561 * function parameter is required.
562 * @param {object} async - Ignored.
563 * @param {object} callback - The client completion callback.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900564 * @returns {undefined|string} Nothing (undefined)
henrique2a7dccc2014-03-07 22:16:51 +0100565 */
566 flush: function(async, callback) {
567 var self = this;
568 if (this.isOpen()) {
569 //Send data and register a callback to invoke the client callback
Kazuki Matsudab909a382016-02-13 19:36:09 +0900570 this.socket.send(this.send_buf);
henrique2a7dccc2014-03-07 22:16:51 +0100571 this.callbacks.push((function() {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900572 var clientCallback = callback;
henrique2a7dccc2014-03-07 22:16:51 +0100573 return function(msg) {
574 self.setRecvBuffer(msg);
575 clientCallback();
576 };
577 }()));
James E. King, III48ba7362017-09-24 08:46:27 -0700578 if(callback) {
579 this.callbacks.push((function() {
580 var clientCallback = callback;
581 return function(msg) {
582 self.setRecvBuffer(msg);
583 clientCallback();
584 };
585 }()));
586 }
henrique2a7dccc2014-03-07 22:16:51 +0100587 } else {
588 //Queue the send to go out __onOpen
589 this.send_pending.push({
590 buf: this.send_buf,
Kazuki Matsudab909a382016-02-13 19:36:09 +0900591 cb: callback
henrique2a7dccc2014-03-07 22:16:51 +0100592 });
593 }
594 },
595
Kazuki Matsudab909a382016-02-13 19:36:09 +0900596 __onOpen: function() {
henrique2a7dccc2014-03-07 22:16:51 +0100597 var self = this;
598 if (this.send_pending.length > 0) {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900599 //If the user made calls before the connection was fully
henrique2a7dccc2014-03-07 22:16:51 +0100600 //open, send them now
601 this.send_pending.forEach(function(elem) {
Philip Frank05a08ce2017-12-04 13:29:58 +0100602 self.socket.send(elem.buf);
603 self.callbacks.push((function() {
Kazuki Matsudab909a382016-02-13 19:36:09 +0900604 var clientCallback = elem.cb;
henrique2a7dccc2014-03-07 22:16:51 +0100605 return function(msg) {
606 self.setRecvBuffer(msg);
607 clientCallback();
608 };
609 }()));
610 });
611 this.send_pending = [];
612 }
613 },
Kazuki Matsudab909a382016-02-13 19:36:09 +0900614
615 __onClose: function(evt) {
henrique2a7dccc2014-03-07 22:16:51 +0100616 this.__reset(this.url);
617 },
Kazuki Matsudab909a382016-02-13 19:36:09 +0900618
henrique2a7dccc2014-03-07 22:16:51 +0100619 __onMessage: function(evt) {
620 if (this.callbacks.length) {
621 this.callbacks.shift()(evt.data);
622 }
623 },
Kazuki Matsudab909a382016-02-13 19:36:09 +0900624
625 __onError: function(evt) {
626 console.log('Thrift WebSocket Error: ' + evt.toString());
henrique2a7dccc2014-03-07 22:16:51 +0100627 this.socket.close();
628 },
629
630 /**
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200631 * Sets the buffer to use when receiving server responses.
632 * @param {string} buf - The buffer to receive server responses.
633 */
634 setRecvBuffer: function(buf) {
635 this.recv_buf = buf;
636 this.recv_buf_sz = this.recv_buf.length;
637 this.wpos = this.recv_buf.length;
638 this.rpos = 0;
639 },
640
641 /**
henrique2a7dccc2014-03-07 22:16:51 +0100642 * Returns true if the transport is open
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200643 * @readonly
Kazuki Matsudab909a382016-02-13 19:36:09 +0900644 * @returns {boolean}
645 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200646 isOpen: function() {
henrique2a7dccc2014-03-07 22:16:51 +0100647 return this.socket && this.socket.readyState == this.socket.OPEN;
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200648 },
649
650 /**
henrique2a7dccc2014-03-07 22:16:51 +0100651 * Opens the transport connection
Kazuki Matsudab909a382016-02-13 19:36:09 +0900652 */
henrique2a7dccc2014-03-07 22:16:51 +0100653 open: function() {
654 //If OPEN/CONNECTING/CLOSING ignore additional opens
655 if (this.socket && this.socket.readyState != this.socket.CLOSED) {
656 return;
657 }
658 //If there is no socket or the socket is closed:
659 this.socket = new WebSocket(this.url);
Kazuki Matsudab909a382016-02-13 19:36:09 +0900660 this.socket.onopen = this.__onOpen.bind(this);
661 this.socket.onmessage = this.__onMessage.bind(this);
662 this.socket.onerror = this.__onError.bind(this);
663 this.socket.onclose = this.__onClose.bind(this);
henrique2a7dccc2014-03-07 22:16:51 +0100664 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200665
666 /**
henrique2a7dccc2014-03-07 22:16:51 +0100667 * Closes the transport connection
Kazuki Matsudab909a382016-02-13 19:36:09 +0900668 */
henrique2a7dccc2014-03-07 22:16:51 +0100669 close: function() {
670 this.socket.close();
671 },
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200672
673 /**
674 * Returns the specified number of characters from the response
675 * buffer.
676 * @param {number} len - The number of characters to return.
677 * @returns {string} Characters sent by the server.
678 */
679 read: function(len) {
680 var avail = this.wpos - this.rpos;
681
682 if (avail === 0) {
683 return '';
684 }
685
686 var give = len;
687
688 if (avail < len) {
689 give = avail;
690 }
691
692 var ret = this.read_buf.substr(this.rpos, give);
693 this.rpos += give;
694
695 //clear buf when complete?
696 return ret;
697 },
698
699 /**
700 * Returns the entire response buffer.
701 * @returns {string} Characters sent by the server.
702 */
703 readAll: function() {
704 return this.recv_buf;
705 },
706
707 /**
708 * Sets the send buffer to buf.
709 * @param {string} buf - The buffer to send.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900710 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200711 write: function(buf) {
712 this.send_buf = buf;
713 },
714
715 /**
716 * Returns the send buffer.
717 * @readonly
718 * @returns {string} The send buffer.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900719 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200720 getSendBuffer: function() {
721 return this.send_buf;
722 }
723
724};
725
726/**
727 * Initializes a Thrift JSON protocol instance.
728 * @constructor
729 * @param {Thrift.Transport} transport - The transport to serialize to/from.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900730 * @classdesc Apache Thrift Protocols perform serialization which enables cross
731 * language RPC. The Protocol type is the JavaScript browser implementation
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200732 * of the Apache Thrift TJSONProtocol.
733 * @example
734 * var protocol = new Thrift.Protocol(transport);
735 */
Roger Meier52744ee2014-03-12 09:38:42 +0100736Thrift.TJSONProtocol = Thrift.Protocol = function(transport) {
radekg1d305582015-01-01 20:35:01 +0100737 this.tstack = [];
738 this.tpos = [];
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200739 this.transport = transport;
740};
741
742/**
743 * Thrift IDL type Id to string mapping.
744 * @readonly
745 * @see {@link Thrift.Type}
746 */
747Thrift.Protocol.Type = {};
748Thrift.Protocol.Type[Thrift.Type.BOOL] = '"tf"';
749Thrift.Protocol.Type[Thrift.Type.BYTE] = '"i8"';
750Thrift.Protocol.Type[Thrift.Type.I16] = '"i16"';
751Thrift.Protocol.Type[Thrift.Type.I32] = '"i32"';
752Thrift.Protocol.Type[Thrift.Type.I64] = '"i64"';
753Thrift.Protocol.Type[Thrift.Type.DOUBLE] = '"dbl"';
754Thrift.Protocol.Type[Thrift.Type.STRUCT] = '"rec"';
755Thrift.Protocol.Type[Thrift.Type.STRING] = '"str"';
756Thrift.Protocol.Type[Thrift.Type.MAP] = '"map"';
757Thrift.Protocol.Type[Thrift.Type.LIST] = '"lst"';
758Thrift.Protocol.Type[Thrift.Type.SET] = '"set"';
759
760/**
761 * Thrift IDL type string to Id mapping.
762 * @readonly
763 * @see {@link Thrift.Type}
764 */
765Thrift.Protocol.RType = {};
766Thrift.Protocol.RType.tf = Thrift.Type.BOOL;
767Thrift.Protocol.RType.i8 = Thrift.Type.BYTE;
768Thrift.Protocol.RType.i16 = Thrift.Type.I16;
769Thrift.Protocol.RType.i32 = Thrift.Type.I32;
770Thrift.Protocol.RType.i64 = Thrift.Type.I64;
771Thrift.Protocol.RType.dbl = Thrift.Type.DOUBLE;
772Thrift.Protocol.RType.rec = Thrift.Type.STRUCT;
773Thrift.Protocol.RType.str = Thrift.Type.STRING;
774Thrift.Protocol.RType.map = Thrift.Type.MAP;
775Thrift.Protocol.RType.lst = Thrift.Type.LIST;
776Thrift.Protocol.RType.set = Thrift.Type.SET;
777
778/**
779 * The TJSONProtocol version number.
780 * @readonly
781 * @const {number} Version
782 * @memberof Thrift.Protocol
783 */
784 Thrift.Protocol.Version = 1;
785
786Thrift.Protocol.prototype = {
787 /**
788 * Returns the underlying transport.
789 * @readonly
790 * @returns {Thrift.Transport} The underlying transport.
Kazuki Matsudab909a382016-02-13 19:36:09 +0900791 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +0200792 getTransport: function() {
793 return this.transport;
794 },
795
796 /**
797 * Serializes the beginning of a Thrift RPC message.
798 * @param {string} name - The service method to call.
799 * @param {Thrift.MessageType} messageType - The type of method call.
800 * @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift).
801 */
802 writeMessageBegin: function(name, messageType, seqid) {
803 this.tstack = [];
804 this.tpos = [];
805
806 this.tstack.push([Thrift.Protocol.Version, '"' +
807 name + '"', messageType, seqid]);
808 },
809
810 /**
811 * Serializes the end of a Thrift RPC message.
812 */
813 writeMessageEnd: function() {
814 var obj = this.tstack.pop();
815
816 this.wobj = this.tstack.pop();
817 this.wobj.push(obj);
818
819 this.wbuf = '[' + this.wobj.join(',') + ']';
820
821 this.transport.write(this.wbuf);
822 },
823
824
825 /**
826 * Serializes the beginning of a struct.
827 * @param {string} name - The name of the struct.
828 */
829 writeStructBegin: function(name) {
830 this.tpos.push(this.tstack.length);
831 this.tstack.push({});
832 },
833
834 /**
835 * Serializes the end of a struct.
836 */
837 writeStructEnd: function() {
838
839 var p = this.tpos.pop();
840 var struct = this.tstack[p];
841 var str = '{';
842 var first = true;
843 for (var key in struct) {
844 if (first) {
845 first = false;
846 } else {
847 str += ',';
848 }
849
850 str += key + ':' + struct[key];
851 }
852
853 str += '}';
854 this.tstack[p] = str;
855 },
856
857 /**
858 * Serializes the beginning of a struct field.
859 * @param {string} name - The name of the field.
860 * @param {Thrift.Protocol.Type} fieldType - The data type of the field.
861 * @param {number} fieldId - The field's unique identifier.
862 */
863 writeFieldBegin: function(name, fieldType, fieldId) {
864 this.tpos.push(this.tstack.length);
865 this.tstack.push({ 'fieldId': '"' +
866 fieldId + '"', 'fieldType': Thrift.Protocol.Type[fieldType]
867 });
868
869 },
870
871 /**
872 * Serializes the end of a field.
873 */
874 writeFieldEnd: function() {
875 var value = this.tstack.pop();
876 var fieldInfo = this.tstack.pop();
877
878 this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' +
879 fieldInfo.fieldType + ':' + value + '}';
880 this.tpos.pop();
881 },
882
883 /**
884 * Serializes the end of the set of fields for a struct.
885 */
886 writeFieldStop: function() {
887 //na
888 },
889
890 /**
891 * Serializes the beginning of a map collection.
892 * @param {Thrift.Type} keyType - The data type of the key.
893 * @param {Thrift.Type} valType - The data type of the value.
894 * @param {number} [size] - The number of elements in the map (ignored).
895 */
896 writeMapBegin: function(keyType, valType, size) {
897 this.tpos.push(this.tstack.length);
898 this.tstack.push([Thrift.Protocol.Type[keyType],
899 Thrift.Protocol.Type[valType], 0]);
900 },
901
902 /**
903 * Serializes the end of a map.
904 */
905 writeMapEnd: function() {
906 var p = this.tpos.pop();
907
908 if (p == this.tstack.length) {
909 return;
910 }
911
912 if ((this.tstack.length - p - 1) % 2 !== 0) {
913 this.tstack.push('');
914 }
915
916 var size = (this.tstack.length - p - 1) / 2;
917
918 this.tstack[p][this.tstack[p].length - 1] = size;
919
920 var map = '}';
921 var first = true;
922 while (this.tstack.length > p + 1) {
923 var v = this.tstack.pop();
924 var k = this.tstack.pop();
925 if (first) {
926 first = false;
927 } else {
928 map = ',' + map;
929 }
930
931 if (! isNaN(k)) { k = '"' + k + '"'; } //json "keys" need to be strings
932 map = k + ':' + v + map;
933 }
934 map = '{' + map;
935
936 this.tstack[p].push(map);
937 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
938 },
939
940 /**
941 * Serializes the beginning of a list collection.
942 * @param {Thrift.Type} elemType - The data type of the elements.
943 * @param {number} size - The number of elements in the list.
944 */
945 writeListBegin: function(elemType, size) {
946 this.tpos.push(this.tstack.length);
947 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
948 },
949
950 /**
951 * Serializes the end of a list.
952 */
953 writeListEnd: function() {
954 var p = this.tpos.pop();
955
956 while (this.tstack.length > p + 1) {
957 var tmpVal = this.tstack[p + 1];
958 this.tstack.splice(p + 1, 1);
959 this.tstack[p].push(tmpVal);
960 }
961
962 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
963 },
964
965 /**
966 * Serializes the beginning of a set collection.
967 * @param {Thrift.Type} elemType - The data type of the elements.
968 * @param {number} size - The number of elements in the list.
969 */
970 writeSetBegin: function(elemType, size) {
971 this.tpos.push(this.tstack.length);
972 this.tstack.push([Thrift.Protocol.Type[elemType], size]);
973 },
974
975 /**
976 * Serializes the end of a set.
977 */
978 writeSetEnd: function() {
979 var p = this.tpos.pop();
980
981 while (this.tstack.length > p + 1) {
982 var tmpVal = this.tstack[p + 1];
983 this.tstack.splice(p + 1, 1);
984 this.tstack[p].push(tmpVal);
985 }
986
987 this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
988 },
989
990 /** Serializes a boolean */
991 writeBool: function(value) {
992 this.tstack.push(value ? 1 : 0);
993 },
994
995 /** Serializes a number */
996 writeByte: function(i8) {
997 this.tstack.push(i8);
998 },
999
1000 /** Serializes a number */
1001 writeI16: function(i16) {
1002 this.tstack.push(i16);
1003 },
1004
1005 /** Serializes a number */
1006 writeI32: function(i32) {
1007 this.tstack.push(i32);
1008 },
1009
1010 /** Serializes a number */
1011 writeI64: function(i64) {
1012 this.tstack.push(i64);
1013 },
1014
1015 /** Serializes a number */
1016 writeDouble: function(dbl) {
1017 this.tstack.push(dbl);
1018 },
1019
1020 /** Serializes a string */
1021 writeString: function(str) {
1022 // We do not encode uri components for wire transfer:
1023 if (str === null) {
1024 this.tstack.push(null);
1025 } else {
1026 // concat may be slower than building a byte buffer
1027 var escapedString = '';
1028 for (var i = 0; i < str.length; i++) {
1029 var ch = str.charAt(i); // a single double quote: "
1030 if (ch === '\"') {
1031 escapedString += '\\\"'; // write out as: \"
Roger Meier52744ee2014-03-12 09:38:42 +01001032 } else if (ch === '\\') { // a single backslash
Kazuki Matsudab909a382016-02-13 19:36:09 +09001033 escapedString += '\\\\'; // write out as double backslash
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001034 } else if (ch === '\b') { // a single backspace: invisible
1035 escapedString += '\\b'; // write out as: \b"
1036 } else if (ch === '\f') { // a single formfeed: invisible
1037 escapedString += '\\f'; // write out as: \f"
1038 } else if (ch === '\n') { // a single newline: invisible
1039 escapedString += '\\n'; // write out as: \n"
1040 } else if (ch === '\r') { // a single return: invisible
1041 escapedString += '\\r'; // write out as: \r"
1042 } else if (ch === '\t') { // a single tab: invisible
1043 escapedString += '\\t'; // write out as: \t"
1044 } else {
1045 escapedString += ch; // Else it need not be escaped
1046 }
1047 }
1048 this.tstack.push('"' + escapedString + '"');
1049 }
1050 },
1051
1052 /** Serializes a string */
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001053 writeBinary: function(binary) {
1054 var str = '';
1055 if (typeof binary == 'string') {
1056 str = binary;
1057 } else if (binary instanceof Uint8Array) {
1058 var arr = binary;
1059 for (var i = 0; i < arr.length; ++i) {
1060 str += String.fromCharCode(arr[i]);
1061 }
1062 } else {
1063 throw new TypeError('writeBinary only accepts String or Uint8Array.');
1064 }
1065 this.tstack.push('"' + btoa(str) + '"');
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001066 },
1067
1068 /**
1069 @class
1070 @name AnonReadMessageBeginReturn
1071 @property {string} fname - The name of the service method.
1072 @property {Thrift.MessageType} mtype - The type of message call.
1073 @property {number} rseqid - The sequence number of the message (0 in Thrift RPC).
1074 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001075 /**
1076 * Deserializes the beginning of a message.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001077 * @returns {AnonReadMessageBeginReturn}
1078 */
1079 readMessageBegin: function() {
1080 this.rstack = [];
1081 this.rpos = [];
1082
Roger Meier52744ee2014-03-12 09:38:42 +01001083 if (typeof JSON !== 'undefined' && typeof JSON.parse === 'function') {
1084 this.robj = JSON.parse(this.transport.readAll());
1085 } else if (typeof jQuery !== 'undefined') {
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001086 this.robj = jQuery.parseJSON(this.transport.readAll());
1087 } else {
1088 this.robj = eval(this.transport.readAll());
1089 }
1090
1091 var r = {};
1092 var version = this.robj.shift();
1093
1094 if (version != Thrift.Protocol.Version) {
1095 throw 'Wrong thrift protocol version: ' + version;
1096 }
1097
1098 r.fname = this.robj.shift();
1099 r.mtype = this.robj.shift();
1100 r.rseqid = this.robj.shift();
1101
1102
1103 //get to the main obj
1104 this.rstack.push(this.robj.shift());
1105
1106 return r;
1107 },
1108
1109 /** Deserializes the end of a message. */
1110 readMessageEnd: function() {
1111 },
1112
Kazuki Matsudab909a382016-02-13 19:36:09 +09001113 /**
1114 * Deserializes the beginning of a struct.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001115 * @param {string} [name] - The name of the struct (ignored)
1116 * @returns {object} - An object with an empty string fname property
Kazuki Matsudab909a382016-02-13 19:36:09 +09001117 */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001118 readStructBegin: function(name) {
1119 var r = {};
1120 r.fname = '';
1121
1122 //incase this is an array of structs
1123 if (this.rstack[this.rstack.length - 1] instanceof Array) {
1124 this.rstack.push(this.rstack[this.rstack.length - 1].shift());
1125 }
1126
1127 return r;
1128 },
1129
1130 /** Deserializes the end of a struct. */
1131 readStructEnd: function() {
1132 if (this.rstack[this.rstack.length - 2] instanceof Array) {
1133 this.rstack.pop();
1134 }
1135 },
1136
1137 /**
1138 @class
1139 @name AnonReadFieldBeginReturn
1140 @property {string} fname - The name of the field (always '').
1141 @property {Thrift.Type} ftype - The data type of the field.
1142 @property {number} fid - The unique identifier of the field.
1143 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001144 /**
1145 * Deserializes the beginning of a field.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001146 * @returns {AnonReadFieldBeginReturn}
1147 */
1148 readFieldBegin: function() {
1149 var r = {};
1150
1151 var fid = -1;
1152 var ftype = Thrift.Type.STOP;
1153
1154 //get a fieldId
1155 for (var f in (this.rstack[this.rstack.length - 1])) {
1156 if (f === null) {
1157 continue;
1158 }
1159
1160 fid = parseInt(f, 10);
1161 this.rpos.push(this.rstack.length);
1162
1163 var field = this.rstack[this.rstack.length - 1][fid];
1164
1165 //remove so we don't see it again
1166 delete this.rstack[this.rstack.length - 1][fid];
1167
1168 this.rstack.push(field);
1169
1170 break;
1171 }
1172
1173 if (fid != -1) {
1174
1175 //should only be 1 of these but this is the only
1176 //way to match a key
1177 for (var i in (this.rstack[this.rstack.length - 1])) {
1178 if (Thrift.Protocol.RType[i] === null) {
1179 continue;
1180 }
1181
1182 ftype = Thrift.Protocol.RType[i];
1183 this.rstack[this.rstack.length - 1] =
1184 this.rstack[this.rstack.length - 1][i];
1185 }
1186 }
1187
1188 r.fname = '';
1189 r.ftype = ftype;
1190 r.fid = fid;
1191
1192 return r;
1193 },
1194
1195 /** Deserializes the end of a field. */
1196 readFieldEnd: function() {
1197 var pos = this.rpos.pop();
1198
1199 //get back to the right place in the stack
1200 while (this.rstack.length > pos) {
1201 this.rstack.pop();
1202 }
1203
1204 },
1205
1206 /**
1207 @class
1208 @name AnonReadMapBeginReturn
1209 @property {Thrift.Type} ktype - The data type of the key.
1210 @property {Thrift.Type} vtype - The data type of the value.
1211 @property {number} size - The number of elements in the map.
1212 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001213 /**
1214 * Deserializes the beginning of a map.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001215 * @returns {AnonReadMapBeginReturn}
1216 */
1217 readMapBegin: function() {
1218 var map = this.rstack.pop();
Liangliang He5d6378f2014-08-19 18:25:37 +08001219 var first = map.shift();
1220 if (first instanceof Array) {
1221 this.rstack.push(map);
1222 map = first;
1223 first = map.shift();
1224 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001225
1226 var r = {};
Liangliang He5d6378f2014-08-19 18:25:37 +08001227 r.ktype = Thrift.Protocol.RType[first];
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001228 r.vtype = Thrift.Protocol.RType[map.shift()];
1229 r.size = map.shift();
1230
1231
1232 this.rpos.push(this.rstack.length);
1233 this.rstack.push(map.shift());
1234
1235 return r;
1236 },
1237
1238 /** Deserializes the end of a map. */
1239 readMapEnd: function() {
1240 this.readFieldEnd();
1241 },
1242
1243 /**
1244 @class
1245 @name AnonReadColBeginReturn
1246 @property {Thrift.Type} etype - The data type of the element.
1247 @property {number} size - The number of elements in the collection.
1248 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001249 /**
1250 * Deserializes the beginning of a list.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001251 * @returns {AnonReadColBeginReturn}
1252 */
1253 readListBegin: function() {
1254 var list = this.rstack[this.rstack.length - 1];
1255
1256 var r = {};
1257 r.etype = Thrift.Protocol.RType[list.shift()];
1258 r.size = list.shift();
1259
1260 this.rpos.push(this.rstack.length);
Henrique Mendonça15d90422015-06-25 22:31:41 +10001261 this.rstack.push(list.shift());
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001262
1263 return r;
1264 },
1265
1266 /** Deserializes the end of a list. */
1267 readListEnd: function() {
1268 this.readFieldEnd();
1269 },
1270
Kazuki Matsudab909a382016-02-13 19:36:09 +09001271 /**
1272 * Deserializes the beginning of a set.
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001273 * @returns {AnonReadColBeginReturn}
1274 */
1275 readSetBegin: function(elemType, size) {
1276 return this.readListBegin(elemType, size);
1277 },
1278
1279 /** Deserializes the end of a set. */
1280 readSetEnd: function() {
1281 return this.readListEnd();
1282 },
1283
Kazuki Matsudab909a382016-02-13 19:36:09 +09001284 /** Returns an object with a value property set to
1285 * False unless the next number in the protocol buffer
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +01001286 * is 1, in which case the value property is True */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001287 readBool: function() {
1288 var r = this.readI32();
1289
1290 if (r !== null && r.value == '1') {
1291 r.value = true;
1292 } else {
1293 r.value = false;
1294 }
1295
1296 return r;
1297 },
1298
Kazuki Matsudab909a382016-02-13 19:36:09 +09001299 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001300 next value found in the protocol buffer */
1301 readByte: function() {
1302 return this.readI32();
1303 },
1304
Kazuki Matsudab909a382016-02-13 19:36:09 +09001305 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001306 next value found in the protocol buffer */
1307 readI16: function() {
1308 return this.readI32();
1309 },
1310
Kazuki Matsudab909a382016-02-13 19:36:09 +09001311 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001312 next value found in the protocol buffer */
1313 readI32: function(f) {
1314 if (f === undefined) {
1315 f = this.rstack[this.rstack.length - 1];
1316 }
1317
1318 var r = {};
1319
1320 if (f instanceof Array) {
1321 if (f.length === 0) {
1322 r.value = undefined;
1323 } else {
1324 r.value = f.shift();
1325 }
1326 } else if (f instanceof Object) {
1327 for (var i in f) {
1328 if (i === null) {
1329 continue;
1330 }
1331 this.rstack.push(f[i]);
1332 delete f[i];
1333
1334 r.value = i;
1335 break;
1336 }
1337 } else {
1338 r.value = f;
1339 this.rstack.pop();
1340 }
1341
1342 return r;
1343 },
1344
Kazuki Matsudab909a382016-02-13 19:36:09 +09001345 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001346 next value found in the protocol buffer */
1347 readI64: function() {
1348 return this.readI32();
1349 },
1350
Kazuki Matsudab909a382016-02-13 19:36:09 +09001351 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001352 next value found in the protocol buffer */
1353 readDouble: function() {
1354 return this.readI32();
1355 },
1356
Kazuki Matsudab909a382016-02-13 19:36:09 +09001357 /** Returns the an object with a value property set to the
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001358 next value found in the protocol buffer */
1359 readString: function() {
1360 var r = this.readI32();
1361 return r;
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 readBinary: function() {
Nobuaki Sukegawa6defea52015-11-14 17:36:29 +09001367 var r = this.readI32();
1368 r.value = atob(r.value);
1369 return r;
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001370 },
1371
Kazuki Matsudab909a382016-02-13 19:36:09 +09001372 /**
Jens Geyer329d59a2014-06-19 22:11:53 +02001373 * Method to arbitrarily skip over data */
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001374 skip: function(type) {
Jens Geyer329d59a2014-06-19 22:11:53 +02001375 var ret, i;
1376 switch (type) {
1377 case Thrift.Type.STOP:
1378 return null;
1379
1380 case Thrift.Type.BOOL:
1381 return this.readBool();
1382
1383 case Thrift.Type.BYTE:
1384 return this.readByte();
1385
1386 case Thrift.Type.I16:
1387 return this.readI16();
1388
1389 case Thrift.Type.I32:
1390 return this.readI32();
1391
1392 case Thrift.Type.I64:
1393 return this.readI64();
1394
1395 case Thrift.Type.DOUBLE:
1396 return this.readDouble();
1397
1398 case Thrift.Type.STRING:
1399 return this.readString();
1400
1401 case Thrift.Type.STRUCT:
1402 this.readStructBegin();
1403 while (true) {
1404 ret = this.readFieldBegin();
1405 if (ret.ftype == Thrift.Type.STOP) {
1406 break;
1407 }
1408 this.skip(ret.ftype);
1409 this.readFieldEnd();
1410 }
1411 this.readStructEnd();
1412 return null;
1413
1414 case Thrift.Type.MAP:
1415 ret = this.readMapBegin();
1416 for (i = 0; i < ret.size; i++) {
1417 if (i > 0) {
1418 if (this.rstack.length > this.rpos[this.rpos.length - 1] + 1) {
1419 this.rstack.pop();
1420 }
1421 }
1422 this.skip(ret.ktype);
1423 this.skip(ret.vtype);
1424 }
1425 this.readMapEnd();
1426 return null;
1427
1428 case Thrift.Type.SET:
1429 ret = this.readSetBegin();
1430 for (i = 0; i < ret.size; i++) {
1431 this.skip(ret.etype);
1432 }
1433 this.readSetEnd();
1434 return null;
1435
1436 case Thrift.Type.LIST:
1437 ret = this.readListBegin();
1438 for (i = 0; i < ret.size; i++) {
1439 this.skip(ret.etype);
1440 }
1441 this.readListEnd();
1442 return null;
1443 }
Henrique Mendonça095ddb72013-09-20 19:38:03 +02001444 }
1445};
henrique5ba91f22013-12-20 21:13:13 +01001446
1447
1448/**
1449 * Initializes a MutilplexProtocol Implementation as a Wrapper for Thrift.Protocol
1450 * @constructor
1451 */
Kazuki Matsudab909a382016-02-13 19:36:09 +09001452Thrift.MultiplexProtocol = function(srvName, trans, strictRead, strictWrite) {
henrique5ba91f22013-12-20 21:13:13 +01001453 Thrift.Protocol.call(this, trans, strictRead, strictWrite);
1454 this.serviceName = srvName;
1455};
1456Thrift.inherits(Thrift.MultiplexProtocol, Thrift.Protocol, 'multiplexProtocol');
1457
1458/** Override writeMessageBegin method of prototype*/
Kazuki Matsudab909a382016-02-13 19:36:09 +09001459Thrift.MultiplexProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
henrique5ba91f22013-12-20 21:13:13 +01001460
1461 if (type === Thrift.MessageType.CALL || type === Thrift.MessageType.ONEWAY) {
Kazuki Matsudab909a382016-02-13 19:36:09 +09001462 Thrift.Protocol.prototype.writeMessageBegin.call(this, this.serviceName + ':' + name, type, seqid);
henrique5ba91f22013-12-20 21:13:13 +01001463 } else {
1464 Thrift.Protocol.prototype.writeMessageBegin.call(this, name, type, seqid);
1465 }
1466};
1467
Kazuki Matsudab909a382016-02-13 19:36:09 +09001468Thrift.Multiplexer = function() {
henrique5ba91f22013-12-20 21:13:13 +01001469 this.seqid = 0;
1470};
1471
1472/** Instantiates a multiplexed client for a specific service
1473 * @constructor
1474 * @param {String} serviceName - The transport to serialize to/from.
1475 * @param {Thrift.ServiceClient} SCl - The Service Client Class
1476 * @param {Thrift.Transport} transport - Thrift.Transport instance which provides remote host:port
1477 * @example
1478 * var mp = new Thrift.Multiplexer();
1479 * var transport = new Thrift.Transport("http://localhost:9090/foo.thrift");
1480 * var protocol = new Thrift.Protocol(transport);
1481 * var client = mp.createClient('AuthService', AuthServiceClient, transport);
1482*/
Kazuki Matsudab909a382016-02-13 19:36:09 +09001483Thrift.Multiplexer.prototype.createClient = function(serviceName, SCl, transport) {
henrique5ba91f22013-12-20 21:13:13 +01001484 if (SCl.Client) {
1485 SCl = SCl.Client;
1486 }
1487 var self = this;
Kazuki Matsudab909a382016-02-13 19:36:09 +09001488 SCl.prototype.new_seqid = function() {
henrique5ba91f22013-12-20 21:13:13 +01001489 self.seqid += 1;
1490 return self.seqid;
1491 };
1492 var client = new SCl(new Thrift.MultiplexProtocol(serviceName, transport));
1493
1494 return client;
1495};
1496
henriquea2de4102014-02-07 14:12:56 +01001497
henrique2a7dccc2014-03-07 22:16:51 +01001498
Henrique Mendonça15d90422015-06-25 22:31:41 +10001499var copyList, copyMap;
1500
1501copyList = function(lst, types) {
1502
1503 if (!lst) {return lst; }
1504
1505 var type;
1506
1507 if (types.shift === undefined) {
1508 type = types;
1509 }
1510 else {
1511 type = types[0];
1512 }
1513 var Type = type;
1514
1515 var len = lst.length, result = [], i, val;
1516 for (i = 0; i < len; i++) {
1517 val = lst[i];
1518 if (type === null) {
1519 result.push(val);
1520 }
1521 else if (type === copyMap || type === copyList) {
1522 result.push(type(val, types.slice(1)));
1523 }
1524 else {
1525 result.push(new Type(val));
1526 }
1527 }
1528 return result;
1529};
1530
Kazuki Matsudab909a382016-02-13 19:36:09 +09001531copyMap = function(obj, types) {
Henrique Mendonça15d90422015-06-25 22:31:41 +10001532
1533 if (!obj) {return obj; }
1534
1535 var type;
1536
1537 if (types.shift === undefined) {
1538 type = types;
1539 }
1540 else {
1541 type = types[0];
1542 }
1543 var Type = type;
1544
1545 var result = {}, val;
Kazuki Matsudab909a382016-02-13 19:36:09 +09001546 for (var prop in obj) {
1547 if (obj.hasOwnProperty(prop)) {
Henrique Mendonça15d90422015-06-25 22:31:41 +10001548 val = obj[prop];
1549 if (type === null) {
1550 result[prop] = val;
1551 }
1552 else if (type === copyMap || type === copyList) {
1553 result[prop] = type(val, types.slice(1));
1554 }
1555 else {
1556 result[prop] = new Type(val);
1557 }
1558 }
1559 }
1560 return result;
1561};
1562
1563Thrift.copyMap = copyMap;
1564Thrift.copyList = copyList;