Debian Codegraph @

closure-library/closure/goog/labs/net/webchannel/webchannelbase.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Base WebChannel implementation.
17 *
18 */
19
20
21 goog.provide('goog.labs.net.webChannel.WebChannelBase');
22
23 goog.require('goog.Uri');
24 goog.require('goog.array');
25 goog.require('goog.asserts');
26 goog.require('goog.async.run');
27 goog.require('goog.debug.TextFormatter');
28 goog.require('goog.json');
29 goog.require('goog.labs.net.webChannel.BaseTestChannel');
30 goog.require('goog.labs.net.webChannel.Channel');
31 goog.require('goog.labs.net.webChannel.ChannelRequest');
32 goog.require('goog.labs.net.webChannel.ConnectionState');
33 goog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');
34 goog.require('goog.labs.net.webChannel.WebChannelDebug');
35 goog.require('goog.labs.net.webChannel.Wire');
36 goog.require('goog.labs.net.webChannel.WireV8');
37 goog.require('goog.labs.net.webChannel.netUtils');
38 goog.require('goog.labs.net.webChannel.requestStats');
39 goog.require('goog.log');
40 goog.require('goog.net.WebChannel');
41 goog.require('goog.net.XhrIo');
42 goog.require('goog.net.rpc.HttpCors');
43 goog.require('goog.object');
44 goog.require('goog.string');
45 goog.require('goog.structs');
46 goog.require('goog.structs.CircularBuffer');
47
48 goog.scope(function() {
49 var WebChannel = goog.net.WebChannel;
50 var BaseTestChannel = goog.labs.net.webChannel.BaseTestChannel;
51 var ChannelRequest = goog.labs.net.webChannel.ChannelRequest;
52 var ConnectionState = goog.labs.net.webChannel.ConnectionState;
53 var ForwardChannelRequestPool =
54 goog.labs.net.webChannel.ForwardChannelRequestPool;
55 var WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;
56 var Wire = goog.labs.net.webChannel.Wire;
57 var WireV8 = goog.labs.net.webChannel.WireV8;
58 var netUtils = goog.labs.net.webChannel.netUtils;
59 var requestStats = goog.labs.net.webChannel.requestStats;
60
61 var httpCors = goog.module.get('goog.net.rpc.HttpCors');
62
63
64 /**
65 * This WebChannel implementation is branched off goog.net.BrowserChannel
66 * for now. Ongoing changes to goog.net.BrowserChannel will be back
67 * ported to this implementation as needed.
68 *
69 * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the
70 * WebChannel instance.
71 * @param {number=} opt_clientVersion An application-specific version number
72 * that is sent to the server when connected.
73 * @param {!ConnectionState=} opt_conn Previously determined connection
74 * conditions.
75 * @constructor
76 * @struct
77 * @implements {goog.labs.net.webChannel.Channel}
78 */
79 goog.labs.net.webChannel.WebChannelBase = function(
80 opt_options, opt_clientVersion, opt_conn) {
81 /**
82 * The client library version (capabilities).
83 * @private {number}
84 */
85 this.clientVersion_ = opt_clientVersion || 0;
86
87 /**
88 * The server library version (capabilities).
89 * @private {number}
90 */
91 this.serverVersion_ = 0;
92
93
94 /**
95 * An array of queued maps that need to be sent to the server.
96 * @private {!Array<Wire.QueuedMap>}
97 */
98 this.outgoingMaps_ = [];
99
100 /**
101 * The channel debug used for logging
102 * @private {!WebChannelDebug}
103 */
104 this.channelDebug_ = new WebChannelDebug();
105
106 /**
107 * Previous connectivity test results.
108 * @private {!ConnectionState}
109 */
110 this.connState_ = opt_conn || new ConnectionState();
111
112 /**
113 * Extra HTTP headers to add to all the requests sent to the server.
114 * @private {Object}
115 */
116 this.extraHeaders_ = null;
117
118 /**
119 * Extra HTTP headers to add to the init request(s) sent to the server.
120 * @private {Object}
121 */
122 this.initHeaders_ = null;
123
124 /**
125 * @private {?string} The URL param name to overwrite custom HTTP headers
126 * to bypass CORS preflight.
127 */
128 this.httpHeadersOverwriteParam_ = null;
129
130 /**
131 * Extra parameters to add to all the requests sent to the server.
132 * @private {Object}
133 */
134 this.extraParams_ = null;
135
136 /**
137 * Parameter name for the http session id.
138 * @private {?string}
139 */
140 this.httpSessionIdParam_ = null;
141
142 /**
143 * The http session id, to be sent with httpSessionIdParam_ with each
144 * request after the initial handshake.
145 * @private {?string}
146 */
147 this.httpSessionId_ = null;
148
149 /**
150 * The ChannelRequest object for the backchannel.
151 * @private {ChannelRequest}
152 */
153 this.backChannelRequest_ = null;
154
155 /**
156 * The relative path (in the context of the the page hosting the browser
157 * channel) for making requests to the server.
158 * @private {?string}
159 */
160 this.path_ = null;
161
162 /**
163 * The absolute URI for the forwardchannel request.
164 * @private {goog.Uri}
165 */
166 this.forwardChannelUri_ = null;
167
168 /**
169 * The absolute URI for the backchannel request.
170 * @private {goog.Uri}
171 */
172 this.backChannelUri_ = null;
173
174 /**
175 * A subdomain prefix for using a subdomain in IE for the backchannel
176 * requests.
177 * @private {?string}
178 */
179 this.hostPrefix_ = null;
180
181 /**
182 * Whether we allow the use of a subdomain in IE for the backchannel requests.
183 * @private {boolean}
184 */
185 this.allowHostPrefix_ = true;
186
187 /**
188 * The next id to use for the RID (request identifier) parameter. This
189 * identifier uniquely identifies the forward channel request.
190 * @private {number}
191 */
192 this.nextRid_ = 0;
193
194 /**
195 * The id to use for the next outgoing map. This identifier uniquely
196 * identifies a sent map.
197 * @private {number}
198 */
199 this.nextMapId_ = 0;
200
201 /**
202 * Whether to fail forward-channel requests after one try or a few tries.
203 * @private {boolean}
204 */
205 this.failFast_ = false;
206
207 /**
208 * The handler that receive callbacks for state changes and data.
209 * @private {goog.labs.net.webChannel.WebChannelBase.Handler}
210 */
211 this.handler_ = null;
212
213 /**
214 * Timer identifier for asynchronously making a forward channel request.
215 * @private {?number}
216 */
217 this.forwardChannelTimerId_ = null;
218
219 /**
220 * Timer identifier for asynchronously making a back channel request.
221 * @private {?number}
222 */
223 this.backChannelTimerId_ = null;
224
225 /**
226 * Timer identifier for the timer that waits for us to retry the backchannel
227 * in the case where it is dead and no longer receiving data.
228 * @private {?number}
229 */
230 this.deadBackChannelTimerId_ = null;
231
232 /**
233 * The TestChannel object which encapsulates the logic for determining
234 * interesting network conditions about the client.
235 * @private {BaseTestChannel}
236 */
237 this.connectionTest_ = null;
238
239 /**
240 * Whether the client's network conditions can support chunked responses.
241 * @private {?boolean}
242 */
243 this.useChunked_ = null;
244
245 /**
246 * Whether chunked mode is allowed. In certain debugging situations, it's
247 * useful to disable this.
248 * @private {boolean}
249 */
250 this.allowChunkedMode_ = true;
251
252 /**
253 * The array identifier of the last array received from the server for the
254 * backchannel request.
255 * @private {number}
256 */
257 this.lastArrayId_ = -1;
258
259 /**
260 * The array id of the last array sent by the server that we know about.
261 * @private {number}
262 */
263 this.lastPostResponseArrayId_ = -1;
264
265 /**
266 * The last status code received.
267 * @private {number}
268 */
269 this.lastStatusCode_ = -1;
270
271 /**
272 * Number of times we have retried the current forward channel request.
273 * @private {number}
274 */
275 this.forwardChannelRetryCount_ = 0;
276
277 /**
278 * Number of times in a row that we have retried the current back channel
279 * request and received no data.
280 * @private {number}
281 */
282 this.backChannelRetryCount_ = 0;
283
284 /**
285 * The attempt id for the current back channel request. Starts at 1 and
286 * increments for each reconnect. The server uses this to log if our
287 * connection is flaky or not.
288 * @private {number}
289 */
290 this.backChannelAttemptId_ = 0;
291
292 /**
293 * The base part of the time before firing next retry request. Default is 5
294 * seconds. Note that a random delay is added (see {@link retryDelaySeedMs_})
295 * for all retries, and linear backoff is applied to the sum for subsequent
296 * retries.
297 * @private {number}
298 */
299 this.baseRetryDelayMs_ = 5 * 1000;
300
301 /**
302 * A random time between 0 and this number of MS is added to the
303 * {@link baseRetryDelayMs_}. Default is 10 seconds.
304 * @private {number}
305 */
306 this.retryDelaySeedMs_ = 10 * 1000;
307
308 /**
309 * Maximum number of attempts to connect to the server for forward channel
310 * requests. Defaults to 2.
311 * @private {number}
312 */
313 this.forwardChannelMaxRetries_ = 2;
314
315 /**
316 * The timeout in milliseconds for a forward channel request. Defaults to 20
317 * seconds. Note that part of this timeout can be randomized.
318 * @private {number}
319 */
320 this.forwardChannelRequestTimeoutMs_ = 20 * 1000;
321
322 /**
323 * The timeout in milliseconds for a back channel request. Defaults to using
324 * the timeout configured in ChannelRequest (45s). If server-side
325 * keepaliveInterval is known to the client, set the backchannel request
326 * timeout to 1.5 * keepaliveInterval (ms).
327 *
328 * @private {number|undefined}
329 */
330 this.backChannelRequestTimeoutMs_ = undefined;
331
332 /**
333 * A throttle time in ms for readystatechange events for the backchannel.
334 * Useful for throttling when ready state is INTERACTIVE (partial data).
335 *
336 * This throttle is useful if the server sends large data chunks down the
337 * backchannel. It prevents examining XHR partial data on every readystate
338 * change event. This is useful because large chunks can trigger hundreds
339 * of readystatechange events, each of which takes ~5ms or so to handle,
340 * in turn making the UI unresponsive for a significant period.
341 *
342 * If set to zero no throttle is used.
343 * @private {number}
344 */
345 this.readyStateChangeThrottleMs_ = 0;
346
347 /**
348 * Whether cross origin requests are supported for the channel.
349 *
350 * See {@link goog.net.XhrIo#setWithCredentials}.
351 * @private {boolean}
352 */
353 this.supportsCrossDomainXhrs_ =
354 (opt_options && opt_options.supportsCrossDomainXhr) || false;
355
356 /**
357 * The current session id.
358 * @private {string}
359 */
360 this.sid_ = '';
361
362 /**
363 * The current ChannelRequest pool for the forward channel.
364 * @private {!ForwardChannelRequestPool}
365 */
366 this.forwardChannelRequestPool_ = new ForwardChannelRequestPool(
367 opt_options && opt_options.concurrentRequestLimit);
368
369 /**
370 * The V8 codec.
371 * @private {!WireV8}
372 */
373 this.wireCodec_ = new WireV8();
374
375 /**
376 * Whether to run the channel test as a background process to not block
377 * the OPEN event.
378 *
379 * @private {boolean}
380 */
381 this.backgroundChannelTest_ =
382 opt_options && goog.isDef(opt_options.backgroundChannelTest) ?
383 opt_options.backgroundChannelTest :
384 true;
385
386 /**
387 * Whether to turn on the fast handshake behavior.
388 *
389 * @private {boolean}
390 */
391 this.fastHandshake_ = (opt_options && opt_options.fastHandshake) || false;
392
393 if (opt_options && opt_options.disableRedact) {
394 this.channelDebug_.disableRedact();
395 }
396 };
397
398 var WebChannelBase = goog.labs.net.webChannel.WebChannelBase;
399
400
401 /**
402 * The channel version that we negotiated with the server for this session.
403 * Starts out as the version we request, and then is changed to the negotiated
404 * version after the initial open.
405 * @private {number}
406 */
407 WebChannelBase.prototype.channelVersion_ = Wire.LATEST_CHANNEL_VERSION;
408
409
410 /**
411 * Enum type for the channel state machine.
412 * @enum {number}
413 */
414 WebChannelBase.State = {
415 /** The channel is closed. */
416 CLOSED: 0,
417
418 /** The channel has been initialized but hasn't yet initiated a connection. */
419 INIT: 1,
420
421 /** The channel is in the process of opening a connection to the server. */
422 OPENING: 2,
423
424 /** The channel is open. */
425 OPENED: 3
426 };
427
428
429 /**
430 * The current state of the WebChannel.
431 * @private {!WebChannelBase.State}
432 */
433 WebChannelBase.prototype.state_ = WebChannelBase.State.INIT;
434
435
436 /**
437 * The timeout in milliseconds for a forward channel request.
438 * @type {number}
439 */
440 WebChannelBase.FORWARD_CHANNEL_RETRY_TIMEOUT = 20 * 1000;
441
442
443 /**
444 * Maximum number of attempts to connect to the server for back channel
445 * requests.
446 * @type {number}
447 */
448 WebChannelBase.BACK_CHANNEL_MAX_RETRIES = 3;
449
450
451 /**
452 * A number in MS of how long we guess the maxmium amount of time a round trip
453 * to the server should take. In the future this could be substituted with a
454 * real measurement of the RTT.
455 * @type {number}
456 */
457 WebChannelBase.RTT_ESTIMATE = 3 * 1000;
458
459
460 /**
461 * When retrying for an inactive channel, we will multiply the total delay by
462 * this number.
463 * @type {number}
464 */
465 WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR = 2;
466
467
468 /**
469 * Enum type for identifying an error.
470 * @enum {number}
471 */
472 WebChannelBase.Error = {
473 /** Value that indicates no error has occurred. */
474 OK: 0,
475
476 /** An error due to a request failing. */
477 REQUEST_FAILED: 2,
478
479 /** An error due to the user being logged out. */
480 LOGGED_OUT: 4,
481
482 /** An error due to server response which contains no data. */
483 NO_DATA: 5,
484
485 /** An error due to a server response indicating an unknown session id */
486 UNKNOWN_SESSION_ID: 6,
487
488 /** An error due to a server response requesting to stop the channel. */
489 STOP: 7,
490
491 /** A general network error. */
492 NETWORK: 8,
493
494 /** An error due to bad data being returned from the server. */
495 BAD_DATA: 10,
496
497 /** An error due to a response that is not parsable. */
498 BAD_RESPONSE: 11
499 };
500
501
502 /**
503 * Internal enum type for the two channel types.
504 * @enum {number}
505 * @private
506 */
507 WebChannelBase.ChannelType_ = {
508 FORWARD_CHANNEL: 1,
509
510 BACK_CHANNEL: 2
511 };
512
513
514 /**
515 * The maximum number of maps that can be sent in one POST. Should match
516 * MAX_MAPS_PER_REQUEST on the server code.
517 * @type {number}
518 * @private
519 */
520 WebChannelBase.MAX_MAPS_PER_REQUEST_ = 1000;
521
522
523 /**
524 * A guess at a cutoff at which to no longer assume the backchannel is dead
525 * when we are slow to receive data. Number in bytes.
526 *
527 * Assumption: The worst bandwidth we work on is 50 kilobits/sec
528 * 50kbits/sec * (1 byte / 8 bits) * 6 sec dead backchannel timeout
529 * @type {number}
530 */
531 WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF = 37500;
532
533
534 /**
535 * @return {!ForwardChannelRequestPool} The forward channel request pool.
536 */
537 WebChannelBase.prototype.getForwardChannelRequestPool = function() {
538 return this.forwardChannelRequestPool_;
539 };
540
541
542 /**
543 * @return {!Object} The codec object, to be used for the test channel.
544 */
545 WebChannelBase.prototype.getWireCodec = function() {
546 return this.wireCodec_;
547 };
548
549
550 /**
551 * Returns the logger.
552 *
553 * @return {!WebChannelDebug} The channel debug object.
554 */
555 WebChannelBase.prototype.getChannelDebug = function() {
556 return this.channelDebug_;
557 };
558
559
560 /**
561 * Sets the logger.
562 *
563 * @param {!WebChannelDebug} channelDebug The channel debug object.
564 */
565 WebChannelBase.prototype.setChannelDebug = function(channelDebug) {
566 this.channelDebug_ = channelDebug;
567 };
568
569
570 /**
571 * Starts the channel. This initiates connections to the server.
572 *
573 * @param {string} testPath The path for the test connection.
574 * @param {string} channelPath The path for the channel connection.
575 * @param {!Object=} opt_extraParams Extra parameter keys and values to add to
576 * the requests.
577 * @param {string=} opt_oldSessionId Session ID from a previous session.
578 * @param {number=} opt_oldArrayId The last array ID from a previous session.
579 */
580 WebChannelBase.prototype.connect = function(
581 testPath, channelPath, opt_extraParams, opt_oldSessionId, opt_oldArrayId) {
582 this.channelDebug_.debug('connect()');
583
584 requestStats.notifyStatEvent(requestStats.Stat.CONNECT_ATTEMPT);
585
586 this.path_ = channelPath;
587 this.extraParams_ = opt_extraParams || {};
588
589 // Attach parameters about the previous session if reconnecting.
590 if (opt_oldSessionId && goog.isDef(opt_oldArrayId)) {
591 this.extraParams_['OSID'] = opt_oldSessionId;
592 this.extraParams_['OAID'] = opt_oldArrayId;
593 }
594
595 if (this.backgroundChannelTest_) {
596 this.channelDebug_.debug('connect() bypassed channel-test.');
597 this.connState_.handshakeResult = [];
598 this.connState_.bufferingProxyResult = false;
599
600 // TODO(user): merge states with background channel test
601 // requestStats.setTimeout(goog.bind(this.connectTest_, this, testPath), 0);
602 // this.connectChannel_();
603 }
604
605 this.connectTest_(testPath);
606 };
607
608
609 /**
610 * Disconnects and closes the channel.
611 */
612 WebChannelBase.prototype.disconnect = function() {
613 this.channelDebug_.debug('disconnect()');
614
615 this.cancelRequests_();
616
617 if (this.state_ == WebChannelBase.State.OPENED) {
618 var rid = this.nextRid_++;
619 var uri = this.forwardChannelUri_.clone();
620 uri.setParameterValue('SID', this.sid_);
621 uri.setParameterValue('RID', rid);
622 uri.setParameterValue('TYPE', 'terminate');
623
624 // Add the reconnect parameters.
625 this.addAdditionalParams_(uri);
626
627 var request = ChannelRequest.createChannelRequest(
628 this, this.channelDebug_, this.sid_, rid);
629 request.sendCloseRequest(uri);
630 }
631
632 this.onClose_();
633 };
634
635
636 /**
637 * Returns the session id of the channel. Only available after the
638 * channel has been opened.
639 * @return {string} Session ID.
640 */
641 WebChannelBase.prototype.getSessionId = function() {
642 return this.sid_;
643 };
644
645
646 /**
647 * Starts the test channel to determine network conditions.
648 *
649 * @param {string} testPath The relative PATH for the test connection.
650 * @private
651 */
652 WebChannelBase.prototype.connectTest_ = function(testPath) {
653 this.channelDebug_.debug('connectTest_()');
654 if (!this.okToMakeRequest_()) {
655 return; // channel is cancelled
656 }
657 this.connectionTest_ = new BaseTestChannel(this, this.channelDebug_);
658
659 if (this.httpHeadersOverwriteParam_ === null) {
660 this.connectionTest_.setExtraHeaders(this.extraHeaders_);
661 }
662
663 var urlPath = testPath;
664 if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {
665 urlPath = httpCors.setHttpHeadersWithOverwriteParam(
666 testPath, this.httpHeadersOverwriteParam_, this.extraHeaders_);
667 }
668
669 this.connectionTest_.connect(/** @type {string} */ (urlPath));
670 };
671
672
673 /**
674 * Starts the regular channel which is run after the test channel is complete.
675 * @private
676 */
677 WebChannelBase.prototype.connectChannel_ = function() {
678 this.channelDebug_.debug('connectChannel_()');
679 this.ensureInState_(WebChannelBase.State.INIT, WebChannelBase.State.CLOSED);
680 this.forwardChannelUri_ =
681 this.getForwardChannelUri(/** @type {string} */ (this.path_));
682 this.ensureForwardChannel_();
683 };
684
685
686 /**
687 * Cancels all outstanding requests.
688 * @private
689 */
690 WebChannelBase.prototype.cancelRequests_ = function() {
691 if (this.connectionTest_) {
692 this.connectionTest_.abort();
693 this.connectionTest_ = null;
694 }
695
696 if (this.backChannelRequest_) {
697 this.backChannelRequest_.cancel();
698 this.backChannelRequest_ = null;
699 }
700
701 if (this.backChannelTimerId_) {
702 goog.global.clearTimeout(this.backChannelTimerId_);
703 this.backChannelTimerId_ = null;
704 }
705
706 this.clearDeadBackchannelTimer_();
707
708 this.forwardChannelRequestPool_.cancel();
709
710 if (this.forwardChannelTimerId_) {
711 goog.global.clearTimeout(this.forwardChannelTimerId_);
712 this.forwardChannelTimerId_ = null;
713 }
714 };
715
716
717 /**
718 * Returns the extra HTTP headers to add to all the requests sent to the server.
719 *
720 * @return {Object} The HTTP headers, or null.
721 */
722 WebChannelBase.prototype.getExtraHeaders = function() {
723 return this.extraHeaders_;
724 };
725
726
727 /**
728 * Sets extra HTTP headers to add to all the requests sent to the server.
729 *
730 * @param {Object} extraHeaders The HTTP headers, or null.
731 */
732 WebChannelBase.prototype.setExtraHeaders = function(extraHeaders) {
733 this.extraHeaders_ = extraHeaders;
734 };
735
736
737 /**
738 * Returns the extra HTTP headers to add to the init requests
739 * sent to the server.
740 *
741 * @return {Object} The HTTP headers, or null.
742 */
743 WebChannelBase.prototype.getInitHeaders = function() {
744 return this.initHeaders_;
745 };
746
747
748 /**
749 * Sets extra HTTP headers to add to the init requests sent to the server.
750 *
751 * @param {Object} initHeaders The HTTP headers, or null.
752 */
753 WebChannelBase.prototype.setInitHeaders = function(initHeaders) {
754 this.initHeaders_ = initHeaders;
755 };
756
757
758 /**
759 * Sets the URL param name to overwrite custom HTTP headers.
760 *
761 * @param {string} httpHeadersOverwriteParam The URL param name.
762 */
763 WebChannelBase.prototype.setHttpHeadersOverwriteParam = function(
764 httpHeadersOverwriteParam) {
765 this.httpHeadersOverwriteParam_ = httpHeadersOverwriteParam;
766 };
767
768
769 /**
770 * @override
771 */
772 WebChannelBase.prototype.setHttpSessionIdParam = function(httpSessionIdParam) {
773 this.httpSessionIdParam_ = httpSessionIdParam;
774 };
775
776
777 /**
778 * @override
779 */
780 WebChannelBase.prototype.getHttpSessionIdParam = function() {
781 return this.httpSessionIdParam_;
782 };
783
784
785 /**
786 * @override
787 */
788 WebChannelBase.prototype.setHttpSessionId = function(httpSessionId) {
789 this.httpSessionId_ = httpSessionId;
790 };
791
792
793 /**
794 * @override
795 */
796 WebChannelBase.prototype.getHttpSessionId = function() {
797 return this.httpSessionId_;
798 };
799
800
801 /**
802 * @override
803 */
804 WebChannelBase.prototype.getBackgroundChannelTest = function() {
805 return this.backgroundChannelTest_;
806 };
807
808
809 /**
810 * Sets the throttle for handling onreadystatechange events for the request.
811 *
812 * @param {number} throttle The throttle in ms. A value of zero indicates
813 * no throttle.
814 */
815 WebChannelBase.prototype.setReadyStateChangeThrottle = function(throttle) {
816 this.readyStateChangeThrottleMs_ = throttle;
817 };
818
819
820 /**
821 * Sets whether cross origin requests are supported for the channel.
822 *
823 * Setting this allows the creation of requests to secondary domains and
824 * sends XHRs with the CORS withCredentials bit set to true.
825 *
826 * In order for cross-origin requests to work, the server will also need to set
827 * CORS response headers as per:
828 * https://developer.mozilla.org/en-US/docs/HTTP_access_control
829 *
830 * See {@link goog.net.XhrIo#setWithCredentials}.
831 * @param {boolean} supportCrossDomain Whether cross domain XHRs are supported.
832 */
833 WebChannelBase.prototype.setSupportsCrossDomainXhrs = function(
834 supportCrossDomain) {
835 this.supportsCrossDomainXhrs_ = supportCrossDomain;
836 };
837
838
839 /**
840 * Returns the handler used for channel callback events.
841 *
842 * @return {WebChannelBase.Handler} The handler.
843 */
844 WebChannelBase.prototype.getHandler = function() {
845 return this.handler_;
846 };
847
848
849 /**
850 * Sets the handler used for channel callback events.
851 * @param {WebChannelBase.Handler} handler The handler to set.
852 */
853 WebChannelBase.prototype.setHandler = function(handler) {
854 this.handler_ = handler;
855 };
856
857
858 /**
859 * Returns whether the channel allows the use of a subdomain. There may be
860 * cases where this isn't allowed.
861 * @return {boolean} Whether a host prefix is allowed.
862 */
863 WebChannelBase.prototype.getAllowHostPrefix = function() {
864 return this.allowHostPrefix_;
865 };
866
867
868 /**
869 * Sets whether the channel allows the use of a subdomain. There may be cases
870 * where this isn't allowed, for example, logging in with troutboard where
871 * using a subdomain causes Apache to force the user to authenticate twice.
872 * @param {boolean} allowHostPrefix Whether a host prefix is allowed.
873 */
874 WebChannelBase.prototype.setAllowHostPrefix = function(allowHostPrefix) {
875 this.allowHostPrefix_ = allowHostPrefix;
876 };
877
878
879 /**
880 * Returns whether the channel is buffered or not. This state is valid for
881 * querying only after the test connection has completed. This may be
882 * queried in the WebChannelBase.okToMakeRequest() callback.
883 * A channel may be buffered if the test connection determines that
884 * a chunked response could not be sent down within a suitable time.
885 * @return {boolean} Whether the channel is buffered.
886 */
887 WebChannelBase.prototype.isBuffered = function() {
888 return !this.useChunked_;
889 };
890
891
892 /**
893 * Returns whether chunked mode is allowed. In certain debugging situations,
894 * it's useful for the application to have a way to disable chunked mode for a
895 * user.
896
897 * @return {boolean} Whether chunked mode is allowed.
898 */
899 WebChannelBase.prototype.getAllowChunkedMode = function() {
900 return this.allowChunkedMode_;
901 };
902
903
904 /**
905 * Sets whether chunked mode is allowed. In certain debugging situations, it's
906 * useful for the application to have a way to disable chunked mode for a user.
907 * @param {boolean} allowChunkedMode Whether chunked mode is allowed.
908 */
909 WebChannelBase.prototype.setAllowChunkedMode = function(allowChunkedMode) {
910 this.allowChunkedMode_ = allowChunkedMode;
911 };
912
913
914 /**
915 * Sends a request to the server. The format of the request is a Map data
916 * structure of key/value pairs. These maps are then encoded in a format
917 * suitable for the wire and then reconstituted as a Map data structure that
918 * the server can process.
919 * @param {!Object|!goog.structs.Map} map The map to send.
920 * @param {!Object=} opt_context The context associated with the map.
921 */
922 WebChannelBase.prototype.sendMap = function(map, opt_context) {
923 goog.asserts.assert(
924 this.state_ != WebChannelBase.State.CLOSED,
925 'Invalid operation: sending map when state is closed');
926
927 // We can only send 1000 maps per POST, but typically we should never have
928 // that much to send, so warn if we exceed that (we still send all the maps).
929 if (this.outgoingMaps_.length == WebChannelBase.MAX_MAPS_PER_REQUEST_) {
930 // severe() is temporary so that we get these uploaded and can figure out
931 // what's causing them. Afterwards can change to warning().
932 this.channelDebug_.severe(function() {
933 return 'Already have ' + WebChannelBase.MAX_MAPS_PER_REQUEST_ +
934 ' queued maps upon queueing ' + goog.json.serialize(map);
935 });
936 }
937
938 this.outgoingMaps_.push(
939 new Wire.QueuedMap(this.nextMapId_++, map, opt_context));
940
941 // Messages need be buffered during OPENING to avoid server-side race
942 if (this.state_ == WebChannelBase.State.OPENED) {
943 this.ensureForwardChannel_();
944 }
945 };
946
947
948 /**
949 * When set to true, this changes the behavior of the forward channel so it
950 * will not retry requests; it will fail after one network failure, and if
951 * there was already one network failure, the request will fail immediately.
952 * @param {boolean} failFast Whether or not to fail fast.
953 */
954 WebChannelBase.prototype.setFailFast = function(failFast) {
955 this.failFast_ = failFast;
956 this.channelDebug_.info('setFailFast: ' + failFast);
957 if ((this.forwardChannelRequestPool_.hasPendingRequest() ||
958 this.forwardChannelTimerId_) &&
959 this.forwardChannelRetryCount_ > this.getForwardChannelMaxRetries()) {
960 var self = this;
961 this.channelDebug_.info(function() {
962 return 'Retry count ' + self.forwardChannelRetryCount_ +
963 ' > new maxRetries ' + self.getForwardChannelMaxRetries() +
964 '. Fail immediately!';
965 });
966
967 if (!this.forwardChannelRequestPool_.forceComplete(
968 goog.bind(this.onRequestComplete, this))) {
969 // i.e., this.forwardChannelTimerId_
970 goog.global.clearTimeout(this.forwardChannelTimerId_);
971 this.forwardChannelTimerId_ = null;
972 // The error code from the last failed request is gone, so just use a
973 // generic one.
974 this.signalError_(WebChannelBase.Error.REQUEST_FAILED);
975 }
976 }
977 };
978
979
980 /**
981 * @return {number} The max number of forward-channel retries, which will be 0
982 * in fail-fast mode.
983 */
984 WebChannelBase.prototype.getForwardChannelMaxRetries = function() {
985 return this.failFast_ ? 0 : this.forwardChannelMaxRetries_;
986 };
987
988
989 /**
990 * Sets the maximum number of attempts to connect to the server for forward
991 * channel requests.
992 * @param {number} retries The maximum number of attempts.
993 */
994 WebChannelBase.prototype.setForwardChannelMaxRetries = function(retries) {
995 this.forwardChannelMaxRetries_ = retries;
996 };
997
998
999 /**
1000 * Sets the timeout for a forward channel request.
1001 * @param {number} timeoutMs The timeout in milliseconds.
1002 */
1003 WebChannelBase.prototype.setForwardChannelRequestTimeout = function(timeoutMs) {
1004 this.forwardChannelRequestTimeoutMs_ = timeoutMs;
1005 };
1006
1007
1008 /**
1009 * @return {number} The max number of back-channel retries, which is a constant.
1010 */
1011 WebChannelBase.prototype.getBackChannelMaxRetries = function() {
1012 // Back-channel retries is a constant.
1013 return WebChannelBase.BACK_CHANNEL_MAX_RETRIES;
1014 };
1015
1016
1017 /**
1018 * @override
1019 */
1020 WebChannelBase.prototype.isClosed = function() {
1021 return this.state_ == WebChannelBase.State.CLOSED;
1022 };
1023
1024
1025 /**
1026 * Returns the channel state.
1027 * @return {WebChannelBase.State} The current state of the channel.
1028 */
1029 WebChannelBase.prototype.getState = function() {
1030 return this.state_;
1031 };
1032
1033
1034 /**
1035 * Return the last status code received for a request.
1036 * @return {number} The last status code received for a request.
1037 */
1038 WebChannelBase.prototype.getLastStatusCode = function() {
1039 return this.lastStatusCode_;
1040 };
1041
1042
1043 /**
1044 * @return {number} The last array id received.
1045 */
1046 WebChannelBase.prototype.getLastArrayId = function() {
1047 return this.lastArrayId_;
1048 };
1049
1050
1051 /**
1052 * Returns whether there are outstanding requests servicing the channel.
1053 * @return {boolean} true if there are outstanding requests.
1054 */
1055 WebChannelBase.prototype.hasOutstandingRequests = function() {
1056 return this.getOutstandingRequests_() != 0;
1057 };
1058
1059
1060 /**
1061 * Returns the number of outstanding requests.
1062 * @return {number} The number of outstanding requests to the server.
1063 * @private
1064 */
1065 WebChannelBase.prototype.getOutstandingRequests_ = function() {
1066 var count = 0;
1067 if (this.backChannelRequest_) {
1068 count++;
1069 }
1070 count += this.forwardChannelRequestPool_.getRequestCount();
1071 return count;
1072 };
1073
1074
1075 /**
1076 * Ensures that a forward channel request is scheduled.
1077 * @private
1078 */
1079 WebChannelBase.prototype.ensureForwardChannel_ = function() {
1080 if (this.forwardChannelRequestPool_.isFull()) {
1081 // enough connection in process - no need to start a new request
1082 return;
1083 }
1084
1085 if (this.forwardChannelTimerId_) {
1086 // no need to start a new request - one is already scheduled
1087 return;
1088 }
1089
1090 this.forwardChannelTimerId_ = requestStats.setTimeout(
1091 goog.bind(this.onStartForwardChannelTimer_, this), 0);
1092 this.forwardChannelRetryCount_ = 0;
1093 };
1094
1095
1096 /**
1097 * Schedules a forward-channel retry for the specified request, unless the max
1098 * retries has been reached.
1099 * @param {!ChannelRequest} request The failed request to retry.
1100 * @return {boolean} true iff a retry was scheduled.
1101 * @private
1102 */
1103 WebChannelBase.prototype.maybeRetryForwardChannel_ = function(request) {
1104 if (this.forwardChannelRequestPool_.getRequestCount() >=
1105 this.forwardChannelRequestPool_.getMaxSize() -
1106 (this.forwardChannelTimerId_ ? 1 : 0)) {
1107 // Should be impossible to be called in this state.
1108 this.channelDebug_.severe('Unexpected retry request is scheduled.');
1109 return false;
1110 }
1111
1112 if (this.forwardChannelTimerId_) {
1113 this.channelDebug_.debug(
1114 'Use the retry request that is already scheduled.');
1115 this.outgoingMaps_ =
1116 request.getPendingMessages().concat(this.outgoingMaps_);
1117 return true;
1118 }
1119
1120 // No retry for open_() and fail-fast
1121 if (this.state_ == WebChannelBase.State.INIT ||
1122 this.state_ == WebChannelBase.State.OPENING ||
1123 (this.forwardChannelRetryCount_ >= this.getForwardChannelMaxRetries())) {
1124 return false;
1125 }
1126
1127 this.channelDebug_.debug('Going to retry POST');
1128
1129 this.forwardChannelTimerId_ = requestStats.setTimeout(
1130 goog.bind(this.onStartForwardChannelTimer_, this, request),
1131 this.getRetryTime_(this.forwardChannelRetryCount_));
1132 this.forwardChannelRetryCount_++;
1133 return true;
1134 };
1135
1136
1137 /**
1138 * Timer callback for ensureForwardChannel
1139 * @param {ChannelRequest=} opt_retryRequest A failed request
1140 * to retry.
1141 * @private
1142 */
1143 WebChannelBase.prototype.onStartForwardChannelTimer_ = function(
1144 opt_retryRequest) {
1145 this.forwardChannelTimerId_ = null;
1146 this.startForwardChannel_(opt_retryRequest);
1147 };
1148
1149
1150 /**
1151 * Begins a new forward channel operation to the server.
1152 * @param {ChannelRequest=} opt_retryRequest A failed request to retry.
1153 * @private
1154 */
1155 WebChannelBase.prototype.startForwardChannel_ = function(opt_retryRequest) {
1156 this.channelDebug_.debug('startForwardChannel_');
1157 if (!this.okToMakeRequest_()) {
1158 return; // channel is cancelled
1159 } else if (this.state_ == WebChannelBase.State.INIT) {
1160 if (opt_retryRequest) {
1161 this.channelDebug_.severe('Not supposed to retry the open');
1162 return;
1163 }
1164 this.open_();
1165 this.state_ = WebChannelBase.State.OPENING;
1166 } else if (this.state_ == WebChannelBase.State.OPENED) {
1167 if (opt_retryRequest) {
1168 this.makeForwardChannelRequest_(opt_retryRequest);
1169 return;
1170 }
1171
1172 if (this.outgoingMaps_.length == 0) {
1173 this.channelDebug_.debug(
1174 'startForwardChannel_ returned: ' +
1175 'nothing to send');
1176 // no need to start a new forward channel request
1177 return;
1178 }
1179
1180 if (this.forwardChannelRequestPool_.isFull()) {
1181 // Should be impossible to be called in this state.
1182 this.channelDebug_.severe(
1183 'startForwardChannel_ returned: ' +
1184 'connection already in progress');
1185 return;
1186 }
1187
1188 this.makeForwardChannelRequest_();
1189 this.channelDebug_.debug('startForwardChannel_ finished, sent request');
1190 }
1191 };
1192
1193
1194 /**
1195 * Establishes a new channel session with the the server.
1196 * @private
1197 */
1198 WebChannelBase.prototype.open_ = function() {
1199 this.channelDebug_.debug('open_()');
1200 this.nextRid_ = Math.floor(Math.random() * 100000);
1201
1202 var rid = this.nextRid_++;
1203 var request =
1204 ChannelRequest.createChannelRequest(this, this.channelDebug_, '', rid);
1205
1206 // mix the init headers
1207 var extraHeaders = this.extraHeaders_;
1208 if (this.initHeaders_) {
1209 if (extraHeaders) {
1210 extraHeaders = goog.object.clone(extraHeaders);
1211 goog.object.extend(extraHeaders, this.initHeaders_);
1212 } else {
1213 extraHeaders = this.initHeaders_;
1214 }
1215 }
1216
1217 if (this.httpHeadersOverwriteParam_ === null) {
1218 request.setExtraHeaders(extraHeaders);
1219 }
1220
1221 var requestText = this.dequeueOutgoingMaps_(request);
1222 var uri = this.forwardChannelUri_.clone();
1223 uri.setParameterValue('RID', rid);
1224
1225 if (this.clientVersion_ > 0) {
1226 uri.setParameterValue('CVER', this.clientVersion_);
1227 }
1228
1229 // http-session-id to be generated as the response
1230 if (this.getBackgroundChannelTest() && this.getHttpSessionIdParam()) {
1231 uri.setParameterValue(
1232 WebChannel.X_HTTP_SESSION_ID, this.getHttpSessionIdParam());
1233 }
1234
1235 // Add the reconnect parameters.
1236 this.addAdditionalParams_(uri);
1237
1238 if (this.httpHeadersOverwriteParam_ && extraHeaders) {
1239 httpCors.setHttpHeadersWithOverwriteParam(
1240 uri, this.httpHeadersOverwriteParam_, extraHeaders);
1241 }
1242
1243 this.forwardChannelRequestPool_.addRequest(request);
1244
1245 // Check the option and use GET to enable QUIC 0-RTT
1246 if (this.fastHandshake_) {
1247 uri.setParameterValue('$req', requestText);
1248 request.xmlHttpPost(uri, null, true); // Send as a GET
1249 } else {
1250 request.xmlHttpPost(uri, requestText, true);
1251 }
1252 };
1253
1254
1255 /**
1256 * Makes a forward channel request using XMLHTTP.
1257 * @param {!ChannelRequest=} opt_retryRequest A failed request to retry.
1258 * @private
1259 */
1260 WebChannelBase.prototype.makeForwardChannelRequest_ = function(
1261 opt_retryRequest) {
1262 var rid;
1263 if (opt_retryRequest) {
1264 rid = opt_retryRequest.getRequestId(); // Reuse the same RID for a retry
1265 } else {
1266 rid = this.nextRid_++;
1267 }
1268
1269 var uri = this.forwardChannelUri_.clone();
1270 uri.setParameterValue('SID', this.sid_);
1271 uri.setParameterValue('RID', rid);
1272 uri.setParameterValue('AID', this.lastArrayId_);
1273 // Add the additional reconnect parameters.
1274 this.addAdditionalParams_(uri);
1275
1276 if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {
1277 httpCors.setHttpHeadersWithOverwriteParam(
1278 uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);
1279 }
1280
1281 var request = ChannelRequest.createChannelRequest(
1282 this, this.channelDebug_, this.sid_, rid,
1283 this.forwardChannelRetryCount_ + 1);
1284
1285 if (this.httpHeadersOverwriteParam_ === null) {
1286 request.setExtraHeaders(this.extraHeaders_);
1287 }
1288
1289 var requestText;
1290 if (opt_retryRequest) {
1291 this.requeuePendingMaps_(opt_retryRequest);
1292 }
1293 requestText = this.dequeueOutgoingMaps_(request);
1294
1295 // Randomize from 50%-100% of the forward channel timeout to avoid
1296 // a big hit if servers happen to die at once.
1297 request.setTimeout(
1298 Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50) +
1299 Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50 * Math.random()));
1300 this.forwardChannelRequestPool_.addRequest(request);
1301 request.xmlHttpPost(uri, requestText, true);
1302 };
1303
1304
1305 /**
1306 * Adds the additional parameters from the handler to the given URI.
1307 * @param {!goog.Uri} uri The URI to add the parameters to.
1308 * @private
1309 */
1310 WebChannelBase.prototype.addAdditionalParams_ = function(uri) {
1311 // Add the additional reconnect parameters as needed.
1312 if (this.handler_) {
1313 var params = this.handler_.getAdditionalParams(this);
1314 if (params) {
1315 goog.structs.forEach(params, function(value, key, coll) {
1316 uri.setParameterValue(key, value);
1317 });
1318 }
1319 }
1320 };
1321
1322
1323 /**
1324 * Returns the request text from the outgoing maps and resets it.
1325 * @param {!ChannelRequest=} request The new request for sending the messages.
1326 * @return {string} The encoded request text created from all the currently
1327 * queued outgoing maps.
1328 * @private
1329 */
1330 WebChannelBase.prototype.dequeueOutgoingMaps_ = function(request) {
1331 var count =
1332 Math.min(this.outgoingMaps_.length, WebChannelBase.MAX_MAPS_PER_REQUEST_);
1333 var badMapHandler = this.handler_ ?
1334 goog.bind(this.handler_.badMapError, this.handler_, this) :
1335 null;
1336 var result = this.wireCodec_.encodeMessageQueue(
1337 this.outgoingMaps_, count, badMapHandler);
1338
1339 request.setPendingMessages(this.outgoingMaps_.splice(0, count));
1340
1341 return result;
1342 };
1343
1344
1345 /**
1346 * Requeues unacknowledged sent arrays for retransmission in the next forward
1347 * channel request.
1348 * @param {!ChannelRequest} retryRequest A failed request to retry.
1349 * @private
1350 */
1351 WebChannelBase.prototype.requeuePendingMaps_ = function(retryRequest) {
1352 this.outgoingMaps_ =
1353 retryRequest.getPendingMessages().concat(this.outgoingMaps_);
1354 };
1355
1356
1357 /**
1358 * Ensures there is a backchannel request for receiving data from the server.
1359 * @private
1360 */
1361 WebChannelBase.prototype.ensureBackChannel_ = function() {
1362 if (this.backChannelRequest_) {
1363 // already have one
1364 return;
1365 }
1366
1367 if (this.backChannelTimerId_) {
1368 // no need to start a new request - one is already scheduled
1369 return;
1370 }
1371
1372 this.backChannelAttemptId_ = 1;
1373
1374 // Use async.run instead of setTimeout(0) to avoid the 1s message delay
1375 // from chrome/firefox background tabs
1376 // backChannelTimerId_ stays unset, as with setTimeout(0)
1377 goog.async.run(this.onStartBackChannelTimer_, this);
1378
1379 this.backChannelRetryCount_ = 0;
1380 };
1381
1382
1383 /**
1384 * Schedules a back-channel retry, unless the max retries has been reached.
1385 * @return {boolean} true iff a retry was scheduled.
1386 * @private
1387 */
1388 WebChannelBase.prototype.maybeRetryBackChannel_ = function() {
1389 if (this.backChannelRequest_ || this.backChannelTimerId_) {
1390 // Should be impossible to be called in this state.
1391 this.channelDebug_.severe('Request already in progress');
1392 return false;
1393 }
1394
1395 if (this.backChannelRetryCount_ >= this.getBackChannelMaxRetries()) {
1396 return false;
1397 }
1398
1399 this.channelDebug_.debug('Going to retry GET');
1400
1401 this.backChannelAttemptId_++;
1402 this.backChannelTimerId_ = requestStats.setTimeout(
1403 goog.bind(this.onStartBackChannelTimer_, this),
1404 this.getRetryTime_(this.backChannelRetryCount_));
1405 this.backChannelRetryCount_++;
1406 return true;
1407 };
1408
1409
1410 /**
1411 * Timer callback for ensureBackChannel_.
1412 * @private
1413 */
1414 WebChannelBase.prototype.onStartBackChannelTimer_ = function() {
1415 this.backChannelTimerId_ = null;
1416 this.startBackChannel_();
1417 };
1418
1419
1420 /**
1421 * Begins a new back channel operation to the server.
1422 * @private
1423 */
1424 WebChannelBase.prototype.startBackChannel_ = function() {
1425 if (!this.okToMakeRequest_()) {
1426 // channel is cancelled
1427 return;
1428 }
1429
1430 this.channelDebug_.debug('Creating new HttpRequest');
1431 this.backChannelRequest_ = ChannelRequest.createChannelRequest(
1432 this, this.channelDebug_, this.sid_, 'rpc', this.backChannelAttemptId_);
1433
1434 if (this.httpHeadersOverwriteParam_ === null) {
1435 this.backChannelRequest_.setExtraHeaders(this.extraHeaders_);
1436 }
1437
1438 this.backChannelRequest_.setReadyStateChangeThrottle(
1439 this.readyStateChangeThrottleMs_);
1440 var uri = this.backChannelUri_.clone();
1441 uri.setParameterValue('RID', 'rpc');
1442 uri.setParameterValue('SID', this.sid_);
1443 uri.setParameterValue('CI', this.useChunked_ ? '0' : '1');
1444 uri.setParameterValue('AID', this.lastArrayId_);
1445
1446 // Add the reconnect parameters.
1447 this.addAdditionalParams_(uri);
1448
1449 uri.setParameterValue('TYPE', 'xmlhttp');
1450
1451 if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {
1452 httpCors.setHttpHeadersWithOverwriteParam(
1453 uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);
1454 }
1455
1456 if (this.backChannelRequestTimeoutMs_) {
1457 this.backChannelRequest_.setTimeout(this.backChannelRequestTimeoutMs_);
1458 }
1459
1460 this.backChannelRequest_.xmlHttpGet(
1461 uri, true /* decodeChunks */, this.hostPrefix_);
1462
1463 this.channelDebug_.debug('New Request created');
1464 };
1465
1466
1467 /**
1468 * Gives the handler a chance to return an error code and stop channel
1469 * execution. A handler might want to do this to check that the user is still
1470 * logged in, for example.
1471 * @private
1472 * @return {boolean} If it's OK to make a request.
1473 */
1474 WebChannelBase.prototype.okToMakeRequest_ = function() {
1475 if (this.handler_) {
1476 var result = this.handler_.okToMakeRequest(this);
1477 if (result != WebChannelBase.Error.OK) {
1478 this.channelDebug_.debug(
1479 'Handler returned error code from okToMakeRequest');
1480 this.signalError_(result);
1481 return false;
1482 }
1483 }
1484 return true;
1485 };
1486
1487
1488 /**
1489 * @override
1490 */
1491 WebChannelBase.prototype.testConnectionFinished = function(
1492 testChannel, useChunked) {
1493 this.channelDebug_.debug('Test Connection Finished');
1494
1495 // Forward channel will not be used prior to this method is called
1496 var clientProtocol = testChannel.getClientProtocol();
1497 if (clientProtocol) {
1498 this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);
1499 }
1500
1501 this.useChunked_ = this.allowChunkedMode_ && useChunked;
1502 this.lastStatusCode_ = testChannel.getLastStatusCode();
1503
1504 this.connectChannel_();
1505 };
1506
1507
1508 /**
1509 * @override
1510 */
1511 WebChannelBase.prototype.testConnectionFailure = function(
1512 testChannel, errorCode) {
1513 this.channelDebug_.debug('Test Connection Failed');
1514 this.lastStatusCode_ = testChannel.getLastStatusCode();
1515 this.signalError_(WebChannelBase.Error.REQUEST_FAILED);
1516 };
1517
1518
1519 /**
1520 * @override
1521 */
1522 WebChannelBase.prototype.onRequestData = function(request, responseText) {
1523 if (this.state_ == WebChannelBase.State.CLOSED ||
1524 (this.backChannelRequest_ != request &&
1525 !this.forwardChannelRequestPool_.hasRequest(request))) {
1526 // either CLOSED or a request we don't know about (perhaps an old request)
1527 return;
1528 }
1529 this.lastStatusCode_ = request.getLastStatusCode();
1530
1531 if (this.forwardChannelRequestPool_.hasRequest(request) &&
1532 this.state_ == WebChannelBase.State.OPENED) {
1533 var response;
1534 try {
1535 response = this.wireCodec_.decodeMessage(responseText);
1536 } catch (ex) {
1537 response = null;
1538 }
1539 if (goog.isArray(response) && response.length == 3) {
1540 this.handlePostResponse_(/** @type {!Array<?>} */ (response), request);
1541 } else {
1542 this.channelDebug_.debug('Bad POST response data returned');
1543 this.signalError_(WebChannelBase.Error.BAD_RESPONSE);
1544 }
1545 } else {
1546 if (this.backChannelRequest_ == request) {
1547 this.clearDeadBackchannelTimer_();
1548 }
1549 if (!goog.string.isEmptyOrWhitespace(responseText)) {
1550 var response = this.wireCodec_.decodeMessage(responseText);
1551 this.onInput_(/** @type {!Array<?>} */ (response), request);
1552 }
1553 }
1554 };
1555
1556
1557 /**
1558 * Handles a POST response from the server.
1559 * @param {Array<number>} responseValues The key value pairs in
1560 * the POST response.
1561 * @param {!ChannelRequest} forwardReq The forward channel request that
1562 * triggers this function call.
1563 * @private
1564 */
1565 WebChannelBase.prototype.handlePostResponse_ = function(
1566 responseValues, forwardReq) {
1567 // The first response value is set to 0 if server is missing backchannel.
1568 if (responseValues[0] == 0) {
1569 this.handleBackchannelMissing_(forwardReq);
1570 return;
1571 }
1572 this.lastPostResponseArrayId_ = responseValues[1];
1573 var outstandingArrays = this.lastPostResponseArrayId_ - this.lastArrayId_;
1574 if (0 < outstandingArrays) {
1575 var numOutstandingBackchannelBytes = responseValues[2];
1576 this.channelDebug_.debug(
1577 numOutstandingBackchannelBytes + ' bytes (in ' + outstandingArrays +
1578 ' arrays) are outstanding on the BackChannel');
1579 if (!this.shouldRetryBackChannel_(numOutstandingBackchannelBytes)) {
1580 return;
1581 }
1582 if (!this.deadBackChannelTimerId_) {
1583 // We expect to receive data within 2 RTTs or we retry the backchannel.
1584 this.deadBackChannelTimerId_ = requestStats.setTimeout(
1585 goog.bind(this.onBackChannelDead_, this),
1586 2 * WebChannelBase.RTT_ESTIMATE);
1587 }
1588 }
1589 };
1590
1591
1592 /**
1593 * Handles a POST response from the server telling us that it has detected that
1594 * we have no hanging GET connection.
1595 * @param {!ChannelRequest} forwardReq The forward channel request that
1596 * triggers this function call.
1597 * @private
1598 */
1599 WebChannelBase.prototype.handleBackchannelMissing_ = function(forwardReq) {
1600 // As long as the back channel was started before the POST was sent,
1601 // we should retry the backchannel. We give a slight buffer of RTT_ESTIMATE
1602 // so as not to excessively retry the backchannel
1603 this.channelDebug_.debug('Server claims our backchannel is missing.');
1604 if (this.backChannelTimerId_) {
1605 this.channelDebug_.debug('But we are currently starting the request.');
1606 return;
1607 } else if (!this.backChannelRequest_) {
1608 this.channelDebug_.warning('We do not have a BackChannel established');
1609 } else if (
1610 this.backChannelRequest_.getRequestStartTime() +
1611 WebChannelBase.RTT_ESTIMATE <
1612 forwardReq.getRequestStartTime()) {
1613 this.clearDeadBackchannelTimer_();
1614 this.backChannelRequest_.cancel();
1615 this.backChannelRequest_ = null;
1616 } else {
1617 return;
1618 }
1619 this.maybeRetryBackChannel_();
1620 requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_MISSING);
1621 };
1622
1623
1624 /**
1625 * Determines whether we should start the process of retrying a possibly
1626 * dead backchannel.
1627 * @param {number} outstandingBytes The number of bytes for which the server has
1628 * not yet received acknowledgement.
1629 * @return {boolean} Whether to start the backchannel retry timer.
1630 * @private
1631 */
1632 WebChannelBase.prototype.shouldRetryBackChannel_ = function(outstandingBytes) {
1633 // Not too many outstanding bytes, not buffered and not after a retry.
1634 return outstandingBytes <
1635 WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF &&
1636 !this.isBuffered() && this.backChannelRetryCount_ == 0;
1637 };
1638
1639
1640 /**
1641 * Decides which host prefix should be used, if any. If there is a handler,
1642 * allows the handler to validate a host prefix provided by the server, and
1643 * optionally override it.
1644 * @param {?string} serverHostPrefix The host prefix provided by the server.
1645 * @return {?string} The host prefix to actually use, if any. Will return null
1646 * if the use of host prefixes was disabled via setAllowHostPrefix().
1647 * @override
1648 */
1649 WebChannelBase.prototype.correctHostPrefix = function(serverHostPrefix) {
1650 if (this.allowHostPrefix_) {
1651 if (this.handler_) {
1652 return this.handler_.correctHostPrefix(serverHostPrefix);
1653 }
1654 return serverHostPrefix;
1655 }
1656 return null;
1657 };
1658
1659
1660 /**
1661 * Handles the timer that indicates that our backchannel is no longer able to
1662 * successfully receive data from the server.
1663 * @private
1664 */
1665 WebChannelBase.prototype.onBackChannelDead_ = function() {
1666 if (goog.isDefAndNotNull(this.deadBackChannelTimerId_)) {
1667 this.deadBackChannelTimerId_ = null;
1668 this.backChannelRequest_.cancel();
1669 this.backChannelRequest_ = null;
1670 this.maybeRetryBackChannel_();
1671 requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_DEAD);
1672 }
1673 };
1674
1675
1676 /**
1677 * Clears the timer that indicates that our backchannel is no longer able to
1678 * successfully receive data from the server.
1679 * @private
1680 */
1681 WebChannelBase.prototype.clearDeadBackchannelTimer_ = function() {
1682 if (goog.isDefAndNotNull(this.deadBackChannelTimerId_)) {
1683 goog.global.clearTimeout(this.deadBackChannelTimerId_);
1684 this.deadBackChannelTimerId_ = null;
1685 }
1686 };
1687
1688
1689 /**
1690 * Returns whether or not the given error/status combination is fatal or not.
1691 * On fatal errors we immediately close the session rather than retrying the
1692 * failed request.
1693 * @param {?ChannelRequest.Error} error The error code for the
1694 * failed request.
1695 * @param {number} statusCode The last HTTP status code.
1696 * @return {boolean} Whether or not the error is fatal.
1697 * @private
1698 */
1699 WebChannelBase.isFatalError_ = function(error, statusCode) {
1700 return error == ChannelRequest.Error.UNKNOWN_SESSION_ID ||
1701 (error == ChannelRequest.Error.STATUS && statusCode > 0);
1702 };
1703
1704
1705 /**
1706 * @override
1707 */
1708 WebChannelBase.prototype.onRequestComplete = function(request) {
1709 this.channelDebug_.debug('Request complete');
1710 var type;
1711 var pendingMessages = null;
1712 if (this.backChannelRequest_ == request) {
1713 this.clearDeadBackchannelTimer_();
1714 this.backChannelRequest_ = null;
1715 type = WebChannelBase.ChannelType_.BACK_CHANNEL;
1716 } else if (this.forwardChannelRequestPool_.hasRequest(request)) {
1717 pendingMessages = request.getPendingMessages();
1718 this.forwardChannelRequestPool_.removeRequest(request);
1719 type = WebChannelBase.ChannelType_.FORWARD_CHANNEL;
1720 } else {
1721 // return if it was an old request from a previous session
1722 return;
1723 }
1724
1725 this.lastStatusCode_ = request.getLastStatusCode();
1726
1727 if (this.state_ == WebChannelBase.State.CLOSED) {
1728 return;
1729 }
1730
1731 if (request.getSuccess()) {
1732 // Yay!
1733 if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {
1734 var size = request.getPostData() ? request.getPostData().length : 0;
1735 requestStats.notifyTimingEvent(
1736 size, goog.now() - request.getRequestStartTime(),
1737 this.forwardChannelRetryCount_);
1738 this.ensureForwardChannel_();
1739 this.onSuccess_(request);
1740 } else { // i.e., back-channel
1741 this.ensureBackChannel_();
1742 }
1743 return;
1744 }
1745 // Else unsuccessful. Fall through.
1746
1747 var lastError = request.getLastError();
1748 if (!WebChannelBase.isFatalError_(lastError, this.lastStatusCode_)) {
1749 // Maybe retry.
1750 var self = this;
1751 this.channelDebug_.debug(function() {
1752 return 'Maybe retrying, last error: ' +
1753 ChannelRequest.errorStringFromCode(lastError, self.lastStatusCode_);
1754 });
1755 if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {
1756 if (this.maybeRetryForwardChannel_(request)) {
1757 return;
1758 }
1759 }
1760 if (type == WebChannelBase.ChannelType_.BACK_CHANNEL) {
1761 if (this.maybeRetryBackChannel_()) {
1762 return;
1763 }
1764 }
1765 // Else exceeded max retries. Fall through.
1766 this.channelDebug_.debug('Exceeded max number of retries');
1767 } else {
1768 // Else fatal error. Fall through and mark the pending maps as failed.
1769 this.channelDebug_.debug('Not retrying due to error type');
1770 }
1771
1772
1773 // Abort the channel now
1774
1775 // Record pending messages from the failed request
1776 if (pendingMessages && pendingMessages.length > 0) {
1777 this.forwardChannelRequestPool_.addPendingMessages(pendingMessages);
1778 }
1779
1780 this.channelDebug_.debug('Error: HTTP request failed');
1781 switch (lastError) {
1782 case ChannelRequest.Error.NO_DATA:
1783 this.signalError_(WebChannelBase.Error.NO_DATA);
1784 break;
1785 case ChannelRequest.Error.BAD_DATA:
1786 this.signalError_(WebChannelBase.Error.BAD_DATA);
1787 break;
1788 case ChannelRequest.Error.UNKNOWN_SESSION_ID:
1789 this.signalError_(WebChannelBase.Error.UNKNOWN_SESSION_ID);
1790 break;
1791 default:
1792 this.signalError_(WebChannelBase.Error.REQUEST_FAILED);
1793 break;
1794 }
1795 };
1796
1797
1798 /**
1799 * @param {number} retryCount Number of retries so far.
1800 * @return {number} Time in ms before firing next retry request.
1801 * @private
1802 */
1803 WebChannelBase.prototype.getRetryTime_ = function(retryCount) {
1804 var retryTime = this.baseRetryDelayMs_ +
1805 Math.floor(Math.random() * this.retryDelaySeedMs_);
1806 if (!this.isActive()) {
1807 this.channelDebug_.debug('Inactive channel');
1808 retryTime = retryTime * WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR;
1809 }
1810 // Backoff for subsequent retries
1811 retryTime *= retryCount;
1812 return retryTime;
1813 };
1814
1815
1816 /**
1817 * @param {number} baseDelayMs The base part of the retry delay, in ms.
1818 * @param {number} delaySeedMs A random delay between 0 and this is added to
1819 * the base part.
1820 */
1821 WebChannelBase.prototype.setRetryDelay = function(baseDelayMs, delaySeedMs) {
1822 this.baseRetryDelayMs_ = baseDelayMs;
1823 this.retryDelaySeedMs_ = delaySeedMs;
1824 };
1825
1826
1827 /**
1828 * Apply any handshake control headers.
1829 * @param {!ChannelRequest} request The underlying request object
1830 * @private
1831 */
1832 WebChannelBase.prototype.applyControlHeaders_ = function(request) {
1833 if (!this.backgroundChannelTest_) {
1834 return;
1835 }
1836
1837 var xhr = request.getXhr();
1838 if (xhr) {
1839 var clientProtocol =
1840 xhr.getStreamingResponseHeader(WebChannel.X_CLIENT_WIRE_PROTOCOL);
1841 if (clientProtocol) {
1842 this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);
1843 }
1844
1845 if (this.getHttpSessionIdParam()) {
1846 var httpSessionIdHeader =
1847 xhr.getStreamingResponseHeader(WebChannel.X_HTTP_SESSION_ID);
1848 if (httpSessionIdHeader) {
1849 this.setHttpSessionId(httpSessionIdHeader);
1850 // update the cached uri
1851 var httpSessionIdParam = this.getHttpSessionIdParam();
1852
1853 this.forwardChannelUri_.setParameterValue(
1854 /** @type {string} */ (httpSessionIdParam), // never null
1855 httpSessionIdHeader);
1856 } else {
1857 this.channelDebug_.warning(
1858 'Missing X_HTTP_SESSION_ID in the handshake response');
1859 }
1860 }
1861 }
1862 };
1863
1864
1865 /**
1866 * Processes the data returned by the server.
1867 * @param {!Array<!Array<?>>} respArray The response array returned
1868 * by the server.
1869 * @param {!ChannelRequest} request The underlying request object
1870 * @private
1871 */
1872 WebChannelBase.prototype.onInput_ = function(respArray, request) {
1873 var batch =
1874 this.handler_ && this.handler_.channelHandleMultipleArrays ? [] : null;
1875 for (var i = 0; i < respArray.length; i++) {
1876 var nextArray = respArray[i];
1877 this.lastArrayId_ = nextArray[0];
1878 nextArray = nextArray[1];
1879 if (this.state_ == WebChannelBase.State.OPENING) {
1880 if (nextArray[0] == 'c') {
1881 this.sid_ = nextArray[1];
1882 this.hostPrefix_ = this.correctHostPrefix(nextArray[2]);
1883
1884 var negotiatedVersion = nextArray[3];
1885 if (goog.isDefAndNotNull(negotiatedVersion)) {
1886 this.channelVersion_ = negotiatedVersion;
1887 this.channelDebug_.info('VER=' + this.channelVersion_);
1888 }
1889
1890 var negotiatedServerVersion = nextArray[4];
1891 if (goog.isDefAndNotNull(negotiatedServerVersion)) {
1892 this.serverVersion_ = negotiatedServerVersion;
1893 this.channelDebug_.info('SVER=' + this.serverVersion_);
1894 }
1895
1896 // CVER=22
1897 var serverKeepaliveMs = nextArray[5];
1898 if (goog.isDefAndNotNull(serverKeepaliveMs) &&
1899 goog.isNumber(serverKeepaliveMs) && serverKeepaliveMs > 0) {
1900 var timeout = 1.5 * serverKeepaliveMs;
1901 this.backChannelRequestTimeoutMs_ = timeout;
1902 this.channelDebug_.info('backChannelRequestTimeoutMs_=' + timeout);
1903 }
1904
1905 this.applyControlHeaders_(request);
1906
1907 this.state_ = WebChannelBase.State.OPENED;
1908 if (this.handler_) {
1909 this.handler_.channelOpened(this);
1910 }
1911 this.backChannelUri_ = this.getBackChannelUri(
1912 this.hostPrefix_, /** @type {string} */ (this.path_));
1913 // Open connection to receive data
1914 this.ensureBackChannel_();
1915 } else if (nextArray[0] == 'stop' || nextArray[0] == 'close') {
1916 // treat close also as an abort
1917 this.signalError_(WebChannelBase.Error.STOP);
1918 }
1919 } else if (this.state_ == WebChannelBase.State.OPENED) {
1920 if (nextArray[0] == 'stop' || nextArray[0] == 'close') {
1921 if (batch && !goog.array.isEmpty(batch)) {
1922 this.handler_.channelHandleMultipleArrays(this, batch);
1923 batch.length = 0;
1924 }
1925 if (nextArray[0] == 'stop') {
1926 this.signalError_(WebChannelBase.Error.STOP);
1927 } else {
1928 this.disconnect();
1929 }
1930 } else if (nextArray[0] == 'noop') {
1931 // ignore - noop to keep connection happy
1932 } else {
1933 if (batch) {
1934 batch.push(nextArray);
1935 } else if (this.handler_) {
1936 this.handler_.channelHandleArray(this, nextArray);
1937 }
1938 }
1939 // We have received useful data on the back-channel, so clear its retry
1940 // count. We do this because back-channels by design do not complete
1941 // quickly, so on a flaky connection we could have many fail to complete
1942 // fully but still deliver a lot of data before they fail. We don't want
1943 // to count such failures towards the retry limit, because we don't want
1944 // to give up on a session if we can still receive data.
1945 this.backChannelRetryCount_ = 0;
1946 }
1947 }
1948 if (batch && !goog.array.isEmpty(batch)) {
1949 this.handler_.channelHandleMultipleArrays(this, batch);
1950 }
1951 };
1952
1953
1954 /**
1955 * Helper to ensure the channel is in the expected state.
1956 * @param {...number} var_args The channel must be in one of the indicated
1957 * states.
1958 * @private
1959 */
1960 WebChannelBase.prototype.ensureInState_ = function(var_args) {
1961 goog.asserts.assert(
1962 goog.array.contains(arguments, this.state_),
1963 'Unexpected channel state: %s', this.state_);
1964 };
1965
1966
1967 /**
1968 * Signals an error has occurred.
1969 * @param {WebChannelBase.Error} error The error code for the failure.
1970 * @private
1971 */
1972 WebChannelBase.prototype.signalError_ = function(error) {
1973 this.channelDebug_.info('Error code ' + error);
1974 if (error == WebChannelBase.Error.REQUEST_FAILED) {
1975 // Create a separate Internet connection to check
1976 // if it's a server error or user's network error.
1977 var imageUri = null;
1978 if (this.handler_) {
1979 imageUri = this.handler_.getNetworkTestImageUri(this);
1980 }
1981 netUtils.testNetwork(goog.bind(this.testNetworkCallback_, this), imageUri);
1982 } else {
1983 requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);
1984 }
1985 this.onError_(error);
1986 };
1987
1988
1989 /**
1990 * Callback for netUtils.testNetwork during error handling.
1991 * @param {boolean} networkUp Whether the network is up.
1992 * @private
1993 */
1994 WebChannelBase.prototype.testNetworkCallback_ = function(networkUp) {
1995 if (networkUp) {
1996 this.channelDebug_.info('Successfully pinged google.com');
1997 requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);
1998 } else {
1999 this.channelDebug_.info('Failed to ping google.com');
2000 requestStats.notifyStatEvent(requestStats.Stat.ERROR_NETWORK);
2001 // Do not call onError_ again to eliminate duplicated Error events.
2002 }
2003 };
2004
2005
2006 /**
2007 * Called when messages have been successfully sent from the queue.
2008 * @param {!ChannelRequest} request The request object
2009 * @private
2010 */
2011 WebChannelBase.prototype.onSuccess_ = function(request) {
2012 if (this.handler_) {
2013 this.handler_.channelSuccess(this, request);
2014 }
2015 };
2016
2017
2018 /**
2019 * Called when we've determined the final error for a channel. It closes the
2020 * notifiers the handler of the error and closes the channel.
2021 * @param {WebChannelBase.Error} error The error code for the failure.
2022 * @private
2023 */
2024 WebChannelBase.prototype.onError_ = function(error) {
2025 this.channelDebug_.debug('HttpChannel: error - ' + error);
2026 this.state_ = WebChannelBase.State.CLOSED;
2027 if (this.handler_) {
2028 this.handler_.channelError(this, error);
2029 }
2030 this.onClose_();
2031 this.cancelRequests_();
2032 };
2033
2034
2035 /**
2036 * Called when the channel has been closed. It notifiers the handler of the
2037 * event, and reports any pending or undelivered maps.
2038 * @private
2039 */
2040 WebChannelBase.prototype.onClose_ = function() {
2041 this.state_ = WebChannelBase.State.CLOSED;
2042 this.lastStatusCode_ = -1;
2043 if (this.handler_) {
2044 var pendingMessages = this.forwardChannelRequestPool_.getPendingMessages();
2045
2046 if (pendingMessages.length == 0 && this.outgoingMaps_.length == 0) {
2047 this.handler_.channelClosed(this);
2048 } else {
2049 var self = this;
2050 this.channelDebug_.debug(function() {
2051 return 'Number of undelivered maps' +
2052 ', pending: ' + pendingMessages.length +
2053 ', outgoing: ' + self.outgoingMaps_.length;
2054 });
2055
2056 this.forwardChannelRequestPool_.clearPendingMessages();
2057
2058 var copyOfUndeliveredMaps = goog.array.clone(this.outgoingMaps_);
2059 this.outgoingMaps_.length = 0;
2060
2061 this.handler_.channelClosed(this, pendingMessages, copyOfUndeliveredMaps);
2062 }
2063 }
2064 };
2065
2066
2067 /**
2068 * @override
2069 */
2070 WebChannelBase.prototype.getForwardChannelUri = function(path) {
2071 var uri = this.createDataUri(null, path);
2072 this.channelDebug_.debug('GetForwardChannelUri: ' + uri);
2073 return uri;
2074 };
2075
2076
2077 /**
2078 * @override
2079 */
2080 WebChannelBase.prototype.getConnectionState = function() {
2081 return this.connState_;
2082 };
2083
2084
2085 /**
2086 * @override
2087 */
2088 WebChannelBase.prototype.getBackChannelUri = function(hostPrefix, path) {
2089 var uri = this.createDataUri(
2090 this.shouldUseSecondaryDomains() ? hostPrefix : null, path);
2091 this.channelDebug_.debug('GetBackChannelUri: ' + uri);
2092 return uri;
2093 };
2094
2095
2096 /**
2097 * @override
2098 */
2099 WebChannelBase.prototype.createDataUri = function(
2100 hostPrefix, path, opt_overridePort) {
2101 var uri = goog.Uri.parse(path);
2102 var uriAbsolute = (uri.getDomain() != '');
2103 if (uriAbsolute) {
2104 if (hostPrefix) {
2105 uri.setDomain(hostPrefix + '.' + uri.getDomain());
2106 }
2107
2108 uri.setPort(opt_overridePort || uri.getPort());
2109 } else {
2110 var locationPage = goog.global.location;
2111 var hostName;
2112 if (hostPrefix) {
2113 hostName = hostPrefix + '.' + locationPage.hostname;
2114 } else {
2115 hostName = locationPage.hostname;
2116 }
2117
2118 var port = opt_overridePort || locationPage.port;
2119
2120 uri = goog.Uri.create(locationPage.protocol, null, hostName, port, path);
2121 }
2122
2123 if (this.extraParams_) {
2124 goog.object.forEach(this.extraParams_, function(value, key) {
2125 uri.setParameterValue(key, value);
2126 });
2127 }
2128
2129 var param = this.getHttpSessionIdParam();
2130 var value = this.getHttpSessionId();
2131 if (param && value) {
2132 uri.setParameterValue(param, value);
2133 }
2134
2135 // Add the protocol version to the URI.
2136 uri.setParameterValue('VER', this.channelVersion_);
2137
2138 // Add the reconnect parameters.
2139 this.addAdditionalParams_(uri);
2140
2141 return uri;
2142 };
2143
2144
2145 /**
2146 * @override
2147 */
2148 WebChannelBase.prototype.createXhrIo = function(hostPrefix) {
2149 if (hostPrefix && !this.supportsCrossDomainXhrs_) {
2150 throw new Error('Can\'t create secondary domain capable XhrIo object.');
2151 }
2152 var xhr = new goog.net.XhrIo();
2153 xhr.setWithCredentials(this.supportsCrossDomainXhrs_);
2154 return xhr;
2155 };
2156
2157
2158 /**
2159 * @override
2160 */
2161 WebChannelBase.prototype.isActive = function() {
2162 return !!this.handler_ && this.handler_.isActive(this);
2163 };
2164
2165
2166 /**
2167 * @override
2168 */
2169 WebChannelBase.prototype.shouldUseSecondaryDomains = function() {
2170 return this.supportsCrossDomainXhrs_;
2171 };
2172
2173
2174 /**
2175 * A LogSaver that can be used to accumulate all the debug logs so they
2176 * can be sent to the server when a problem is detected.
2177 */
2178 WebChannelBase.LogSaver = {};
2179
2180
2181 /**
2182 * Buffer for accumulating the debug log
2183 * @type {goog.structs.CircularBuffer}
2184 * @private
2185 */
2186 WebChannelBase.LogSaver.buffer_ = new goog.structs.CircularBuffer(1000);
2187
2188
2189 /**
2190 * Whether we're currently accumulating the debug log.
2191 * @type {boolean}
2192 * @private
2193 */
2194 WebChannelBase.LogSaver.enabled_ = false;
2195
2196
2197 /**
2198 * Formatter for saving logs.
2199 * @type {goog.debug.Formatter}
2200 * @private
2201 */
2202 WebChannelBase.LogSaver.formatter_ = new goog.debug.TextFormatter();
2203
2204
2205 /**
2206 * Returns whether the LogSaver is enabled.
2207 * @return {boolean} Whether saving is enabled or disabled.
2208 */
2209 WebChannelBase.LogSaver.isEnabled = function() {
2210 return WebChannelBase.LogSaver.enabled_;
2211 };
2212
2213
2214 /**
2215 * Enables of disables the LogSaver.
2216 * @param {boolean} enable Whether to enable or disable saving.
2217 */
2218 WebChannelBase.LogSaver.setEnabled = function(enable) {
2219 if (enable == WebChannelBase.LogSaver.enabled_) {
2220 return;
2221 }
2222
2223 var fn = WebChannelBase.LogSaver.addLogRecord;
2224 var logger = goog.log.getLogger('goog.net');
2225 if (enable) {
2226 goog.log.addHandler(logger, fn);
2227 } else {
2228 goog.log.removeHandler(logger, fn);
2229 }
2230 };
2231
2232
2233 /**
2234 * Adds a log record.
2235 * @param {goog.log.LogRecord} logRecord the LogRecord.
2236 */
2237 WebChannelBase.LogSaver.addLogRecord = function(logRecord) {
2238 WebChannelBase.LogSaver.buffer_.add(
2239 WebChannelBase.LogSaver.formatter_.formatRecord(logRecord));
2240 };
2241
2242
2243 /**
2244 * Returns the log as a single string.
2245 * @return {string} The log as a single string.
2246 */
2247 WebChannelBase.LogSaver.getBuffer = function() {
2248 return WebChannelBase.LogSaver.buffer_.getValues().join('');
2249 };
2250
2251
2252 /**
2253 * Clears the buffer
2254 */
2255 WebChannelBase.LogSaver.clearBuffer = function() {
2256 WebChannelBase.LogSaver.buffer_.clear();
2257 };
2258
2259
2260
2261 /**
2262 * Abstract base class for the channel handler
2263 * @constructor
2264 * @struct
2265 */
2266 WebChannelBase.Handler = function() {};
2267
2268
2269 /**
2270 * Callback handler for when a batch of response arrays is received from the
2271 * server. When null, batched dispatching is disabled.
2272 * @type {?function(!WebChannelBase, !Array<!Array<?>>)}
2273 */
2274 WebChannelBase.Handler.prototype.channelHandleMultipleArrays = null;
2275
2276
2277 /**
2278 * Whether it's okay to make a request to the server. A handler can return
2279 * false if the channel should fail. For example, if the user has logged out,
2280 * the handler may want all requests to fail immediately.
2281 * @param {WebChannelBase} channel The channel.
2282 * @return {WebChannelBase.Error} An error code. The code should
2283 * return WebChannelBase.Error.OK to indicate it's okay. Any other
2284 * error code will cause a failure.
2285 */
2286 WebChannelBase.Handler.prototype.okToMakeRequest = function(channel) {
2287 return WebChannelBase.Error.OK;
2288 };
2289
2290
2291 /**
2292 * Indicates the WebChannel has successfully negotiated with the server
2293 * and can now send and receive data.
2294 * @param {WebChannelBase} channel The channel.
2295 */
2296 WebChannelBase.Handler.prototype.channelOpened = function(channel) {};
2297
2298
2299 /**
2300 * New input is available for the application to process.
2301 *
2302 * @param {WebChannelBase} channel The channel.
2303 * @param {Array<?>} array The data array.
2304 */
2305 WebChannelBase.Handler.prototype.channelHandleArray = function(channel, array) {
2306 };
2307
2308
2309 /**
2310 * Indicates messages that have been successfully sent on the channel.
2311 *
2312 * @param {WebChannelBase} channel The channel.
2313 * @param {!ChannelRequest} request The request object that contains
2314 * the pending messages that have been successfully delivered to the server.
2315 */
2316 WebChannelBase.Handler.prototype.channelSuccess = function(channel, request) {};
2317
2318
2319 /**
2320 * Indicates an error occurred on the WebChannel.
2321 *
2322 * @param {WebChannelBase} channel The channel.
2323 * @param {WebChannelBase.Error} error The error code.
2324 */
2325 WebChannelBase.Handler.prototype.channelError = function(channel, error) {};
2326
2327
2328 /**
2329 * Indicates the WebChannel is closed. Also notifies about which maps,
2330 * if any, that may not have been delivered to the server.
2331 * @param {WebChannelBase} channel The channel.
2332 * @param {Array<Wire.QueuedMap>=} opt_pendingMaps The
2333 * array of pending maps, which may or may not have been delivered to the
2334 * server.
2335 * @param {Array<Wire.QueuedMap>=} opt_undeliveredMaps
2336 * The array of undelivered maps, which have definitely not been delivered
2337 * to the server.
2338 */
2339 WebChannelBase.Handler.prototype.channelClosed = function(
2340 channel, opt_pendingMaps, opt_undeliveredMaps) {};
2341
2342
2343 /**
2344 * Gets any parameters that should be added at the time another connection is
2345 * made to the server.
2346 * @param {WebChannelBase} channel The channel.
2347 * @return {!Object} Extra parameter keys and values to add to the requests.
2348 */
2349 WebChannelBase.Handler.prototype.getAdditionalParams = function(channel) {
2350 return {};
2351 };
2352
2353
2354 /**
2355 * Gets the URI of an image that can be used to test network connectivity.
2356 * @param {WebChannelBase} channel The channel.
2357 * @return {goog.Uri?} A custom URI to load for the network test.
2358 */
2359 WebChannelBase.Handler.prototype.getNetworkTestImageUri = function(channel) {
2360 return null;
2361 };
2362
2363
2364 /**
2365 * Gets whether this channel is currently active. This is used to determine the
2366 * length of time to wait before retrying.
2367 * @param {WebChannelBase} channel The channel.
2368 * @return {boolean} Whether the channel is currently active.
2369 */
2370 WebChannelBase.Handler.prototype.isActive = function(channel) {
2371 return true;
2372 };
2373
2374
2375 /**
2376 * Called by the channel if enumeration of the map throws an exception.
2377 * @param {WebChannelBase} channel The channel.
2378 * @param {Object} map The map that can't be enumerated.
2379 */
2380 WebChannelBase.Handler.prototype.badMapError = function(channel, map) {};
2381
2382
2383 /**
2384 * Allows the handler to override a host prefix provided by the server. Will
2385 * be called whenever the channel has received such a prefix and is considering
2386 * its use.
2387 * @param {?string} serverHostPrefix The host prefix provided by the server.
2388 * @return {?string} The host prefix the client should use.
2389 */
2390 WebChannelBase.Handler.prototype.correctHostPrefix = function(
2391 serverHostPrefix) {
2392 return serverHostPrefix;
2393 };
2394 }); // goog.scope