This repository has been archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathchannelrequest.js
1418 lines (1223 loc) · 39.3 KB
/
channelrequest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Definition of the ChannelRequest class. The request
* object encapsulates the logic for making a single request, either for the
* forward channel, back channel, or test channel, to the server. It contains
* the logic for the two types of transports we use:
* XMLHTTP and Image request. It provides timeout detection. More transports
* to be added in future, such as Fetch, WebSocket.
*
*/
goog.provide('goog.labs.net.webChannel.ChannelRequest');
goog.require('goog.Timer');
goog.require('goog.asserts');
goog.require('goog.async.Throttle');
goog.require('goog.dispose');
goog.require('goog.events.EventHandler');
goog.require('goog.labs.net.webChannel.Channel');
goog.require('goog.labs.net.webChannel.WebChannelDebug');
goog.require('goog.labs.net.webChannel.environment');
goog.require('goog.labs.net.webChannel.requestStats');
goog.require('goog.net.ErrorCode');
goog.require('goog.net.EventType');
goog.require('goog.net.WebChannel');
goog.require('goog.net.XmlHttp');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.userAgent');
goog.requireType('goog.Uri');
goog.requireType('goog.events.Event');
goog.requireType('goog.labs.net.webChannel.Wire.QueuedMap');
goog.requireType('goog.net.XhrIo');
/**
* A new ChannelRequest is created for each request to the server.
*
* @param {goog.labs.net.webChannel.Channel} channel
* The channel that owns this request.
* @param {goog.labs.net.webChannel.WebChannelDebug} channelDebug A
* WebChannelDebug to use for logging.
* @param {string=} opt_sessionId The session id for the channel.
* @param {string|number=} opt_requestId The request id for this request.
* @param {number=} opt_retryId The retry id for this request.
* @constructor
* @struct
* @final
*/
goog.labs.net.webChannel.ChannelRequest = function(
channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {
'use strict';
/**
* The channel object that owns the request.
* @private {goog.labs.net.webChannel.Channel}
*/
this.channel_ = channel;
/**
* The channel debug to use for logging
* @private {goog.labs.net.webChannel.WebChannelDebug}
*/
this.channelDebug_ = channelDebug;
/**
* The Session ID for the channel.
* @private {string|undefined}
*/
this.sid_ = opt_sessionId;
/**
* The RID (request ID) for the request.
* @private {string|number|undefined}
*/
this.rid_ = opt_requestId;
/**
* The attempt number of the current request.
* @private {number}
*/
this.retryId_ = opt_retryId || 1;
/**
* An object to keep track of the channel request event listeners.
* @private {!goog.events.EventHandler<
* !goog.labs.net.webChannel.ChannelRequest>}
*/
this.eventHandler_ = new goog.events.EventHandler(this);
/**
* The timeout in ms before failing the request.
* @private {number}
*/
this.timeout_ = goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_;
/**
* A timer for polling responseText in browsers that don't fire
* onreadystatechange during incremental loading of responseText.
* @private {goog.Timer}
*/
this.pollingTimer_ =
new goog.Timer(goog.labs.net.webChannel.environment.getPollingInterval());
/**
* Extra HTTP headers to add to all the requests sent to the server.
* @private {?Object}
*/
this.extraHeaders_ = null;
/**
* Whether the request was successful. This is only set to true after the
* request successfully completes.
* @private {boolean}
*/
this.successful_ = false;
/**
* The TimerID of the timer used to detect if the request has timed-out.
* @type {?number}
* @private
*/
this.watchDogTimerId_ = null;
/**
* The time in the future when the request will timeout.
* @private {?number}
*/
this.watchDogTimeoutTime_ = null;
/**
* The time the request started.
* @private {?number}
*/
this.requestStartTime_ = null;
/**
* The type of request (XMLHTTP, IMG)
* @private {?number}
*/
this.type_ = null;
/**
* The base Uri for the request. The includes all the parameters except the
* one that indicates the retry number.
* @private {?goog.Uri}
*/
this.baseUri_ = null;
/**
* The request Uri that was actually used for the most recent request attempt.
* @private {?goog.Uri}
*/
this.requestUri_ = null;
/**
* The post data, if the request is a post.
* @private {?string}
*/
this.postData_ = null;
/**
* An array of pending messages that we have either received a non-successful
* response for, or no response at all, and which therefore may or may not
* have been received by the server.
* @private {!Array<goog.labs.net.webChannel.Wire.QueuedMap>}
*/
this.pendingMessages_ = [];
/**
* The XhrLte request if the request is using XMLHTTP
* @private {?goog.net.XhrIo}
*/
this.xmlHttp_ = null;
/**
* The position of where the next unprocessed chunk starts in the response
* text.
* @private {number}
*/
this.xmlHttpChunkStart_ = 0;
/**
* The verb (Get or Post) for the request.
* @private {?string}
*/
this.verb_ = null;
/**
* The last error if the request failed.
* @private {?goog.labs.net.webChannel.ChannelRequest.Error}
*/
this.lastError_ = null;
/**
* The response headers received along with the non-200 status.
*
* @private {!Object<string, string>|undefined}
*/
this.errorResponseHeaders_ = undefined;
/**
* The last status code received.
* @private {number}
*/
this.lastStatusCode_ = -1;
/**
* Whether the request has been cancelled due to a call to cancel.
* @private {boolean}
*/
this.cancelled_ = false;
/**
* A throttle time in ms for readystatechange events for the backchannel.
* Useful for throttling when ready state is INTERACTIVE (partial data).
* If set to zero no throttle is used.
*
* See WebChannelBase.prototype.readyStateChangeThrottleMs_
*
* @private {number}
*/
this.readyStateChangeThrottleMs_ = 0;
/**
* The throttle for readystatechange events for the current request, or null
* if there is none.
* @private {?goog.async.Throttle}
*/
this.readyStateChangeThrottle_ = null;
/**
* Whether to the result is expected to be encoded for chunking and thus
* requires decoding.
* @private {boolean}
*/
this.decodeChunks_ = false;
/**
* Whether to decode x-http-initial-response.
* @private {boolean}
*/
this.decodeInitialResponse_ = false;
/**
* Whether x-http-initial-response has been decoded (dispatched).
* @private {boolean}
*/
this.initialResponseDecoded_ = false;
/**
* Whether the first byte of response body has arrived, for a successful
* response.
* @private {boolean}
*/
this.firstByteReceived_ = false;
/**
* The current state of fetch responses if webchannel is using WHATWG
* fetch/streams.
* @private {!goog.labs.net.webChannel.FetchResponseState}
*/
this.fetchResponseState_ = new goog.labs.net.webChannel.FetchResponseState();
};
/**
* A collection of fetch/stream properties.
* @struct
* @constructor
*/
goog.labs.net.webChannel.FetchResponseState = function() {
'use strict';
/**
* The TextDecoder for decoding Uint8Array responses from fetch request.
* @type {?goog.global.TextDecoder}
*/
this.textDecoder = null;
/**
* The unconsumed response text from the fetch requests.
* @type {string}
*/
this.responseBuffer = '';
/**
* Whether or not the response body has arrived.
* @type {boolean}
*/
this.responseArrivedForFetch = false;
};
goog.scope(function() {
'use strict';
const WebChannel = goog.net.WebChannel;
const Channel = goog.labs.net.webChannel.Channel;
const ChannelRequest = goog.labs.net.webChannel.ChannelRequest;
const FetchResponseState = goog.labs.net.webChannel.FetchResponseState;
const requestStats = goog.labs.net.webChannel.requestStats;
const WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;
const environment = goog.labs.net.webChannel.environment;
/**
* Default timeout in MS for a request. The server must return data within this
* time limit for the request to not timeout.
* @private {number}
*/
ChannelRequest.TIMEOUT_MS_ = 45 * 1000;
/**
* Enum for channel requests type
* @enum {number}
* @private
*/
ChannelRequest.Type_ = {
/**
* XMLHTTP requests.
*/
XML_HTTP: 1,
/**
* IMG requests.
*/
CLOSE_REQUEST: 2
};
/**
* Enum type for identifying an error.
* @enum {number}
*/
ChannelRequest.Error = {
/**
* Errors due to a non-200 status code.
*/
STATUS: 0,
/**
* Errors due to no data being returned.
*/
NO_DATA: 1,
/**
* Errors due to a timeout.
*/
TIMEOUT: 2,
/**
* Errors due to the server returning an unknown.
*/
UNKNOWN_SESSION_ID: 3,
/**
* Errors due to bad data being received.
*/
BAD_DATA: 4,
/**
* Errors due to the handler throwing an exception.
*/
HANDLER_EXCEPTION: 5,
/**
* The browser declared itself offline during the request.
*/
BROWSER_OFFLINE: 6
};
/**
* Returns a useful error string for debugging based on the specified error
* code.
* @param {?ChannelRequest.Error} errorCode The error code.
* @param {number} statusCode The HTTP status code.
* @return {string} The error string for the given code combination.
*/
ChannelRequest.errorStringFromCode = function(errorCode, statusCode) {
'use strict';
switch (errorCode) {
case ChannelRequest.Error.STATUS:
return 'Non-200 return code (' + statusCode + ')';
case ChannelRequest.Error.NO_DATA:
return 'XMLHTTP failure (no data)';
case ChannelRequest.Error.TIMEOUT:
return 'HttpConnection timeout';
default:
return 'Unknown error';
}
};
/**
* Sentinel value used to indicate an invalid chunk in a multi-chunk response.
* @private {!Object}
*/
ChannelRequest.INVALID_CHUNK_ = {};
/**
* Sentinel value used to indicate an incomplete chunk in a multi-chunk
* response.
* @private {!Object}
*/
ChannelRequest.INCOMPLETE_CHUNK_ = {};
/**
* Returns whether XHR streaming is supported on this browser.
*
* @return {boolean} Whether XHR streaming is supported.
* @see http://code.google.com/p/closure-library/issues/detail?id=346
*/
ChannelRequest.supportsXhrStreaming = function() {
'use strict';
return !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(10);
};
/**
* Sets extra HTTP headers to add to all the requests sent to the server.
*
* @param {Object} extraHeaders The HTTP headers.
*/
ChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {
'use strict';
this.extraHeaders_ = extraHeaders;
};
/**
* Overrides the default HTTP method.
*
* @param {string} verb The HTTP method
*/
ChannelRequest.prototype.setVerb = function(verb) {
'use strict';
this.verb_ = verb;
};
/**
* Sets the timeout for a request
*
* @param {number} timeout The timeout in MS for when we fail the request.
*/
ChannelRequest.prototype.setTimeout = function(timeout) {
'use strict';
this.timeout_ = timeout;
};
/**
* Sets the throttle for handling onreadystatechange events for the request.
*
* @param {number} throttle The throttle in ms. A value of zero indicates
* no throttle.
*/
ChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {
'use strict';
this.readyStateChangeThrottleMs_ = throttle;
};
/**
* Sets the pending messages that this request is handling.
*
* @param {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} pendingMessages
* The pending messages for this request.
*/
ChannelRequest.prototype.setPendingMessages = function(pendingMessages) {
'use strict';
this.pendingMessages_ = pendingMessages;
};
/**
* Gets the pending messages that this request is handling, in case of a retry.
*
* @return {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} The pending
* messages for this request.
*/
ChannelRequest.prototype.getPendingMessages = function() {
'use strict';
return this.pendingMessages_;
};
/**
* Uses XMLHTTP to send an HTTP POST to the server.
*
* @param {goog.Uri} uri The uri of the request.
* @param {?string} postData The data for the post body.
* @param {boolean} decodeChunks Whether to the result is expected to be
* encoded for chunking and thus requires decoding.
*/
ChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) {
'use strict';
this.type_ = ChannelRequest.Type_.XML_HTTP;
this.baseUri_ = uri.clone().makeUnique();
this.postData_ = postData;
this.decodeChunks_ = decodeChunks;
this.sendXmlHttp_(null /* hostPrefix */);
};
/**
* Uses XMLHTTP to send an HTTP GET to the server.
*
* @param {goog.Uri} uri The uri of the request.
* @param {boolean} decodeChunks Whether to the result is expected to be
* encoded for chunking and thus requires decoding.
* @param {?string} hostPrefix The host prefix, if we might be using a
* secondary domain. Note that it should also be in the URL, adding this
* won't cause it to be added to the URL.
*/
ChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks, hostPrefix) {
'use strict';
this.type_ = ChannelRequest.Type_.XML_HTTP;
this.baseUri_ = uri.clone().makeUnique();
this.postData_ = null;
this.decodeChunks_ = decodeChunks;
this.sendXmlHttp_(hostPrefix);
};
/**
* Sends a request via XMLHTTP according to the current state of the request
* object.
*
* @param {?string} hostPrefix The host prefix, if we might be using a secondary
* domain.
* @private
*/
ChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) {
'use strict';
this.requestStartTime_ = Date.now();
this.ensureWatchDogTimer_();
// clone the base URI to create the request URI. The request uri has the
// attempt number as a parameter which helps in debugging.
this.requestUri_ = this.baseUri_.clone();
this.requestUri_.setParameterValues('t', this.retryId_);
// send the request either as a POST or GET
this.xmlHttpChunkStart_ = 0;
const useSecondaryDomains = this.channel_.shouldUseSecondaryDomains();
this.fetchResponseState_ = new FetchResponseState();
// If the request is a GET request, start a backchannel to transfer streaming
// data. Note that WebChannel GET request can also be used for closing the
// channel as in method ChannelRequest#sendCloseRequest.
// The second parameter of Channel#createXhrIo is JS only.
this.xmlHttp_ = this.channel_.createXhrIo(
useSecondaryDomains ? hostPrefix : null, !this.postData_);
if (this.readyStateChangeThrottleMs_ > 0) {
this.readyStateChangeThrottle_ = new goog.async.Throttle(
goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_),
this.readyStateChangeThrottleMs_);
}
this.eventHandler_.listen(
this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE,
this.readyStateChangeHandler_);
const headers =
this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {};
if (this.postData_) {
if (!this.verb_) {
this.verb_ = 'POST';
}
headers['Content-Type'] = 'application/x-www-form-urlencoded';
this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers);
} else {
this.verb_ = 'GET';
this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers);
}
requestStats.notifyServerReachabilityEvent(
requestStats.ServerReachability.REQUEST_MADE);
this.channelDebug_.xmlHttpChannelRequest(
this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_);
};
/**
* Handles a readystatechange event.
* @param {goog.events.Event} evt The event.
* @private
*/
ChannelRequest.prototype.readyStateChangeHandler_ = function(evt) {
'use strict';
const xhr = /** @type {goog.net.XhrIo} */ (evt.target);
const throttle = this.readyStateChangeThrottle_;
if (throttle &&
xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) {
// Only throttle in the partial data case.
this.channelDebug_.debug('Throttling readystatechange.');
throttle.fire();
} else {
// If we haven't throttled, just handle response directly.
this.xmlHttpHandler_(xhr);
}
};
/**
* XmlHttp handler
* @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request.
* @private
*/
ChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) {
'use strict';
requestStats.onStartExecution();
try {
if (xmlhttp == this.xmlHttp_) {
this.onXmlHttpReadyStateChanged_();
} else {
this.channelDebug_.warning(
'Called back with an ' +
'unexpected xmlhttp');
}
} catch (ex) {
this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_');
if (this.hasResponseBody_()) {
const channelRequest = this;
this.channelDebug_.dumpException(ex, function() {
'use strict';
return 'ResponseText: ' + channelRequest.xmlHttp_.getResponseText();
});
} else {
this.channelDebug_.dumpException(ex, 'No response text');
}
} finally {
requestStats.onEndExecution();
}
};
/**
* Called by the readystate handler for XMLHTTP requests.
*
* @private
*/
ChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() {
'use strict';
const readyState = this.xmlHttp_.getReadyState();
const errorCode = this.xmlHttp_.getLastErrorCode();
const statusCode = this.xmlHttp_.getStatus();
// we get partial results in browsers that support ready state interactive.
// We also make sure that getResponseText is not null in interactive mode
// before we continue.
if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE ||
(readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&
!environment.isPollingRequired() && // otherwise, go on to startPolling
!this.hasResponseBody_())) {
return; // not yet ready
}
// Dispatch any appropriate network events.
if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&
errorCode != goog.net.ErrorCode.ABORT) {
// Pretty conservative, these are the only known scenarios which we'd
// consider indicative of a truly non-functional network connection.
if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) {
requestStats.notifyServerReachabilityEvent(
requestStats.ServerReachability.REQUEST_FAILED);
} else {
requestStats.notifyServerReachabilityEvent(
requestStats.ServerReachability.REQUEST_SUCCEEDED);
}
}
// got some data so cancel the watchdog timer
this.cancelWatchDogTimer_();
const status = this.xmlHttp_.getStatus();
this.lastStatusCode_ = status;
const responseText = this.decodeXmlHttpResponse_();
if (!this.hasResponseBody_()) {
const channelRequest = this;
this.channelDebug_.debug(function() {
'use strict';
return 'No response text for uri ' + channelRequest.requestUri_ +
' status ' + status;
});
}
this.successful_ = (status == 200);
this.channelDebug_.xmlHttpChannelResponseMetaData(
/** @type {string} */ (this.verb_), this.requestUri_, this.rid_,
this.retryId_, readyState, status);
if (!this.successful_) {
this.errorResponseHeaders_ = this.xmlHttp_.getResponseHeaders();
if (status == 400 && responseText.indexOf('Unknown SID') > 0) {
// the server error string will include 'Unknown SID' which indicates the
// server doesn't know about the session (maybe it got restarted, maybe
// the user got moved to another server, etc.,). Handlers can special
// case this error
this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID;
requestStats.notifyStatEvent(
requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);
this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')');
} else {
this.lastError_ = ChannelRequest.Error.STATUS;
requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_STATUS);
this.channelDebug_.warning(
'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')');
}
this.cleanup_();
this.dispatchFailure_();
return;
}
if (this.shouldCheckInitialResponse_()) {
const initialResponse = this.getInitialResponse_();
if (initialResponse) {
this.channelDebug_.xmlHttpChannelResponseText(
this.rid_, initialResponse,
'Initial handshake response via ' +
WebChannel.X_HTTP_INITIAL_RESPONSE);
this.initialResponseDecoded_ = true;
this.safeOnRequestData_(initialResponse);
} else {
this.successful_ = false;
this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID; // fail-fast
requestStats.notifyStatEvent(
requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);
this.channelDebug_.warning(
'XMLHTTP Missing X_HTTP_INITIAL_RESPONSE' +
' (' + this.rid_ + ')');
this.cleanup_();
this.dispatchFailure_();
return;
}
}
if (this.decodeChunks_) {
this.decodeNextChunks_(readyState, responseText);
if (environment.isPollingRequired() && this.successful_ &&
readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) {
this.startPolling_();
}
} else {
this.channelDebug_.xmlHttpChannelResponseText(
this.rid_, responseText, null);
this.safeOnRequestData_(responseText);
}
if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {
this.cleanup_();
}
if (!this.successful_) {
return;
}
if (!this.cancelled_) {
if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {
this.channel_.onRequestComplete(this);
} else {
// The default is false, the result from this callback shouldn't carry
// over to the next callback, otherwise the request looks successful if
// the watchdog timer gets called
this.successful_ = false;
this.ensureWatchDogTimer_();
}
}
};
/**
* Whether we need check the initial-response header that is sent during the
* fast handshake.
*
* @return {boolean} true if the initial-response header is yet to be processed.
* @private
*/
ChannelRequest.prototype.shouldCheckInitialResponse_ = function() {
'use strict';
return this.decodeInitialResponse_ && !this.initialResponseDecoded_;
};
/**
* Queries the initial response header that is sent during the handshake.
*
* @return {?string} The non-empty header value or null.
* @private
*/
ChannelRequest.prototype.getInitialResponse_ = function() {
'use strict';
if (this.xmlHttp_) {
const value = this.xmlHttp_.getStreamingResponseHeader(
WebChannel.X_HTTP_INITIAL_RESPONSE);
if (value && !goog.string.isEmptyOrWhitespace(value)) {
return value;
}
}
return null;
};
/**
* Check if the initial response header has been handled.
*
* @return {boolean} true if X_HTTP_INITIAL_RESPONSE has been handled.
*/
ChannelRequest.prototype.isInitialResponseDecoded = function() {
'use strict';
return this.initialResponseDecoded_;
};
/**
* Decodes X_HTTP_INITIAL_RESPONSE if present.
*/
ChannelRequest.prototype.setDecodeInitialResponse = function() {
'use strict';
this.decodeInitialResponse_ = true;
};
/**
* Decodes the responses from XhrIo object.
* @returns {string} responseText
* @private
*/
ChannelRequest.prototype.decodeXmlHttpResponse_ = function() {
'use strict';
if (!this.useFetchStreamsForResponse_()) {
return this.xmlHttp_.getResponseText();
}
const responseChunks =
/** @type {!Array<!Uint8Array>} */ (this.xmlHttp_.getResponse());
let responseText = '';
const responseLength = responseChunks.length;
const requestCompleted =
this.xmlHttp_.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;
if (!this.fetchResponseState_.textDecoder) {
if (typeof TextDecoder === 'undefined') {
this.channelDebug_.severe(
'TextDecoder is not supported by this browser.');
this.cleanup_();
this.dispatchFailure_();
return '';
}
this.fetchResponseState_.textDecoder = new goog.global.TextDecoder();
}
for (let i = 0; i < responseLength; i++) {
this.fetchResponseState_.responseArrivedForFetch = true;
const isLastChunk = requestCompleted && i == responseLength - 1;
responseText += this.fetchResponseState_.textDecoder.decode(
responseChunks[i], {stream: isLastChunk});
}
responseChunks.length = 0; // Empty the `responseChunks` array.
this.fetchResponseState_.responseBuffer += responseText;
this.xmlHttpChunkStart_ = 0;
return this.fetchResponseState_.responseBuffer;
};
/**
* Whether or not the response has response body.
* @private
* @returns {boolean}
*/
ChannelRequest.prototype.hasResponseBody_ = function() {
'use strict';
if (!this.xmlHttp_) {
return false;
}
if (this.fetchResponseState_.responseArrivedForFetch) {
return true;
}
return !(!this.xmlHttp_.getResponseText() && !this.xmlHttp_.getResponse());
};
/**
* Whether or not the response body is streamed.
* @private
* @returns {boolean}
*/
ChannelRequest.prototype.useFetchStreamsForResponse_ = function() {
'use strict';
if (!this.xmlHttp_) {
return false;
}
return (
this.verb_ == 'GET' && this.type_ != ChannelRequest.Type_.CLOSE_REQUEST &&
this.channel_.usesFetchStreams());
};
/**
* Decodes the next set of available chunks in the response.
* @param {number} readyState The value of readyState.
* @param {string} responseText The value of responseText.
* @private
*/
ChannelRequest.prototype.decodeNextChunks_ = function(
readyState, responseText) {
'use strict';
let decodeNextChunksSuccessful = true;
let chunkText;
while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) {
chunkText = this.getNextChunk_(responseText);
if (chunkText == ChannelRequest.INCOMPLETE_CHUNK_) {
if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {
// should have consumed entire response when the request is done
this.lastError_ = ChannelRequest.Error.BAD_DATA;
requestStats.notifyStatEvent(requestStats.Stat.REQUEST_INCOMPLETE_DATA);
decodeNextChunksSuccessful = false;
}
this.channelDebug_.xmlHttpChannelResponseText(
this.rid_, null, '[Incomplete Response]');
break;
} else if (chunkText == ChannelRequest.INVALID_CHUNK_) {
this.lastError_ = ChannelRequest.Error.BAD_DATA;
requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_DATA);
this.channelDebug_.xmlHttpChannelResponseText(
this.rid_, responseText, '[Invalid Chunk]');
decodeNextChunksSuccessful = false;
break;
} else {
this.channelDebug_.xmlHttpChannelResponseText(
this.rid_, /** @type {string} */ (chunkText), null);
this.safeOnRequestData_(/** @type {string} */ (chunkText));
}
}
if (this.useFetchStreamsForResponse_() && this.xmlHttpChunkStart_ != 0) {
// Remove processed chunk text from response buffer.
this.fetchResponseState_.responseBuffer =
this.fetchResponseState_.responseBuffer.slice(this.xmlHttpChunkStart_);
this.xmlHttpChunkStart_ = 0;
}
if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&
responseText.length == 0 &&
!this.fetchResponseState_.responseArrivedForFetch) {
// also an error if we didn't get any response
this.lastError_ = ChannelRequest.Error.NO_DATA;
requestStats.notifyStatEvent(requestStats.Stat.REQUEST_NO_DATA);
decodeNextChunksSuccessful = false;
}
this.successful_ = this.successful_ && decodeNextChunksSuccessful;
if (!decodeNextChunksSuccessful) {
// malformed response - we make this trigger retry logic
this.channelDebug_.xmlHttpChannelResponseText(
this.rid_, responseText, '[Invalid Chunked Response]');
this.cleanup_();
this.dispatchFailure_();
} else {
if (responseText.length > 0 && !this.firstByteReceived_) {
this.firstByteReceived_ = true;
this.channel_.onFirstByteReceived(this, responseText);
}
}
};
/**
* Polls the response for new data.
* @private
*/
ChannelRequest.prototype.pollResponse_ = function() {
'use strict';
if (!this.xmlHttp_) {
return; // already closed
}
const readyState = this.xmlHttp_.getReadyState();
const responseText = this.xmlHttp_.getResponseText();
if (this.xmlHttpChunkStart_ < responseText.length) {
this.cancelWatchDogTimer_();
this.decodeNextChunks_(readyState, responseText);
if (this.successful_ &&
readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {
this.ensureWatchDogTimer_();
}
}
};