-
Notifications
You must be signed in to change notification settings - Fork 21
/
gwt.js
2072 lines (1962 loc) · 75 KB
/
gwt.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
function convertToByteArray(target) {
var source = peergos.shared.user.JavaScriptPoster.emptyArray();
// This relies on internal implementation details of GWT's byte[] emulation
target.___clazz = source.___clazz;
target.castableTypeMap = source.castableTypeMap;
target.typeMarker = source.typeMarker;
target.__elementTypeCategory$ = source.__elementTypeCategory$;
target.__elementTypeId$ = source.__elementTypeId$;
var len = target.length;
target.__proto__ = source.__proto__;
target.length = len;
return target;
}
function propsToFragment(props) {
// Manually percent encode commas to work around some broken clients, like signal
return encodeURI(JSON.stringify(props)).split(",").join("%2c");
}
function fragmentToProps(fragment) {
var decoded = decodeURIComponent(fragment);
return JSON.parse(decoded);
}
function getProm(url) {
return getWithHeadersProm(url, []);
}
function getWithHeadersProm(url, headers) {
var future = peergos.shared.util.Futures.incomplete();
var req = new XMLHttpRequest();
req.open('GET', url);
req.responseType = 'arraybuffer';
var index = 0;
while (index < headers.length){
var name = headers[index++];
var value = headers[index++];
if (name != "Host" && name != "Content-Length")
req.setRequestHeader(name, value);
}
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
future.complete(convertToByteArray(new Int8Array(req.response)));
} else if (req.status == 404) {
future.completeExceptionally(new peergos.shared.storage.HttpFileNotFoundException());
} else if (req.status == 429 || req.status == 503) {
future.completeExceptionally(new peergos.shared.storage.RateLimitException());
} else {
future.completeExceptionally(java.lang.Throwable.of(Error(req.getResponseHeader("Trailer"))));
}
};
req.onerror = function(e) {
future.completeExceptionally(new peergos.shared.storage.RateLimitException());
};
req.send();
return future;
}
function postProm(url, data, timeout) {
var future = peergos.shared.util.Futures.incomplete();
new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('POST', url);
if (timeout >= 0)
req.timeout = timeout;
req.responseType = 'arraybuffer';
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
resolve(new Int8Array(req.response));
}
else {
try {
let trailer = req.getResponseHeader("Trailer");
if (trailer == null) {
reject('Unexpected error from server');
} else {
if (trailer.startsWith('Storage+quota+reached')) {
future.completeExceptionally(new peergos.shared.storage.StorageQuotaExceededException(trailer));
} else if (trailer.startsWith('CAS+exception') || trailer.startsWith('Mutable+pointer+update+failed')) {
future.completeExceptionally(new peergos.shared.storage.CasException(trailer));
} else {
reject(trailer);
}
}
} catch (e) {
reject(e);
}
}
};
req.onerror = function(e) {
future.completeExceptionally(new java.net.ConnectException("Unable to connect"));
};
req.ontimeout = function() {
reject(Error("Network timeout"));
};
req.send(data);
}).then(function(result, err) {
if (err != null)
future.completeExceptionally(java.lang.Throwable.of(err));
else
future.complete(convertToByteArray(result));
}, function(err) {
future.completeExceptionally(java.lang.Throwable.of(err));
});
return future;
}
function postMultipartProm(url, dataArrays, timeout) {
var future = peergos.shared.util.Futures.incomplete();
new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('POST', url);
if (timeout >= 0)
req.timeout = timeout;
req.responseType = 'arraybuffer';
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
resolve(new Int8Array(req.response));
}
else {
try {
let trailer = req.getResponseHeader("Trailer");
if (trailer == null) {
reject('Unexpected error from server');
} else {
if (trailer.startsWith('Storage+quota+reached')) {
future.completeExceptionally(new peergos.shared.storage.StorageQuotaExceededException(trailer));
} else if (trailer.startsWith('CAS+exception') || trailer.startsWith('Mutable+pointer+update+failed')) {
future.completeExceptionally(new peergos.shared.storage.CasException(trailer));
} else {
reject(trailer);
}
}
} catch (e) {
reject("Error");
}
}
};
req.onerror = function(e) {
future.completeExceptionally(new java.net.ConnectException("Unable to connect"));
};
req.ontimeout = function(e) {
future.completeExceptionally(new peergos.shared.storage.RateLimitException());
};
var form = new FormData();
for (var i=0; i < dataArrays.array.length; i++)
form.append(i, new Blob([dataArrays.array[i]]));
req.send(form);
}).then(function(result, err) {
if (err != null)
future.completeExceptionally(java.lang.Throwable.of(err));
else
future.complete(convertToByteArray(result));
}, function(err) {
future.completeExceptionally(java.lang.Throwable.of(err));
});
return future;
}
function putProm(url, data, headers) {
var future = peergos.shared.util.Futures.incomplete();
new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('PUT', url);
req.responseType = 'arraybuffer';
var index = 0;
while (index < headers.length){
var name = headers[index++];
var value = headers[index++];
if (name != "Host" && name != "Content-Length")
req.setRequestHeader(name, value);
}
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
resolve(new Int8Array(req.response));
} else if (req.status == 429 || req.status == 500 || req.status == 503) {
future.completeExceptionally(new peergos.shared.storage.RateLimitException());
} else {
reject("HTTP " + req.status);
}
};
req.onerror = function(e) {
future.completeExceptionally(new peergos.shared.storage.RateLimitException());
};
req.ontimeout = function(e) {
future.completeExceptionally(new peergos.shared.storage.RateLimitException());
};
req.send(data);
}).then(function(result, err) {
if (err != null)
future.completeExceptionally(java.lang.Throwable.of(err));
else
future.complete(convertToByteArray(result));
}, function(err) {
future.completeExceptionally(java.lang.Throwable.of(err));
});
return future;
}
var callback = {
NativeJSScheduler: function() {
this.callAfterDelay = function callbackFunc(func, delay) {
setTimeout(function(){
func.call();
}, delay);
}
}
};
var http = {
NativeJSHttp: function() {
this.get = getProm;
this.getWithHeaders = getWithHeadersProm;
this.post = postProm;
this.postMultipart = postMultipartProm;
this.put = putProm;
}
};
var online = {
NativeJsOnlineState: function() {
this.isOnline = function() {
return window.navigator.onLine;
};
}
};
var cache = {
NativeJSCache: function() {
this.cacheStore = null;
this.cacheStoreMetadata = null;
this.cacheDesiredSizeStore = null;
this.cacheMetadataArray = [];
this.cacheMetadataRefs = {};
this.maxSizeBytes = 0;
this.currentCacheSize = 0;
this.currentCacheBlockCount = 0;
this.MAX_CACHE_BLOCKS = 30000; // must be > 1000
this.enablePolicyEvictOnBlockCount = false;
this.evicting = false;
this.isCachingEnabled = false;
this.isOpfsCachingEnabled = false;
this.isIndexedDBCachingEnabled = false;
this.desiredCacheSize = 0;
this.init = function init(maxSizeMiB) {
let that = this;
bindCacheStore(that);
isOPFSAvailable().thenApply(function(isOpfsCachingEnabled) {
isIndexedDBAvailable().thenApply(function(isIndexedDBCachingEnabled) {
that.isIndexedDBCachingEnabled = isIndexedDBCachingEnabled;
that.isOpfsCachingEnabled = isIndexedDBCachingEnabled && isOpfsCachingEnabled;
that.isCachingEnabled = isOpfsCachingEnabled || isIndexedDBCachingEnabled;
if (that.isCachingEnabled) {
that.cacheStore = isOpfsCachingEnabled ? 'data' : createStoreIDBKV('data', 'keyval');
that.cacheStoreMetadata = isOpfsCachingEnabled ? null : createStoreIDBKV('metadata', 'keyval');
that.cacheDesiredSizeStore = createStoreIDBKV('size', 'keyval');
getDesiredCacheSize().thenApply(desiredCacheSize => {
getBrowserStorageQuota().then(browserStorageQuota => {
that.maxSizeBytes = calculateCacheSize(maxSizeMiB * 1024 * 1024, browserStorageQuota, desiredCacheSize);
that.desiredCacheSize = that.maxSizeBytes;
if (isOpfsCachingEnabled) {
removeIndexedDBIfExists().thenApply((done) => {
valuesOPFSKV(that.cacheStore).thenApply((values) => {
values.forEach((json, idx) => {
that.cacheMetadataArray.push(json);
that.cacheMetadataRefs['k'+json.key] = that.cacheMetadataArray[idx]; // 'k' prefix as key may start with a digit
that.currentCacheSize = that.currentCacheSize + json.l;
});
that.prepare(values);
});
});
} else {
valuesIDBKV(that.cacheStoreMetadata).then((values) => {
values.forEach((value, idx) => {
let json = JSON.parse(value);
that.cacheMetadataArray.push(json);
that.cacheMetadataRefs['k'+json.key] = that.cacheMetadataArray[idx]; // 'k' prefix as key may start with a digit
that.currentCacheSize = that.currentCacheSize + json.l;
});
that.prepare(values);
});
}
});
});
}
});
});
};
this.prepare = function(values) {
let that = this;
that.currentCacheBlockCount = values.length;
prepareLRU().thenApply(lruInitialised => {
setDesiredCacheSize(that.maxSizeBytes).thenApply(done => {
let currentMiB = (that.currentCacheSize /1024 /1024).toFixed(2);
let maxMiB = (that.maxSizeBytes /1024 /1024).toFixed(2);
getBrowserStorageUsage().then(browserStorageUsage => {
let actualMiB = (browserStorageUsage /1024 /1024).toFixed(2);
console.log('Block Cache. Actual usage:' + actualMiB + ' MiB');
console.log('Block Cache. Objects:' + that.currentCacheBlockCount + " Size:" + currentMiB + " MiB" + " Max:" + maxMiB + " MiB");
});
});
});
}
this.put = putIntoCacheProm;
this.get = getFromCacheProm;
this.hasBlock = hasBlockInCache;
this.clear = clearCache;
}
};
function prepareLRU() {
let future = peergos.shared.util.Futures.incomplete();
evictLRU(blockStoreCache, function() {future.complete(true)});
return future;
}
var rootDirectory = null;
function delManyOPFSKV(filesArray, directory) {
let future = peergos.shared.util.Futures.incomplete();
deleteFiles(filesArray, directory).then(() => {
future.complete(true);
})
return future;
}
async function deleteFiles(filesArray, directory) {
const promises = [];
for await (const name of filesArray) {
let prom = new Promise(function(resolve, reject) {
let work = function(filename, retryCount) {
getParentDirectoryHandle(filename, directory).then(parentDirHandle => {
parentDirHandle.removeEntry(filename).then(() => {
resolve(true);
}).catch(e => {
if (retryCount < 5) {
setTimeout(() => work(filename, retryCount + 1), 10);
} else {
console.log(e);
resolve(false);
}
});
});
};
work(name, 0);
});
promises.push(prom);
}
return Promise.all(promises);
}
function clearOPFSKV(directory) {
let future = peergos.shared.util.Futures.incomplete();
rootDirectory.removeEntry(directory, { recursive: true }).then(() => {
future.complete(true)
});
return future;
}
function getParentDirectoryHandle(filename, directory) {
let blockFolder = filename.substring(filename.length - 3, filename.length - 1);
return rootDirectory.getDirectoryHandle(directory, { create: true })
.then(dirHandle =>
dirHandle.getDirectoryHandle(blockFolder, { create: true }));
}
let pendingWrites = new Map(); // filename => value
let pendingReads = new Map(); // filename => [future] Note: possibility of multiple futures
opfsWorker = new Worker("/js/opfs.js");
opfsWorker.postMessage({action: 'init'});
opfsWorker.onmessage = function(event) { // reads
let message = event.data;
const pendingFutures = pendingReads.get(message.filename);
if (pendingFutures != null) {
pendingReads.delete(message.filename);
if (message.contents == null) {
pendingFutures.forEach(pendingFuture =>
pendingFuture.complete(peergos.client.JsUtil.emptyOptional())
);
} else {
pendingFutures.forEach(pendingFuture =>
pendingFuture.complete(peergos.client.JsUtil.optionalOf(convertToByteArray(message.contents)))
);
}
}
};
function setOPFSKV(filename, value, directory) {
if (!pendingWrites.has(filename)) {
pendingWrites.set(filename, peergos.client.JsUtil.optionalOf(convertToByteArray(value)));
opfsWorker.postMessage({action: 'set', filename: filename, value: value, directory: directory});
setTimeout(() => {
pendingWrites.delete(filename);
}, 5000);
}
}
function getOPFSKV(filename, context, future) {
let directory = context.cacheStore;
const pending = pendingWrites.get(filename);
if (pending != null) {
future.complete(pending);
} else {
if (pendingReads.has(filename)) {
pendingReads.get(filename).push(future);
} else {
pendingReads.set(filename, [future]);
opfsWorker.postMessage({action: 'get', filename: filename, directory: directory});
}
let that = this;
setTimeout(() => {
let entry = context.cacheMetadataRefs['k'+filename];
if (entry != null) {
let now = new Date();
entry.t = now.getTime();
}
});
}
}
function valuesOPFSKV(directory) {
let future = peergos.shared.util.Futures.incomplete();
rootDirectory.getDirectoryHandle(directory, { create: true }).then(dirHandle => {
getFilesMetadata(dirHandle).then(values => {
future.complete(values);
});
});
return future;
}
async function getFilesMetadata(directoryHandle) {
const filesMetadata = [];
for await (const stats of getFileStatsRecursively(directoryHandle)) {
filesMetadata.push(stats);
}
return filesMetadata;
}
async function* getFileStatsRecursively(entry) { //https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryHandle
if (entry.kind === "file") {
const file = await entry.getFile();
if (file !== null) {
let json = {key: file.name, l: file.size, t: file.lastModified};
yield json;
}
} else if (entry.kind === "directory") {
for await (const handle of entry.values()) {
yield* getFileStatsRecursively(handle);
}
}
}
/*
mobile browsers - not confirmed to work and difficult to debug.
*/
function isOPFSAvailable() {
let future = peergos.shared.util.Futures.incomplete();
try {
let isMobile = /Mobi|Android/i.test(navigator.userAgent); // https://stackoverflow.com/a/24600597
let isLinuxOnFirefox = navigator.userAgent.search('Linux')!==-1 && navigator.userAgent.search('X11')!==-1
&& navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
if (!isMobile && !isLinuxOnFirefox) {
navigator.storage.getDirectory().then(root => {
if (rootDirectory == null) {
rootDirectory = root;
}
console.log('OPFS available');
future.complete(true);
}).catch(e => {
console.log('OPFS not available:' + e);
future.complete(false);
});
} else {
console.log('OPFS support not currently available for your browser');
future.complete(false);
}
} catch (e) {
future.complete(false);
}
return future;
}
//Firefox private mode does not support IndexedDB. https://bugzilla.mozilla.org/show_bug.cgi?id=781982
function isIndexedDBAvailable() {
let future = peergos.shared.util.Futures.incomplete();
if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1
|| navigator.userAgent.toLowerCase().indexOf("iphone") > -1){
//console.log("Firefox")
try {
var db = indexedDB.open("IsPBMode");
db.onerror = function() {
future.complete(false);
};
db.onsuccess = function() {
console.log('IndexedDB available');
future.complete(true);
};
}
catch(err) {
future.complete(false);
}
} else {
console.log('IndexedDB available');
future.complete(true);
}
return future;
}
var blockStoreCache;
var pointerStoreCache;
var batStoreCache;
var accountStoreCache;
var pkiStoreCache;
var rootKeyCache;
let SAFARI_CACHE_SIZE = 1024 * 1024 * 700;
function bindCacheStore(storeCache) {
blockStoreCache = storeCache;
}
function isCachingAvailable() {
return blockStoreCache.isCachingEnabled;
}
function getCurrentCacheSizeMiB() {
return blockStoreCache.maxSizeBytes /1024 /1024;
}
function getCurrentDesiredCacheSize() {
return blockStoreCache.desiredCacheSize /1024/1024;
}
function getDesiredCacheSize() {
let future = peergos.shared.util.Futures.incomplete();
getIDBKV("desiredSize", blockStoreCache.cacheDesiredSizeStore).then((val) => {
if (val == null || val == -1) {
future.complete(-1);
} else if(val == 0 && isSafariTest()) {
future.complete(SAFARI_CACHE_SIZE);
} else {
future.complete(val);
}
});
return future;
}
function setDesiredCacheSize(desiredSize) {
let that = this;
let future = peergos.shared.util.Futures.incomplete();
if (!blockStoreCache.isCachingEnabled) {
future.complete(true);
} else {
setIDBKV("desiredSize", desiredSize, blockStoreCache.cacheDesiredSizeStore).then(() => {
future.complete(true);
}).catch(err => {
console.error("unable to update desired size!", err.message);
clearCacheFully(blockStoreCache, function() {
setIDBKV("desiredSize", desiredSize, blockStoreCache.cacheDesiredSizeStore).then(() => {
future.complete(true);
}).catch(err => {
future.complete(true);
});
});
});
}
return future;
}
function modifyCacheSize(newCacheSizeMiB) {
let newSizeBytes = newCacheSizeMiB * 1024 * 1024;
let future = peergos.shared.util.Futures.incomplete();
if (!blockStoreCache.isCachingEnabled) {
future.complete(true);
} else {
setDesiredCacheSize(newSizeBytes).thenApply(done => {
blockStoreCache.desiredCacheSize = newSizeBytes;
if (newSizeBytes == 0) {
clearCacheFully(blockStoreCache, function() {
clearPointerCacheFully(pointerStoreCache, function() {
blockStoreCache.maxSizeBytes = 0;
future.complete(true);
});
});
} else if (newSizeBytes < blockStoreCache.maxSizeBytes) { //less than current max
blockStoreCache.maxSizeBytes = newSizeBytes;
if (triggerEviction(blockStoreCache)) {
evictLRU(blockStoreCache, function() {future.complete(true)});
} else {
future.complete(true);
}
} else {
blockStoreCache.maxSizeBytes = newSizeBytes;
future.complete(true);
}
});
}
return future;
}
function getBrowserStorageUsage() {
if (navigator.storage && navigator.storage.estimate) {
return navigator.storage.estimate().then(quota => quota.usage);
} else {
let prom = new Promise(function(resolve, reject) { resolve(0)});
return prom;
}
}
function isSafariTest() {
let test =
/constructor/i.test(window.HTMLElement) ||
(function (p) {
return p.toString() === "[object SafariRemoteNotification]";
})(!window["safari"] || safari.pushNotification);
return test;
}
function getBrowserStorageQuota() {
if (navigator.storage && navigator.storage.estimate) {
return navigator.storage.estimate().then(quota => quota.quota);
} else {
let prom = new Promise(function(resolve, reject) { resolve(isSafariTest() ? SAFARI_CACHE_SIZE : 0)});
return prom;
}
}
function calculateCacheSize(maxSizeBytes, maxBrowserStorageBytes, desiredCacheSize) {
if (maxBrowserStorageBytes == 0) {
return 0;//no cache
} else if (maxSizeBytes <= 0) {
if (desiredCacheSize > -1 && desiredCacheSize < maxBrowserStorageBytes) {
return desiredCacheSize;
} else {
return maxBrowserStorageBytes;
}
} else {
let newLimit = maxSizeBytes > maxBrowserStorageBytes ? maxBrowserStorageBytes : maxSizeBytes;
if (desiredCacheSize > -1 && desiredCacheSize < maxBrowserStorageBytes && desiredCacheSize < newLimit) {
return desiredCacheSize;
} else {
return newLimit;
}
}
}
function triggerEviction(cache) {
if (!cache.isCachingEnabled) {
return false;
}
//above 90% of max
return (cache.currentCacheSize / cache.maxSizeBytes) * 100.0 > 90.0
|| (cache.enablePolicyEvictOnBlockCount && cache.currentCacheBlockCount > cache.MAX_CACHE_BLOCKS);
}
function reclaim(cache) {
//80% of max
return Math.floor(cache.maxSizeBytes / 100 * 80);
}
function evictLRU(cache, callback) {
if (!cache.isCachingEnabled) {
return;
}
if (cache.evicting) {
return;
}
cache.evicting = true;
var cacheSize = cache.currentCacheSize;
var cacheBlockCount = cache.currentCacheBlockCount;
let toDelete = [];
let newLimit = reclaim(cache);
let isOverBlockCountLimit = (cache.enablePolicyEvictOnBlockCount && cache.currentCacheBlockCount > cache.MAX_CACHE_BLOCKS);
let newBlockCountLimit = isOverBlockCountLimit ? cache.MAX_CACHE_BLOCKS - 1000 : cache.MAX_CACHE_BLOCKS;
if (!isOverBlockCountLimit && cacheSize <= newLimit) {
callback();
cache.evicting=false;
} else {
let sorted = cache.cacheMetadataArray.slice().sort((a, b) => a.t < b.t);
for(var i=0; i < sorted.length; i++) {
cacheSize = cacheSize - sorted[i].l;
toDelete.push(sorted[i].key);
cacheBlockCount = cacheBlockCount - 1;
if (cacheSize <= newLimit && cacheBlockCount <= newBlockCountLimit) {
cache.currentCacheSize = cacheSize;
cache.currentCacheBlockCount = cacheBlockCount;
break;
}
}
for (var i=0; i < toDelete.length; i++) {
sorted.splice(sorted.findIndex(v => v.key === toDelete[i]), 1);
try {
delete cache.cacheMetadataRefs['k' + toDelete[i]];
} catch(e) {}
}
cache.cacheMetadataArray = sorted;
if (cache.isOpfsCachingEnabled) {
delManyOPFSKV(toDelete, cache.cacheStore)
.thenApply(() => { callback();cache.evicting=false;});
} else {
delManyIDBKV(toDelete, cache.cacheStore)
.then(() => {
delManyIDBKV(toDelete, cache.cacheStoreMetadata)
.then(() => { callback();cache.evicting=false;})
.catch((err) => {
console.log("block cache metadata evict error:" + err);
clearCacheFully(cache, function(){callback();cache.evicting=false;});
});
}).catch((err) => {
console.log("block cache evict error:" + err);
clearCacheFully(cache, function(){callback();cache.evicting=false;});
});
}
}
}
function createBlockCacheMetadataRecord(key, blockLength) {
let now = new Date();
let length = blockLength + (key.length * 2);
let json = {key: key, l: length, t: now.getTime()};
var record = JSON.stringify(json);
json.l = length + record.length;//close enough
return json;
}
//public native CompletableFuture<Boolean> put(Cid hash, byte[] data);
function putIntoCacheProm(hash, data) {
let future = peergos.shared.util.Futures.incomplete();
if (this.maxSizeBytes == 0 || !this.isCachingEnabled) {
future.complete(true);
} else {
let that = this;
let key = hash.toString();
if (this.isOpfsCachingEnabled) {
if (data.byteLength == 0) {
console.log("OPFS: attempt to write 0 byte data. hash:" + key);
future.complete(true); //We don't want to force .exceptionally() handling and OPFS is just a cache, so .get() can return empty.
} else {
that.currentCacheSize = that.currentCacheSize + data.byteLength;
let now = new Date();
let metaData = {key: key, l: data.byteLength, t: now.getTime()};
let length = that.cacheMetadataArray.length;
that.cacheMetadataArray.push(metaData);
that.cacheMetadataRefs['k'+metaData.key] = that.cacheMetadataArray[length];
that.currentCacheBlockCount = that.currentCacheBlockCount + 1;
setOPFSKV(key, data, this.cacheStore);
setTimeout(() => {
if (triggerEviction(this)) {
evictLRU(this, function() {future.complete(true)});
}
});
future.complete(true);
}
} else {
setIDBKV(key, data, this.cacheStore).then(() => {
let metaData = createBlockCacheMetadataRecord(key, data.byteLength);
that.currentCacheSize = that.currentCacheSize + metaData.l;
setIDBKV(key, JSON.stringify(metaData), that.cacheStoreMetadata).then(() => {
let length = that.cacheMetadataArray.length;
that.cacheMetadataArray.push(metaData);
that.cacheMetadataRefs['k'+metaData.key] = that.cacheMetadataArray[length];
that.currentCacheBlockCount = that.currentCacheBlockCount + 1;
if (triggerEviction(this)) {
evictLRU(this, function() {future.complete(true)});
} else {
future.complete(true);
}
}).catch(err => {
delIDBKV(key, that.cacheStore).then(() => {
future.complete(true);
});
});
}).catch(err => {
evictLRU(blockStoreCache, function() {future.complete(true)});
});
}
}
return future;
}
function noop() {
}
//public native CompletableFuture<Optional<byte[]>> get(Cid hash);
function getFromCacheProm(hash) {
let future = peergos.shared.util.Futures.incomplete();
return getFromCachePromWithRetry(this, future, hash);
}
function getFromCachePromWithRetry(context, future, hash) {
let that = context;
if (!that.isCachingEnabled) {
future.complete(peergos.client.JsUtil.emptyOptional());
} else {
let key = hash.toString();
if (that.isOpfsCachingEnabled) {
getOPFSKV(key, that, future);
} else {
getIDBKV(key, that.cacheStore).then((val) => {
if (val == null) {
future.complete(peergos.client.JsUtil.emptyOptional());
} else {
setTimeout(() => {
let metaData = createBlockCacheMetadataRecord(key, val.length);
setIDBKV(key, JSON.stringify(metaData), that.cacheStoreMetadata).then(() => {
try {
let now = new Date();
that.cacheMetadataRefs['k'+key].t = now.getTime();
} catch(e) {}
}).catch(err => {
noop();
});
});
future.complete(peergos.client.JsUtil.optionalOf(convertToByteArray(val)));
}
});
}
}
return future;
}
//public native boolean hasBlock(Cid hash);
function hasBlockInCache(hash) {
return this.cacheEntrySizes.get(hash.toString()) != null;
}
//public native CompletableFuture<Boolean> clear();
function clearCache() {
let future = peergos.shared.util.Futures.incomplete();
if (cache.isCachingEnabled) {
clearCacheFully(this, function() {
future.complete(true);
});
} else {
future.complete(true);
}
return future;
}
function removeIndexedDBIfExists() {
let future = peergos.shared.util.Futures.incomplete();
let cacheStore = createStoreIDBKV('data', 'keyval');
let cacheStoreMetadata = createStoreIDBKV('metadata', 'keyval');
clearIDBKV(cacheStore).then((res1) => {
clearIDBKV(cacheStoreMetadata).then((res2) => {
future.complete(true);
});
});
return future;
}
function clearCacheFully(cache, func) {
if (cache.isCachingEnabled) {
cache.cacheMetadataArray = [];
cache.cacheMetadataRefs = {};
cache.currentCacheSize = 0;
if (cache.isOpfsCachingEnabled) {
clearOPFSKV(cache.cacheStore).thenApply((res2) => func());
} else {
clearIDBKV(cache.cacheStore).then((res1) => {
clearIDBKV(cache.cacheStoreMetadata).then((res2) => func());
});
}
} else {
func();
}
}
var pointerCache = {
NativeJSPointerCache: function() {
this.cachePointerStore = createStoreIDBKV('pointers', 'keyval');
this.cachePointerStoreMetadata = createStoreIDBKV('pmetadata', 'keyval');
this.cachePointerMetadataArray = [];
this.cachePointerRefs = {};
this.maxItems = 2000;
this.currentCacheSize = 0;
this.evicting = false;
this.isCachingEnabled = false;
this.init = function init(maxItems) {
let that = this;
bindPointerCacheStore(that);
isIndexedDBAvailable().thenApply(function(isCachingEnabled) {
that.isCachingEnabled = isCachingEnabled;
if (isCachingEnabled) {
valuesIDBKV(that.cachePointerStoreMetadata).then((values) => {
values.forEach((value, idx) => {
let json = JSON.parse(value);
that.cachePointerMetadataArray.push(json);
that.cachePointerRefs['k'+json.key] = that.cachePointerMetadataArray[idx];
});
that.currentCacheSize = values.length;
console.log('Pointer Cache. Objects:' + that.currentCacheSize);
});
}
});
};
this.put = putIntoPointerCacheProm;
this.get = getFromPointerCacheProm;
}
};
function bindPointerCacheStore(storeCache) {
pointerStoreCache = storeCache;
}
function triggerPointerCacheEviction(cache) {
//above 90% of max
return (cache.currentCacheSize / cache.maxItems) * 100.0 > 90.0;
}
function reclaimPointerCache(cache) {
//80% of max
return Math.floor(cache.maxItems / 100 * 80);
}
function evictPointerCacheLRU(cache, callback) {
if (cache.evicting || !cache.isCachingEnabled) {
return;
}
cache.evicting = true;
let sorted = cache.cachePointerMetadataArray.slice().sort((a, b) => a.t < b.t);
var cacheSize = cache.currentCacheSize;
let toDelete = [];
let newLimit = reclaimPointerCache(cache);
if (cacheSize <= newLimit) {
callback();
cache.evicting=false;
} else {
for(var i=0; i < sorted.length; i++) {
cacheSize--;
toDelete.push(sorted[i].key);
if (cacheSize <= newLimit) {
cache.currentCacheSize = cacheSize;
break;
}
}
for (var i=0; i < toDelete.length; i++) {
sorted.splice(sorted.findIndex(v => v.key === toDelete[i]), 1);
try {
delete cache.cachePointerRefs['k' + toDelete[i]];
} catch(e) {}
}
cache.cachePointerMetadataArray = sorted;
delManyIDBKV(toDelete, cache.cachePointerStore)
.then(() => {
delManyIDBKV(toDelete, cache.cachePointerStoreMetadata)
.then(() => { callback();cache.evicting=false;})
.catch((err) => {
console.log("pointer cache metadata evict error:" + err);
clearPointerCacheFully(cache, function(){callback();cache.evicting=false;});
});
}).catch((err) => {
console.log("pointer cache evict error:" + err);
clearPointerCacheFully(cache, function(){callback();cache.evicting=false;});
});
}
}
// public native CompletableFuture<Boolean> put(PublicKeyHash owner, PublicKeyHash writer, byte[] writerSignedBtreeRootHash);
function putIntoPointerCacheProm(owner, writer, writerSignedBtreeRootHash) {
let future = peergos.shared.util.Futures.incomplete();
if (!this.isCachingEnabled) {
future.complete(true);
} else {
let that = this;
let key = owner.toString() + "-" + writer.toString();
setIDBKV(key, writerSignedBtreeRootHash, this.cachePointerStore).then(() => {
let now = new Date();
let json = {key: key, t: now.getTime()};
let value = JSON.stringify(json);
that.currentCacheSize++;
setIDBKV(key, value, that.cachePointerStoreMetadata).then(() => {
let length = that.cachePointerMetadataArray.length;
that.cachePointerMetadataArray.push(json);
that.cachePointerRefs['k'+json.key] = that.cachePointerMetadataArray[length];
if (triggerPointerCacheEviction(this)) {
evictPointerCacheLRU(this, function() {future.complete(true)});
} else {
future.complete(true);
}
}).catch(err => {
delIDBKV(key, that.cachePointerStore).then(() => {
future.complete(true);
});
});
}).catch(err => {
future.complete(true);
});
}
return future;
}
// public native CompletableFuture<Optional<byte[]>> get(PublicKeyHash owner, PublicKeyHash writer);
function getFromPointerCacheProm(owner, writer) {
let that = this;
let future = peergos.shared.util.Futures.incomplete();
if (!this.isCachingEnabled) {
future.complete(peergos.client.JsUtil.emptyOptional());
} else {
let key = owner.toString() + "-" + writer.toString();
getIDBKV(key, this.cachePointerStore).then((val) => {
if (val == null) {
future.complete(peergos.client.JsUtil.emptyOptional());
} else {
setTimeout(() => {
let now = new Date();
let json = {key: key, t: now.getTime()};
setIDBKV(key, JSON.stringify(json), that.cachePointerStoreMetadata).then(() => {
try {
let now = new Date();
that.cachePointerRefs['k'+key].t = now.getTime();
} catch(e) {}