-
Notifications
You must be signed in to change notification settings - Fork 7
/
odatajs-4.0.0-beta-01.js
8025 lines (6819 loc) · 277 KB
/
odatajs-4.0.0-beta-01.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* !! Modified by Michael Bromley on line 2089
*/
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var odatajs = require('./lib/odatajs.js');
odatajs.oData = require('./lib/odata.js');
odatajs.store = require('./lib/store.js');
odatajs.cache = require('./lib/cache.js');
if (typeof window !== 'undefined') {
//expose to browsers window object
window.odatajs = odatajs;
} else {
//expose in commonjs style
odatajs.node = "node";
module.exports = odatajs;
}
},{"./lib/cache.js":2,"./lib/odata.js":4,"./lib/odatajs.js":11,"./lib/store.js":15}],2:[function(require,module,exports){
/** @module cache */
var odatajs = require('./odatajs.js');
var utils = odatajs.utils;
var deferred = odatajs.deferred;
var storeReq = odatajs.store;
var cacheSource = require('./cache/source');
var assigned = utils.assigned;
var delay = utils.delay;
var extend = utils.extend;
var djsassert = utils.djsassert;
var isArray = utils.isArray;
var normalizeURI = utils.normalizeURI;
var parseInt10 = utils.parseInt10;
var undefinedDefault = utils.undefinedDefault;
var createDeferred = deferred.createDeferred;
var DjsDeferred = deferred.DjsDeferred;
var getJsonValueArraryLength = utils.getJsonValueArraryLength;
var sliceJsonValueArray = utils.sliceJsonValueArray;
var concatJsonValueArray = utils.concatJsonValueArray;
/** Appends a page's data to the operation data.
* @param {Object} operation - Operation with (i)ndex, (c)ount and (d)ata.
* @param {Object} page - Page with (i)ndex, (c)ount and (d)ata.
*/
function appendPage(operation, page) {
var intersection = intersectRanges(operation, page);
var start = 0;
var end = 0;
if (intersection) {
start = intersection.i - page.i;
end = start + (operation.c - getJsonValueArraryLength(operation.d));
}
operation.d = concatJsonValueArray(operation.d, sliceJsonValueArray(page.d, start, end));
}
/** Returns the {(i)ndex, (c)ount} range for the intersection of x and y.
* @param {Object} x - Range with (i)ndex and (c)ount members.
* @param {Object} y - Range with (i)ndex and (c)ount members.
* @returns {Object} The intersection (i)ndex and (c)ount; undefined if there is no intersection.
*/
function intersectRanges(x, y) {
var xLast = x.i + x.c;
var yLast = y.i + y.c;
var resultIndex = (x.i > y.i) ? x.i : y.i;
var resultLast = (xLast < yLast) ? xLast : yLast;
var result;
if (resultLast >= resultIndex) {
result = { i: resultIndex, c: resultLast - resultIndex };
}
return result;
}
/** Checks whether val is a defined number with value zero or greater.
* @param {Number} val - Value to check.
* @param {String} name - Parameter name to use in exception.
* @throws Throws an exception if the check fails
*/
function checkZeroGreater(val, name) {
if (val === undefined || typeof val !== "number") {
throw { message: "'" + name + "' must be a number." };
}
if (isNaN(val) || val < 0 || !isFinite(val)) {
throw { message: "'" + name + "' must be greater than or equal to zero." };
}
}
/** Checks whether val is undefined or a number with value greater than zero.
* @param {Number} val - Value to check.
* @param {String} name - Parameter name to use in exception.
* @throws Throws an exception if the check fails
*/
function checkUndefinedGreaterThanZero(val, name) {
if (val !== undefined) {
if (typeof val !== "number") {
throw { message: "'" + name + "' must be a number." };
}
if (isNaN(val) || val <= 0 || !isFinite(val)) {
throw { message: "'" + name + "' must be greater than zero." };
}
}
}
/** Checks whether val is undefined or a number
* @param {Number} val - Value to check.
* @param {String} name - Parameter name to use in exception.
* @throws Throws an exception if the check fails
*/
function checkUndefinedOrNumber(val, name) {
if (val !== undefined && (typeof val !== "number" || isNaN(val) || !isFinite(val))) {
throw { message: "'" + name + "' must be a number." };
}
}
/** Performs a linear search on the specified array and removes the first instance of 'item'.
* @param {Array} arr - Array to search.
* @param {*} item - Item being sought.
* @returns {Boolean} true if the item was removed otherwise false
*/
function removeFromArray(arr, item) {
var i, len;
for (i = 0, len = arr.length; i < len; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
return true;
}
}
return false;
}
/** Estimates the size of an object in bytes.
* Object trees are traversed recursively
* @param {Object} object - Object to determine the size of.
* @returns {Integer} Estimated size of the object in bytes.
*/
function estimateSize(object) {
var size = 0;
var type = typeof object;
if (type === "object" && object) {
for (var name in object) {
size += name.length * 2 + estimateSize(object[name]);
}
} else if (type === "string") {
size = object.length * 2;
} else {
size = 8;
}
return size;
}
/** Snaps low and high indices into page sizes and returns a range.
* @param {Number} lowIndex - Low index to snap to a lower value.
* @param {Number} highIndex - High index to snap to a higher value.
* @param {Number} pageSize - Page size to snap to.
* @returns {Object} A range with (i)ndex and (c)ount of elements.
*/
function snapToPageBoundaries(lowIndex, highIndex, pageSize) {
lowIndex = Math.floor(lowIndex / pageSize) * pageSize;
highIndex = Math.ceil((highIndex + 1) / pageSize) * pageSize;
return { i: lowIndex, c: highIndex - lowIndex };
}
// The DataCache is implemented using state machines. The following constants are used to properly
// identify and label the states that these machines transition to.
var CACHE_STATE_DESTROY = "destroy";
var CACHE_STATE_IDLE = "idle";
var CACHE_STATE_INIT = "init";
var CACHE_STATE_READ = "read";
var CACHE_STATE_PREFETCH = "prefetch";
var CACHE_STATE_WRITE = "write";
// DataCacheOperation state machine states.
// Transitions on operations also depend on the cache current of the cache.
var OPERATION_STATE_CANCEL = "cancel";
var OPERATION_STATE_END = "end";
var OPERATION_STATE_ERROR = "error";
var OPERATION_STATE_START = "start";
var OPERATION_STATE_WAIT = "wait";
// Destroy state machine states
var DESTROY_STATE_CLEAR = "clear";
// Read / Prefetch state machine states
var READ_STATE_DONE = "done";
var READ_STATE_LOCAL = "local";
var READ_STATE_SAVE = "save";
var READ_STATE_SOURCE = "source";
/** Creates a new operation object.
* @class DataCacheOperation
* @param {Function} stateMachine - State machine that describes the specific behavior of the operation.
* @param {DjsDeferred} promise - Promise for requested values.
* @param {Boolean} isCancelable - Whether this operation can be canceled or not.
* @param {Number} index - Index of first item requested.
* @param {Number} count - Count of items requested.
* @param {Array} data - Array with the items requested by the operation.
* @param {Number} pending - Total number of pending prefetch records.
* @returns {DataCacheOperation} A new data cache operation instance.
*/
function DataCacheOperation(stateMachine, promise, isCancelable, index, count, data, pending) {
/// <field name="p" type="DjsDeferred">Promise for requested values.</field>
/// <field name="i" type="Number">Index of first item requested.</field>
/// <field name="c" type="Number">Count of items requested.</field>
/// <field name="d" type="Array">Array with the items requested by the operation.</field>
/// <field name="s" type="Array">Current state of the operation.</field>
/// <field name="canceled" type="Boolean">Whether the operation has been canceled.</field>
/// <field name="pending" type="Number">Total number of pending prefetch records.</field>
/// <field name="oncomplete" type="Function">Callback executed when the operation reaches the end state.</field>
var stateData;
var cacheState;
var that = this;
that.p = promise;
that.i = index;
that.c = count;
that.d = data;
that.s = OPERATION_STATE_START;
that.canceled = false;
that.pending = pending;
that.oncomplete = null;
/** Transitions this operation to the cancel state and sets the canceled flag to true.
* The function is a no-op if the operation is non-cancelable.</summary>
* @method DataCacheOperation#cancel
*/
that.cancel = function cancel() {
if (!isCancelable) {
return;
}
var state = that.s;
if (state !== OPERATION_STATE_ERROR && state !== OPERATION_STATE_END && state !== OPERATION_STATE_CANCEL) {
that.canceled = true;
transition(OPERATION_STATE_CANCEL, stateData);
}
};
/** Transitions this operation to the end state.
* @method DataCacheOperation#complete
*/
that.complete = function () {
djsassert(that.s !== OPERATION_STATE_END, "DataCacheOperation.complete() - operation is in the end state", that);
transition(OPERATION_STATE_END, stateData);
};
/** Transitions this operation to the error state.
* @method DataCacheOperation#error
*/
that.error = function (err) {
if (!that.canceled) {
djsassert(that.s !== OPERATION_STATE_END, "DataCacheOperation.error() - operation is in the end state", that);
djsassert(that.s !== OPERATION_STATE_ERROR, "DataCacheOperation.error() - operation is in the error state", that);
transition(OPERATION_STATE_ERROR, err);
}
};
/** Executes the operation's current state in the context of a new cache state.
* @method DataCacheOperation#run
* @param {Object} state - New cache state.
*/
that.run = function (state) {
cacheState = state;
that.transition(that.s, stateData);
};
/** Transitions this operation to the wait state.
* @method DataCacheOperation#wait
*/
that.wait = function (data) {
djsassert(that.s !== OPERATION_STATE_END, "DataCacheOperation.wait() - operation is in the end state", that);
transition(OPERATION_STATE_WAIT, data);
};
/** State machine that describes all operations common behavior.
* @method DataCacheOperation#operationStateMachine
* @param {Object} opTargetState - Operation state to transition to.
* @param {Object} cacheState - Current cache state.
* @param {Object} [data] - Additional data passed to the state.
*/
var operationStateMachine = function (opTargetState, cacheState, data) {
switch (opTargetState) {
case OPERATION_STATE_START:
// Initial state of the operation. The operation will remain in this state until the cache has been fully initialized.
if (cacheState !== CACHE_STATE_INIT) {
stateMachine(that, opTargetState, cacheState, data);
}
break;
case OPERATION_STATE_WAIT:
// Wait state indicating that the operation is active but waiting for an asynchronous operation to complete.
stateMachine(that, opTargetState, cacheState, data);
break;
case OPERATION_STATE_CANCEL:
// Cancel state.
stateMachine(that, opTargetState, cacheState, data);
that.fireCanceled();
transition(OPERATION_STATE_END);
break;
case OPERATION_STATE_ERROR:
// Error state. Data is expected to be an object detailing the error condition.
stateMachine(that, opTargetState, cacheState, data);
that.canceled = true;
that.fireRejected(data);
transition(OPERATION_STATE_END);
break;
case OPERATION_STATE_END:
// Final state of the operation.
if (that.oncomplete) {
that.oncomplete(that);
}
if (!that.canceled) {
that.fireResolved();
}
stateMachine(that, opTargetState, cacheState, data);
break;
default:
// Any other state is passed down to the state machine describing the operation's specific behavior.
// DATAJS INTERNAL START
if (true) {
// Check that the state machine actually handled the sate.
var handled = stateMachine(that, opTargetState, cacheState, data);
djsassert(handled, "Bad operation state: " + opTargetState + " cacheState: " + cacheState, this);
} else {
// DATAJS INTERNAL END
stateMachine(that, opTargetState, cacheState, data);
// DATAJS INTERNAL START
}
// DATAJS INTERNAL END
break;
}
};
/** Transitions this operation to a new state.
* @method DataCacheOperation#transition
* @param {Object} state - State to transition the operation to.
* @param {Object} [data] -
*/
var transition = function (state, data) {
that.s = state;
stateData = data;
operationStateMachine(state, cacheState, data);
};
that.transition = transition;
return that;
}
/** Fires a resolved notification as necessary.
* @method DataCacheOperation#fireResolved
*/
DataCacheOperation.prototype.fireResolved = function () {
// Fire the resolve just once.
var p = this.p;
if (p) {
this.p = null;
p.resolve(this.d);
}
};
/** Fires a rejected notification as necessary.
* @method DataCacheOperation#fireRejected
*/
DataCacheOperation.prototype.fireRejected = function (reason) {
// Fire the rejection just once.
var p = this.p;
if (p) {
this.p = null;
p.reject(reason);
}
};
/** Fires a canceled notification as necessary.
* @method DataCacheOperation#fireCanceled
*/
DataCacheOperation.prototype.fireCanceled = function () {
this.fireRejected({ canceled: true, message: "Operation canceled" });
};
/** Creates a data cache for a collection that is efficiently loaded on-demand.
* @class DataCache
* @param options - Options for the data cache, including name, source, pageSize,
* prefetchSize, cacheSize, storage mechanism, and initial prefetch and local-data handler.
* @returns {DataCache} A new data cache instance.
*/
function DataCache(options) {
var state = CACHE_STATE_INIT;
var stats = { counts: 0, netReads: 0, prefetches: 0, cacheReads: 0 };
var clearOperations = [];
var readOperations = [];
var prefetchOperations = [];
var actualCacheSize = 0; // Actual cache size in bytes.
var allDataLocal = false; // Whether all data is local.
var cacheSize = undefinedDefault(options.cacheSize, 1048576); // Requested cache size in bytes, default 1 MB.
var collectionCount = 0; // Number of elements in the server collection.
var highestSavedPage = 0; // Highest index of all the saved pages.
var highestSavedPageSize = 0; // Item count of the saved page with the highest index.
var overflowed = cacheSize === 0; // If the cache has overflowed (actualCacheSize > cacheSize or cacheSize == 0);
var pageSize = undefinedDefault(options.pageSize, 50); // Number of elements to store per page.
var prefetchSize = undefinedDefault(options.prefetchSize, pageSize); // Number of elements to prefetch from the source when the cache is idling.
var version = "1.0";
var cacheFailure;
var pendingOperations = 0;
var source = options.source;
if (typeof source === "string") {
// Create a new cache source.
source = new cacheSource.ODataCacheSource(options);
}
source.options = options;
// Create a cache local store.
var store = storeReq.createStore(options.name, options.mechanism);
var that = this;
that.onidle = options.idle;
that.stats = stats;
/** Counts the number of items in the collection.
* @method DataCache#count
* @returns {Object} A promise with the number of items.
*/
that.count = function () {
if (cacheFailure) {
throw cacheFailure;
}
var deferred = createDeferred();
var canceled = false;
if (allDataLocal) {
delay(function () {
deferred.resolve(collectionCount);
});
return deferred.promise();
}
// TODO: Consider returning the local data count instead once allDataLocal flag is set to true.
var request = source.count(function (count) {
request = null;
stats.counts++;
deferred.resolve(count);
}, function (err) {
request = null;
deferred.reject(extend(err, { canceled: canceled }));
});
return extend(deferred.promise(), {
/** Aborts the count operation (used within promise callback)
* @method DataCache#cancelCount
*/
cancel: function () {
if (request) {
canceled = true;
request.abort();
request = null;
}
}
});
};
/** Cancels all running operations and clears all local data associated with this cache.
* New read requests made while a clear operation is in progress will not be canceled.
* Instead they will be queued for execution once the operation is completed.
* @method DataCache#clear
* @returns {Object} A promise that has no value and can't be canceled.
*/
that.clear = function () {
if (cacheFailure) {
throw cacheFailure;
}
if (clearOperations.length === 0) {
var deferred = createDeferred();
var op = new DataCacheOperation(destroyStateMachine, deferred, false);
queueAndStart(op, clearOperations);
return deferred.promise();
}
return clearOperations[0].p;
};
/** Filters the cache data based a predicate.
* Specifying a negative count value will yield all the items in the cache that satisfy the predicate.
* @method DataCache#filterForward
* @param {Number} index - The index of the item to start filtering forward from.
* @param {Number} count - Maximum number of items to include in the result.
* @param {Function} predicate - Callback function returning a boolean that determines whether an item should be included in the result or not.
* @returns {DjsDeferred} A promise for an array of results.
*/
that.filterForward = function (index, count, predicate) {
return filter(index, count, predicate, false);
};
/** Filters the cache data based a predicate.
* Specifying a negative count value will yield all the items in the cache that satisfy the predicate.
* @method DataCache#filterBack
* @param {Number} index - The index of the item to start filtering backward from.
* @param {Number} count - Maximum number of items to include in the result.
* @param {Function} predicate - Callback function returning a boolean that determines whether an item should be included in the result or not.
* @returns {DjsDeferred} A promise for an array of results.
*/
that.filterBack = function (index, count, predicate) {
return filter(index, count, predicate, true);
};
/** Reads a range of adjacent records.
* New read requests made while a clear operation is in progress will not be canceled.
* Instead they will be queued for execution once the operation is completed.
* @method DataCache#readRange
* @param {Number} index - Zero-based index of record range to read.
* @param {Number} count - Number of records in the range.
* @returns {DjsDeferred} A promise for an array of records; less records may be returned if the
* end of the collection is found.
*/
that.readRange = function (index, count) {
checkZeroGreater(index, "index");
checkZeroGreater(count, "count");
if (cacheFailure) {
throw cacheFailure;
}
var deferred = createDeferred();
// Merging read operations would be a nice optimization here.
var op = new DataCacheOperation(readStateMachine, deferred, true, index, count, {}, 0);
queueAndStart(op, readOperations);
return extend(deferred.promise(), {
cancel: function () {
/** Aborts the readRange operation (used within promise callback)
* @method DataCache#cancelReadRange
*/
op.cancel();
}
});
};
/** Creates an Observable object that enumerates all the cache contents.
* @method DataCache#toObservable
* @returns A new Observable object that enumerates all the cache contents.
*/
that.ToObservable = that.toObservable = function () {
if ( !utils.inBrowser()) {
throw { message: "Only in broser supported" };
}
if (!window.Rx || !window.Rx.Observable) {
throw { message: "Rx library not available - include rx.js" };
}
if (cacheFailure) {
throw cacheFailure;
}
return new window.Rx.Observable(function (obs) {
var disposed = false;
var index = 0;
var errorCallback = function (error) {
if (!disposed) {
obs.onError(error);
}
};
var successCallback = function (data) {
if (!disposed) {
var i, len;
for (i = 0, len = data.value.length; i < len; i++) {
// The wrapper automatically checks for Dispose
// on the observer, so we don't need to check it here.
obs.onNext(data.value[i]);
}
if (data.value.length < pageSize) {
obs.onCompleted();
} else {
index += pageSize;
that.readRange(index, pageSize).then(successCallback, errorCallback);
}
}
};
that.readRange(index, pageSize).then(successCallback, errorCallback);
return { Dispose: function () {
obs.dispose(); // otherwise the check isStopped obs.onNext(data.value[i]);
disposed = true;
} };
});
};
/** Creates a function that handles a callback by setting the cache into failure mode.
* @method DataCache~cacheFailureCallback
* @param {String} message - Message text.
* @returns {Function} Function to use as error callback.
* This function will specifically handle problems with critical store resources
* during cache initialization.
*/
var cacheFailureCallback = function (message) {
return function (error) {
cacheFailure = { message: message, error: error };
// Destroy any pending clear or read operations.
// At this point there should be no prefetch operations.
// Count operations will go through but are benign because they
// won't interact with the store.
djsassert(prefetchOperations.length === 0, "prefetchOperations.length === 0");
var i, len;
for (i = 0, len = readOperations.length; i < len; i++) {
readOperations[i].fireRejected(cacheFailure);
}
for (i = 0, len = clearOperations.length; i < len; i++) {
clearOperations[i].fireRejected(cacheFailure);
}
// Null out the operation arrays.
readOperations = clearOperations = null;
};
};
/** Updates the cache's state and signals all pending operations of the change.
* @method DataCache~changeState
* @param {Object} newState - New cache state.
* This method is a no-op if the cache's current state and the new state are the same.</remarks>
*/
var changeState = function (newState) {
if (newState !== state) {
state = newState;
var operations = clearOperations.concat(readOperations, prefetchOperations);
var i, len;
for (i = 0, len = operations.length; i < len; i++) {
operations[i].run(state);
}
}
};
/** Removes all the data stored in the cache.
* @method DataCache~clearStore
* @returns {DjsDeferred} A promise with no value.
*/
var clearStore = function () {
djsassert(state === CACHE_STATE_DESTROY || state === CACHE_STATE_INIT, "DataCache.clearStore() - cache is not on the destroy or initialize state, current sate = " + state);
var deferred = new DjsDeferred();
store.clear(function () {
// Reset the cache settings.
actualCacheSize = 0;
allDataLocal = false;
collectionCount = 0;
highestSavedPage = 0;
highestSavedPageSize = 0;
overflowed = cacheSize === 0;
// version is not reset, in case there is other state in eg V1.1 that is still around.
// Reset the cache stats.
stats = { counts: 0, netReads: 0, prefetches: 0, cacheReads: 0 };
that.stats = stats;
store.close();
deferred.resolve();
}, function (err) {
deferred.reject(err);
});
return deferred;
};
/** Removes an operation from the caches queues and changes the cache state to idle.
* @method DataCache~dequeueOperation
* @param {DataCacheOperation} operation - Operation to dequeue.
* This method is used as a handler for the operation's oncomplete event.</remarks>
*/
var dequeueOperation = function (operation) {
var removed = removeFromArray(clearOperations, operation);
if (!removed) {
removed = removeFromArray(readOperations, operation);
if (!removed) {
removeFromArray(prefetchOperations, operation);
}
}
pendingOperations--;
changeState(CACHE_STATE_IDLE);
};
/** Requests data from the cache source.
* @method DataCache~fetchPage
* @param {Number} start - Zero-based index of items to request.
* @returns {DjsDeferred} A promise for a page object with (i)ndex, (c)ount, (d)ata.
*/
var fetchPage = function (start) {
djsassert(state !== CACHE_STATE_DESTROY, "DataCache.fetchPage() - cache is on the destroy state");
djsassert(state !== CACHE_STATE_IDLE, "DataCache.fetchPage() - cache is on the idle state");
var deferred = new DjsDeferred();
var canceled = false;
var request = source.read(start, pageSize, function (data) {
var length = getJsonValueArraryLength(data);
var page = { i: start, c: length, d: data };
deferred.resolve(page);
}, function (err) {
deferred.reject(err);
});
return extend(deferred, {
cancel: function () {
if (request) {
request.abort();
canceled = true;
request = null;
}
}
});
};
/** Filters the cache data based a predicate.
* @method DataCache~filter
* @param {Number} index - The index of the item to start filtering from.
* @param {Number} count - Maximum number of items to include in the result.
* @param {Function} predicate - Callback function returning a boolean that determines whether an item should be included in the result or not.
* @param {Boolean} backwards - True if the filtering should move backward from the specified index, falsey otherwise.
* Specifying a negative count value will yield all the items in the cache that satisfy the predicate.
* @returns {DjsDeferred} A promise for an array of results.
*/
var filter = function (index, count, predicate, backwards) {
index = parseInt10(index);
count = parseInt10(count);
if (isNaN(index)) {
throw { message: "'index' must be a valid number.", index: index };
}
if (isNaN(count)) {
throw { message: "'count' must be a valid number.", count: count };
}
if (cacheFailure) {
throw cacheFailure;
}
index = Math.max(index, 0);
var deferred = createDeferred();
var returnData = {};
returnData.value = [];
var canceled = false;
var pendingReadRange = null;
var readMore = function (readIndex, readCount) {
if (!canceled) {
if (count > 0 && returnData.value.length >= count) {
deferred.resolve(returnData);
} else {
pendingReadRange = that.readRange(readIndex, readCount).then(function (data) {
if (data["@odata.context"] && !returnData["@odata.context"]) {
returnData["@odata.context"] = data["@odata.context"];
}
for (var i = 0, length = data.value.length; i < length && (count < 0 || returnData.value.length < count); i++) {
var dataIndex = backwards ? length - i - 1 : i;
var item = data.value[dataIndex];
if (predicate(item)) {
var element = {
index: readIndex + dataIndex,
item: item
};
backwards ? returnData.value.unshift(element) : returnData.value.push(element);
}
}
// Have we reached the end of the collection?
if ((!backwards && data.value.length < readCount) || (backwards && readIndex <= 0)) {
deferred.resolve(returnData);
} else {
var nextIndex = backwards ? Math.max(readIndex - pageSize, 0) : readIndex + readCount;
readMore(nextIndex, pageSize);
}
}, function (err) {
deferred.reject(err);
});
}
}
};
// Initially, we read from the given starting index to the next/previous page boundary
var initialPage = snapToPageBoundaries(index, index, pageSize);
var initialIndex = backwards ? initialPage.i : index;
var initialCount = backwards ? index - initialPage.i + 1 : initialPage.i + initialPage.c - index;
readMore(initialIndex, initialCount);
return extend(deferred.promise(), {
/** Aborts the filter operation (used within promise callback)
* @method DataCache#cancelFilter
*/
cancel: function () {
if (pendingReadRange) {
pendingReadRange.cancel();
}
canceled = true;
}
});
};
/** Fires an onidle event if any functions are assigned.
* @method DataCache~fireOnIdle
*/
var fireOnIdle = function () {
if (that.onidle && pendingOperations === 0) {
that.onidle();
}
};
/** Creates and starts a new prefetch operation.
* @method DataCache~prefetch
* @param {Number} start - Zero-based index of the items to prefetch.
* This method is a no-op if any of the following conditions is true:
* 1.- prefetchSize is 0
* 2.- All data has been read and stored locally in the cache.
* 3.- There is already an all data prefetch operation queued.
* 4.- The cache has run out of available space (overflowed).
*/
var prefetch = function (start) {
if (allDataLocal || prefetchSize === 0 || overflowed) {
return;
}
djsassert(state === CACHE_STATE_READ, "DataCache.prefetch() - cache is not on the read state, current state: " + state);
if (prefetchOperations.length === 0 || (prefetchOperations[0] && prefetchOperations[0].c !== -1)) {
// Merging prefetch operations would be a nice optimization here.
var op = new DataCacheOperation(prefetchStateMachine, null, true, start, prefetchSize, null, prefetchSize);
queueAndStart(op, prefetchOperations);
}
};
/** Queues an operation and runs it.
* @param {DataCacheOperation} op - Operation to queue.
* @param {Array} queue - Array that will store the operation.
*/
var queueAndStart = function (op, queue) {
op.oncomplete = dequeueOperation;
queue.push(op);
pendingOperations++;
op.run(state);
};
/** Requests a page from the cache local store.
* @method DataCache~readPage
* @param {Number} key - Zero-based index of the reuqested page.
* @returns {DjsDeferred} A promise for a found flag and page object with (i)ndex, (c)ount, (d)ata, and (t)icks.
*/
var readPage = function (key) {
djsassert(state !== CACHE_STATE_DESTROY, "DataCache.readPage() - cache is on the destroy state");
var canceled = false;
var deferred = extend(new DjsDeferred(), {
/** Aborts the readPage operation. (used within promise callback)
* @method DataCache#cancelReadPage
*/
cancel: function () {
canceled = true;
}
});
var error = storeFailureCallback(deferred, "Read page from store failure");
store.contains(key, function (contained) {
if (canceled) {
return;
}
if (contained) {
store.read(key, function (_, data) {
if (!canceled) {
deferred.resolve(data !== undefined, data);
}
}, error);
return;
}
deferred.resolve(false);
}, error);
return deferred;
};
/** Saves a page to the cache local store.
* @method DataCache~savePage
* @param {Number} key - Zero-based index of the requested page.
* @param {Object} page - Object with (i)ndex, (c)ount, (d)ata, and (t)icks.
* @returns {DjsDeferred} A promise with no value.
*/
var savePage = function (key, page) {
djsassert(state !== CACHE_STATE_DESTROY, "DataCache.savePage() - cache is on the destroy state");
djsassert(state !== CACHE_STATE_IDLE, "DataCache.savePage() - cache is on the idle state");
var canceled = false;
var deferred = extend(new DjsDeferred(), {
/** Aborts the savePage operation. (used within promise callback)
* @method DataCache#cancelReadPage
*/
cancel: function () {
canceled = true;
}
});
var error = storeFailureCallback(deferred, "Save page to store failure");
var resolve = function () {
deferred.resolve(true);
};
if (page.c > 0) {
var pageBytes = estimateSize(page);
overflowed = cacheSize >= 0 && cacheSize < actualCacheSize + pageBytes;
if (!overflowed) {
store.addOrUpdate(key, page, function () {