This repository was archived by the owner on Jul 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathstorageservice.js
More file actions
2222 lines (1976 loc) · 68.2 KB
/
Copy pathstorageservice.js
File metadata and controls
2222 lines (1976 loc) · 68.2 KB
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* This file contains APIs for interacting with the Storage Service API.
*
* The specification for the service is available at.
* http://docs.services.mozilla.com/storage/index.html
*
* Nothing about the spec or the service is Sync-specific. And, that is how
* these APIs are implemented. Instead, it is expected that consumers will
* create a new type inheriting or wrapping those provided by this file.
*
* STORAGE SERVICE OVERVIEW
*
* The storage service is effectively a key-value store where each value is a
* well-defined envelope that stores specific metadata along with a payload.
* These values are called Basic Storage Objects, or BSOs. BSOs are organized
* into named groups called collections.
*
* The service also provides ancillary APIs not related to storage, such as
* looking up the set of stored collections, current quota usage, etc.
*/
"use strict";
this.EXPORTED_SYMBOLS = [
"BasicStorageObject",
"StorageServiceClient",
"StorageServiceRequestError",
];
const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
Cu.import("resource://services-common/async.js");
Cu.import("resource://services-common/log4moz.js");
Cu.import("resource://services-common/preferences.js");
Cu.import("resource://services-common/rest.js");
Cu.import("resource://services-common/utils.js");
const Prefs = new Preferences("services.common.storageservice.");
/**
* The data type stored in the storage service.
*
* A Basic Storage Object (BSO) is the primitive type stored in the storage
* service. BSO's are simply maps with a well-defined set of keys.
*
* BSOs belong to named collections.
*
* A single BSO consists of the following fields:
*
* id - An identifying string. This is how a BSO is uniquely identified within
* a single collection.
* modified - Integer milliseconds since Unix epoch BSO was modified.
* payload - String contents of BSO. The format of the string is undefined
* (although JSON is typically used).
* ttl - The number of seconds to keep this record.
* sortindex - Integer indicating relative importance of record within the
* collection.
*
* The constructor simply creates an empty BSO having the specified ID (which
* can be null or undefined). It also takes an optional collection. This is
* purely for convenience.
*
* This type is meant to be a dumb container and little more.
*
* @param id
* (string) ID of BSO. Can be null.
* (string) Collection BSO belongs to. Can be null;
*/
this.BasicStorageObject =
function BasicStorageObject(id=null, collection=null) {
this.data = {};
this.id = id;
this.collection = collection;
}
BasicStorageObject.prototype = {
id: null,
collection: null,
data: null,
// At the time this was written, the convention for constructor arguments
// was not adopted by Harmony. It could break in the future. We have test
// coverage that will break if SpiderMonkey changes, just in case.
_validKeys: new Set(["id", "payload", "modified", "sortindex", "ttl"]),
/**
* Get the string payload as-is.
*/
get payload() {
return this.data.payload;
},
/**
* Set the string payload to a new value.
*/
set payload(value) {
this.data.payload = value;
},
/**
* Get the modified time of the BSO in milliseconds since Unix epoch.
*
* You can convert this to a native JS Date instance easily:
*
* let date = new Date(bso.modified);
*/
get modified() {
return this.data.modified;
},
/**
* Sets the modified time of the BSO in milliseconds since Unix epoch.
*
* Please note that if this value is sent to the server it will be ignored.
* The server will use its time at the time of the operation when storing the
* BSO.
*/
set modified(value) {
this.data.modified = value;
},
get sortindex() {
if (this.data.sortindex) {
return this.data.sortindex || 0;
}
return 0;
},
set sortindex(value) {
if (!value && value !== 0) {
delete this.data.sortindex;
return;
}
this.data.sortindex = value;
},
get ttl() {
return this.data.ttl;
},
set ttl(value) {
if (!value && value !== 0) {
delete this.data.ttl;
return;
}
this.data.ttl = value;
},
/**
* Deserialize JSON or another object into this instance.
*
* The argument can be a string containing serialized JSON or an object.
*
* If the JSON is invalid or if the object contains unknown fields, an
* exception will be thrown.
*
* @param json
* (string|object) Value to construct BSO from.
*/
deserialize: function deserialize(input) {
let data;
if (typeof(input) == "string") {
data = JSON.parse(input);
if (typeof(data) != "object") {
throw new Error("Supplied JSON is valid but is not a JS-Object.");
}
}
else if (typeof(input) == "object") {
data = input;
} else {
throw new Error("Argument must be a JSON string or object: " +
typeof(input));
}
for each (let key in Object.keys(data)) {
if (key == "id") {
this.id = data.id;
continue;
}
if (!this._validKeys.has(key)) {
throw new Error("Invalid key in object: " + key);
}
this.data[key] = data[key];
}
},
/**
* Serialize the current BSO to JSON.
*
* @return string
* The JSON representation of this BSO.
*/
toJSON: function toJSON() {
let obj = {};
for (let [k, v] in Iterator(this.data)) {
obj[k] = v;
}
if (this.id) {
obj.id = this.id;
}
return obj;
},
toString: function toString() {
return "{ " +
"id: " + this.id + " " +
"modified: " + this.modified + " " +
"ttl: " + this.ttl + " " +
"index: " + this.sortindex + " " +
"payload: " + this.payload +
" }";
},
};
/**
* Represents an error encountered during a StorageServiceRequest request.
*
* Instances of this will be passed to the onComplete callback for any request
* that did not succeed.
*
* This type effectively wraps other error conditions. It is up to the client
* to determine the appropriate course of action for each error type
* encountered.
*
* The following error "classes" are defined by properties on each instance:
*
* serverModified - True if the request to modify data was conditional and
* the server rejected the request because it has newer data than the
* client.
*
* notFound - True if the requested URI or resource does not exist.
*
* conflict - True if the server reported that a resource being operated on
* was in conflict. If this occurs, the client should typically wait a
* little and try the request again.
*
* requestTooLarge - True if the request was too large for the server. If
* this happens on batch requests, the client should retry the request with
* smaller batches.
*
* network - A network error prevented this request from succeeding. If set,
* it will be an Error thrown by the Gecko network stack. If set, it could
* mean that the request could not be performed or that an error occurred
* when the request was in flight. It is also possible the request
* succeeded on the server but the response was lost in transit.
*
* authentication - If defined, an authentication error has occurred. If
* defined, it will be an Error instance. If seen, the client should not
* retry the request without first correcting the authentication issue.
*
* client - An error occurred which was the client's fault. This typically
* means the code in this file is buggy.
*
* server - An error occurred on the server. In the ideal world, this should
* never happen. But, it does. If set, this will be an Error which
* describes the error as reported by the server.
*/
this.StorageServiceRequestError = function StorageServiceRequestError() {
this.serverModified = false;
this.notFound = false;
this.conflict = false;
this.requestToolarge = false;
this.network = null;
this.authentication = null;
this.client = null;
this.server = null;
}
/**
* Represents a single request to the storage service.
*
* Instances of this type are returned by the APIs on StorageServiceClient.
* They should not be created outside of StorageServiceClient.
*
* This type encapsulates common storage API request and response handling.
* Metadata required to perform the request is stored inside each instance and
* should be treated as invisible by consumers.
*
* A number of "public" properties are exposed to allow clients to further
* customize behavior. These are documented below.
*
* Some APIs in StorageServiceClient define their own types which inherit from
* this one. Read the API documentation to see which types those are and when
* they apply.
*
* This type wraps RESTRequest rather than extending it. The reason is mainly
* to avoid the fragile base class problem. We implement considerable extra
* functionality on top of RESTRequest and don't want this to accidentally
* trample on RESTRequest's members.
*
* If this were a C++ class, it and StorageServiceClient would be friend
* classes. Each touches "protected" APIs of the other. Thus, each should be
* considered when making changes to the other.
*
* Usage
* =====
*
* When you obtain a request instance, it is waiting to be dispatched. It may
* have additional settings available for tuning. See the documentation in
* StorageServiceClient for more.
*
* There are essentially two types of requests: "basic" and "streaming."
* "Basic" requests encapsulate the traditional request-response paradigm:
* a request is issued and we get a response later once the full response
* is available. Most of the APIs in StorageServiceClient issue these "basic"
* requests. Streaming requests typically involve the transport of multiple
* BasicStorageObject instances. When a new BSO instance is available, a
* callback is fired.
*
* For basic requests, the general flow looks something like:
*
* // Obtain a new request instance.
* let request = client.getCollectionInfo();
*
* // Install a handler which provides callbacks for request events. The most
* // important is `onComplete`, which is called when the request has
* // finished and the response is completely received.
* request.handler = {
* onComplete: function onComplete(error, request) {
* // Do something.
* }
* };
*
* // Send the request.
* request.dispatch();
*
* Alternatively, we can install the onComplete handler when calling dispatch:
*
* let request = client.getCollectionInfo();
* request.dispatch(function onComplete(error, request) {
* // Handle response.
* });
*
* Please note that installing an `onComplete` handler as the argument to
* `dispatch()` will overwrite an existing `handler`.
*
* In both of the above example, the two `request` variables are identical. The
* original `StorageServiceRequest` is passed into the callback so callers
* don't need to rely on closures.
*
* Most of the complexity for onComplete handlers is error checking.
*
* The first thing you do in your onComplete handler is ensure no error was
* seen:
*
* function onComplete(error, request) {
* if (error) {
* // Handle error.
* }
* }
*
* If `error` is defined, it will be an instance of
* `StorageServiceRequestError`. An error will be set if the request didn't
* complete successfully. This means the transport layer must have succeeded
* and the application protocol (HTTP) must have returned a successful status
* code (2xx and some 3xx). Please see the documentation for
* `StorageServiceRequestError` for more.
*
* A robust error handler would look something like:
*
* function onComplete(error, request) {
* if (error) {
* if (error.network) {
* // Network error encountered!
* } else if (error.server) {
* // Something went wrong on the server (HTTP 5xx).
* } else if (error.authentication) {
* // Server rejected request due to bad credentials.
* } else if (error.serverModified) {
* // The conditional request was rejected because the server has newer
* // data than what the client reported.
* } else if (error.conflict) {
* // The server reported that the operation could not be completed
* // because another client is also updating it.
* } else if (error.requestTooLarge) {
* // The server rejected the request because it was too large.
* } else if (error.notFound) {
* // The requested resource was not found.
* } else if (error.client) {
* // Something is wrong with the client's request. You should *never*
* // see this, as it means this client is likely buggy. It could also
* // mean the server is buggy or misconfigured. Either way, something
* // is buggy.
* }
*
* return;
* }
*
* // Handle successful case.
* }
*
* If `error` is null, the request completed successfully. There may or may not
* be additional data available on the request instance.
*
* For requests that obtain data, this data is typically made available through
* the `resultObj` property on the request instance. The API that was called
* will install its own response hander and ensure this property is decoded to
* what you expect.
*
* Conditional Requests
* --------------------
*
* Many of the APIs on `StorageServiceClient` support conditional requests.
* That is, the client defines the last version of data it has (the version
* comes from a previous response from the server) and sends this as part of
* the request.
*
* For query requests, if the server hasn't changed, no new data will be
* returned. If issuing a conditional query request, the caller should check
* the `notModified` property on the request in the response callback. If this
* property is true, the server has no new data and there is obviously no data
* on the response.
*
* For example:
*
* let request = client.getCollectionInfo();
* request.locallyModifiedVersion = Date.now() - 60000;
* request.dispatch(function onComplete(error, request) {
* if (error) {
* // Handle error.
* return;
* }
*
* if (request.notModified) {
* return;
* }
*
* let info = request.resultObj;
* // Do stuff.
* });
*
* For modification requests, if the server has changed, the request will be
* rejected. When this happens, `error`will be defined and the `serverModified`
* property on it will be true.
*
* For example:
*
* let request = client.setBSO(bso);
* request.locallyModifiedVersion = bso.modified;
* request.dispatch(function onComplete(error, request) {
* if (error) {
* if (error.serverModified) {
* // Server data is newer! We should probably fetch it and apply
* // locally.
* }
*
* return;
* }
*
* // Handle success.
* });
*
* Future Features
* ---------------
*
* The current implementation does not support true streaming for things like
* multi-BSO retrieval. However, the API supports it, so we should be able
* to implement it transparently.
*/
function StorageServiceRequest() {
this._log = Log4Moz.repository.getLogger("Sync.StorageService.Request");
this._log.level = Log4Moz.Level[Prefs.get("log.level")];
this.notModified = false;
this._client = null;
this._request = null;
this._method = null;
this._handler = {};
this._data = null;
this._error = null;
this._resultObj = null;
this._locallyModifiedVersion = null;
this._allowIfModified = false;
this._allowIfUnmodified = false;
}
StorageServiceRequest.prototype = {
/**
* The StorageServiceClient this request came from.
*/
get client() {
return this._client;
},
/**
* The underlying RESTRequest instance.
*
* This should be treated as read only and should not be modified
* directly by external callers. While modification would probably work, this
* would defeat the purpose of the API and the abstractions it is meant to
* provide.
*
* If a consumer needs to modify the underlying request object, it is
* recommended for them to implement a new type that inherits from
* StorageServiceClient and override the necessary APIs to modify the request
* there.
*
* This accessor may disappear in future versions.
*/
get request() {
return this._request;
},
/**
* The RESTResponse that resulted from the RESTRequest.
*/
get response() {
return this._request.response;
},
/**
* HTTP status code from response.
*/
get statusCode() {
let response = this.response;
return response ? response.status : null;
},
/**
* Holds any error that has occurred.
*
* If a network error occurred, that will be returned. If no network error
* occurred, the client error will be returned. If no error occurred (yet),
* null will be returned.
*/
get error() {
return this._error;
},
/**
* The result from the request.
*
* This stores the object returned from the server. The type of object depends
* on the request type. See the per-API documentation in StorageServiceClient
* for details.
*/
get resultObj() {
return this._resultObj;
},
/**
* Define the local version of the entity the client has.
*
* This is used to enable conditional requests. Depending on the request
* type, the value set here could be reflected in the X-If-Modified-Since or
* X-If-Unmodified-Since headers.
*
* This attribute is not honoured on every request. See the documentation
* in the client API to learn where it is valid.
*/
set locallyModifiedVersion(value) {
// Will eventually become a header, so coerce to string.
this._locallyModifiedVersion = "" + value;
},
/**
* Object which holds callbacks and state for this request.
*
* The handler is installed by users of this request. It is simply an object
* containing 0 or more of the following properties:
*
* onComplete - A function called when the request has completed and all
* data has been received from the server. The function receives the
* following arguments:
*
* (StorageServiceRequestError) Error encountered during request. null
* if no error was encountered.
* (StorageServiceRequest) The request that was sent (this instance).
* Response information is available via properties and functions.
*
* Unless the call to dispatch() throws before returning, this callback
* is guaranteed to be invoked.
*
* Every client almost certainly wants to install this handler.
*
* onDispatch - A function called immediately before the request is
* dispatched. This hook can be used to inspect or modify the request
* before it is issued.
*
* The called function receives the following arguments:
*
* (StorageServiceRequest) The request being issued (this request).
*
* onBSORecord - When retrieving multiple BSOs from the server, this
* function is invoked when a new BSO record has been read. This function
* will be invoked 0 to N times before onComplete is invoked. onComplete
* signals that the last BSO has been processed or that an error
* occurred. The function receives the following arguments:
*
* (StorageServiceRequest) The request that was sent (this instance).
* (BasicStorageObject|string) The received BSO instance (when in full
* mode) or the string ID of the BSO (when not in full mode).
*
* Callers are free to (and encouraged) to store extra state in the supplied
* handler.
*/
set handler(value) {
if (typeof(value) != "object") {
throw new Error("Invalid handler. Must be an Object.");
}
this._handler = value;
if (!value.onComplete) {
this._log.warn("Handler does not contain an onComplete callback!");
}
},
get handler() {
return this._handler;
},
//---------------
// General APIs |
//---------------
/**
* Start the request.
*
* The request is dispatched asynchronously. The installed handler will have
* one or more of its callbacks invoked as the state of the request changes.
*
* The `onComplete` argument is optional. If provided, the supplied function
* will be installed on a *new* handler before the request is dispatched. This
* is equivalent to calling:
*
* request.handler = {onComplete: value};
* request.dispatch();
*
* Please note that any existing handler will be replaced if onComplete is
* provided.
*
* @param onComplete
* (function) Callback to be invoked when request has completed.
*/
dispatch: function dispatch(onComplete) {
if (onComplete) {
this.handler = {onComplete: onComplete};
}
// Installing the dummy callback makes implementation easier in _onComplete
// because we can then blindly call.
this._dispatch(function _internalOnComplete(error) {
this._onComplete(error);
this.completed = true;
}.bind(this));
},
/**
* This is a synchronous version of dispatch().
*
* THIS IS AN EVIL FUNCTION AND SHOULD NOT BE CALLED. It is provided for
* legacy reasons to support evil, synchronous clients.
*
* Please note that onComplete callbacks are executed from this JS thread.
* We dispatch the request, spin the event loop until it comes back. Then,
* we execute callbacks ourselves then return. In other words, there is no
* potential for spinning between callback execution and this function
* returning.
*
* The `onComplete` argument has the same behavior as for `dispatch()`.
*
* @param onComplete
* (function) Callback to be invoked when request has completed.
*/
dispatchSynchronous: function dispatchSynchronous(onComplete) {
if (onComplete) {
this.handler = {onComplete: onComplete};
}
let cb = Async.makeSyncCallback();
this._dispatch(cb);
let error = Async.waitForSyncCallback(cb);
this._onComplete(error);
this.completed = true;
},
//-------------------------------------------------------------------------
// HIDDEN APIS. DO NOT CHANGE ANYTHING UNDER HERE FROM OUTSIDE THIS TYPE. |
//-------------------------------------------------------------------------
/**
* Data to include in HTTP request body.
*/
_data: null,
/**
* StorageServiceRequestError encountered during dispatchy.
*/
_error: null,
/**
* Handler to parse response body into another object.
*
* This is installed by the client API. It should return the value the body
* parses to on success. If a failure is encountered, an exception should be
* thrown.
*/
_completeParser: null,
/**
* Dispatch the request.
*
* This contains common functionality for dispatching requests. It should
* ideally be part of dispatch, but since dispatchSynchronous exists, we
* factor out common code.
*/
_dispatch: function _dispatch(onComplete) {
// RESTRequest throws if the request has already been dispatched, so we
// need not bother checking.
// Inject conditional headers into request if they are allowed and if a
// value is set. Note that _locallyModifiedVersion is always a string and
// if("0") is true.
if (this._allowIfModified && this._locallyModifiedVersion) {
this._log.trace("Making request conditional.");
this._request.setHeader("X-If-Modified-Since",
this._locallyModifiedVersion);
} else if (this._allowIfUnmodified && this._locallyModifiedVersion) {
this._log.trace("Making request conditional.");
this._request.setHeader("X-If-Unmodified-Since",
this._locallyModifiedVersion);
}
// We have both an internal and public hook.
// If these throw, it is OK since we are not in a callback.
if (this._onDispatch) {
this._onDispatch();
}
if (this._handler.onDispatch) {
this._handler.onDispatch(this);
}
this._client.runListeners("onDispatch", this);
this._log.info("Dispatching request: " + this._method + " " +
this._request.uri.asciiSpec);
this._request.dispatch(this._method, this._data, onComplete);
},
/**
* RESTRequest onComplete handler for all requests.
*
* This provides common logic for all response handling.
*/
_onComplete: function(error) {
let onCompleteCalled = false;
let callOnComplete = function callOnComplete() {
onCompleteCalled = true;
if (!this._handler.onComplete) {
this._log.warn("No onComplete installed in handler!");
return;
}
try {
this._handler.onComplete(this._error, this);
} catch (ex) {
this._log.warn("Exception when invoking handler's onComplete: " +
CommonUtils.exceptionStr(ex));
throw ex;
}
}.bind(this);
try {
if (error) {
this._error = new StorageServiceRequestError();
this._error.network = error;
this._log.info("Network error during request: " + error);
this._client.runListeners("onNetworkError", this._client, this, error);
callOnComplete();
return;
}
let response = this._request.response;
this._log.info(response.status + " " + this._request.uri.asciiSpec);
this._processHeaders();
if (response.status == 200) {
this._resultObj = this._completeParser(response);
callOnComplete();
return;
}
if (response.status == 201) {
callOnComplete();
return;
}
if (response.status == 204) {
callOnComplete();
return;
}
if (response.status == 304) {
this.notModified = true;
callOnComplete();
return;
}
// TODO handle numeric response code from server.
if (response.status == 400) {
this._error = new StorageServiceRequestError();
this._error.client = new Error("Client error!");
callOnComplete();
return;
}
if (response.status == 401) {
this._error = new StorageServiceRequestError();
this._error.authentication = new Error("401 Received.");
this._client.runListeners("onAuthFailure", this._error.authentication,
this);
callOnComplete();
return;
}
if (response.status == 404) {
this._error = new StorageServiceRequestError();
this._error.notFound = true;
callOnComplete();
return;
}
if (response.status == 409) {
this._error = new StorageServiceRequestError();
this._error.conflict = true;
callOnComplete();
return;
}
if (response.status == 412) {
this._error = new StorageServiceRequestError();
this._error.serverModified = true;
callOnComplete();
return;
}
if (response.status == 413) {
this._error = new StorageServiceRequestError();
this._error.requestTooLarge = true;
callOnComplete();
return;
}
// If we see this, either the client or the server is buggy. We should
// never see this.
if (response.status == 415) {
this._log.error("415 HTTP response seen from server! This should " +
"never happen!");
this._error = new StorageServiceRequestError();
this._error.client = new Error("415 Unsupported Media Type received!");
callOnComplete();
return;
}
if (response.status >= 500 && response.status <= 599) {
this._log.error(response.status + " seen from server!");
this._error = new StorageServiceRequestError();
this._error.server = new Error(response.status + " status code.");
callOnComplete();
return;
}
callOnComplete();
} catch (ex) {
this._clientError = ex;
this._log.info("Exception when processing _onComplete: " + ex);
if (!onCompleteCalled) {
this._log.warn("Exception in internal response handling logic!");
try {
callOnComplete();
} catch (ex) {
this._log.warn("An additional exception was encountered when " +
"calling the handler's onComplete: " + ex);
}
}
}
},
_processHeaders: function _processHeaders() {
let headers = this._request.response.headers;
if (headers["x-timestamp"]) {
this.serverTime = parseFloat(headers["x-timestamp"]);
}
if (headers["x-backoff"]) {
this.backoffInterval = 1000 * parseInt(headers["x-backoff"], 10);
}
if (headers["retry-after"]) {
this.backoffInterval = 1000 * parseInt(headers["retry-after"], 10);
}
if (this.backoffInterval) {
let failure = this._request.response.status == 503;
this._client.runListeners("onBackoffReceived", this._client, this,
this.backoffInterval, !failure);
}
if (headers["x-quota-remaining"]) {
this.quotaRemaining = parseInt(headers["x-quota-remaining"], 10);
this._client.runListeners("onQuotaRemaining", this._client, this,
this.quotaRemaining);
}
},
};
/**
* Represents a request to fetch from a collection.
*
* These requests are highly configurable so they are given their own type.
* This type inherits from StorageServiceRequest and provides additional
* controllable parameters.
*
* By default, requests are issued in "streaming" mode. As the client receives
* data from the server, it will invoke the caller-supplied onBSORecord
* callback for each record as it is ready. When all records have been received,
* it will invoke onComplete as normal. To change this behavior, modify the
* "streaming" property before the request is dispatched.
*/
function StorageCollectionGetRequest() {
StorageServiceRequest.call(this);
}
StorageCollectionGetRequest.prototype = {
__proto__: StorageServiceRequest.prototype,
_namedArgs: {},
_streaming: true,
/**
* Control whether streaming mode is in effect.
*
* Read the type documentation above for more details.
*/
set streaming(value) {
this._streaming = !!value;
},
/**
* Define the set of IDs to fetch from the server.
*/
set ids(value) {
this._namedArgs.ids = value.join(",");
},
/**
* Only retrieve BSOs that were modified strictly before this time.
*
* Defined in milliseconds since UNIX epoch.
*/
set older(value) {
this._namedArgs.older = value;
},
/**
* Only retrieve BSOs that were modified strictly after this time.
*
* Defined in milliseconds since UNIX epoch.
*/
set newer(value) {
this._namedArgs.newer = value;
},
/**
* If set to a truthy value, return full BSO information.
*
* If not set (the default), the request will only return the set of BSO
* ids.
*/
set full(value) {
if (value) {
this._namedArgs.full = "1";
} else {
delete this._namedArgs["full"];
}
},
/**