-
Notifications
You must be signed in to change notification settings - Fork 299
/
backend.ts
1369 lines (1232 loc) · 39.4 KB
/
backend.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2016 Google Inc.
* Licensed 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.
*/
import { throttle } from "lodash-es";
import type {
ChunkSourceParametersConstructor,
LayerChunkProgressInfo,
} from "#src/chunk_manager/base.js";
import {
CHUNK_LAYER_STATISTICS_RPC_ID,
CHUNK_MANAGER_RPC_ID,
CHUNK_QUEUE_MANAGER_RPC_ID,
CHUNK_SOURCE_INVALIDATE_RPC_ID,
ChunkDownloadStatistics,
ChunkMemoryStatistics,
ChunkPriorityTier,
ChunkState,
getChunkDownloadStatisticIndex,
getChunkStateStatisticIndex,
numChunkMemoryStatistics,
numChunkStatistics,
REQUEST_CHUNK_STATISTICS_RPC_ID,
} from "#src/chunk_manager/base.js";
import type { SharedWatchableValue } from "#src/shared_watchable_value.js";
import type { TypedArray } from "#src/util/array.js";
import type { Borrowed, Disposable } from "#src/util/disposable.js";
import { RefCounted } from "#src/util/disposable.js";
import LinkedList0 from "#src/util/linked_list.0.js";
import LinkedList1 from "#src/util/linked_list.1.js";
import type { LinkedListOperations } from "#src/util/linked_list.js";
import { StringMemoize } from "#src/util/memoize.js";
import PairingHeap0 from "#src/util/pairing_heap.0.js";
import PairingHeap1 from "#src/util/pairing_heap.1.js";
import type {
ComparisonFunction,
PairingHeapOperations,
} from "#src/util/pairing_heap.js";
import { NullarySignal } from "#src/util/signal.js";
import type { RPC } from "#src/worker_rpc.js";
import {
initializeSharedObjectCounterpart,
registerPromiseRPC,
registerRPC,
registerSharedObject,
registerSharedObjectOwner,
SharedObject,
SharedObjectCounterpart,
} from "#src/worker_rpc.js";
const DEBUG_CHUNK_UPDATES = false;
export interface ChunkStateListener {
(chunk: Chunk, oldState: ChunkState): void;
}
let nextMarkGeneration = 0;
export function getNextMarkGeneration() {
return ++nextMarkGeneration;
}
export class Chunk implements Disposable {
// Node properties used for eviction/promotion heaps and LRU linked lists.
child0: Chunk | null = null;
next0: Chunk | null = null;
prev0: Chunk | null = null;
child1: Chunk | null = null;
next1: Chunk | null = null;
prev1: Chunk | null = null;
source: ChunkSource | null = null;
key: string | null = null;
private state_ = ChunkState.NEW;
error: any = null;
// Used by layers for marking chunks for various purposes.
markGeneration = -1;
/**
* Specifies existing priority within priority tier. Only meaningful if priorityTier in
* CHUNK_ORDERED_PRIORITY_TIERS. Higher numbers mean higher priority.
*/
priority = 0;
/**
* Specifies updated priority within priority tier, not yet reflected in priority queue state.
* Only meaningful if newPriorityTier in CHUNK_ORDERED_PRIORITY_TIERS.
*/
newPriority = 0;
priorityTier = ChunkPriorityTier.RECENT;
/**
* Specifies updated priority tier, not yet reflected in priority queue state.
*/
newPriorityTier = ChunkPriorityTier.RECENT;
private systemMemoryBytes_ = 0;
private gpuMemoryBytes_ = 0;
private downloadSlots_ = 1;
isComputational = false;
/**
* Specifies lowest numeric state required by any request, if `prioritTier !==
* ChunkPriorityTier.RECENT`, then this must be one of `GPU_MEMORY`, `SYSTEM_MEMORY`, or
* `SYSTEM_MEMORY_WORKER`.
*/
requestedState = ChunkState.NEW;
newRequestedState = ChunkState.NEW;
/**
* Abort controller used to cancel the pending download. Set to undefined except when state !==
* DOWNLOADING. This should not be accessed by code outside this module.
*/
downloadAbortController: AbortController | undefined = undefined;
initialize(key: string) {
this.key = key;
this.priority = Number.NEGATIVE_INFINITY;
this.priorityTier = ChunkPriorityTier.RECENT;
this.newPriority = Number.NEGATIVE_INFINITY;
this.newPriorityTier = ChunkPriorityTier.RECENT;
this.error = null;
this.state = ChunkState.NEW;
this.requestedState = ChunkState.NEW;
this.newRequestedState = ChunkState.NEW;
}
/**
* Sets this.priority{Tier,} to this.newPriority{Tier,}, and resets this.newPriorityTier to
* ChunkPriorityTier.RECENT.
*
* This does not actually update any queues to reflect this change.
*/
updatePriorityProperties() {
this.priorityTier = this.newPriorityTier;
this.priority = this.newPriority;
this.newPriorityTier = ChunkPriorityTier.RECENT;
this.newPriority = Number.NEGATIVE_INFINITY;
this.requestedState = this.newRequestedState;
this.newRequestedState = ChunkState.NEW;
}
dispose() {
this.source = null;
this.error = null;
}
get chunkManager() {
return (<ChunkSource>this.source).chunkManager;
}
get queueManager() {
return (<ChunkSource>this.source).chunkManager.queueManager;
}
downloadFailed(error: any) {
this.error = error;
this.queueManager.updateChunkState(this, ChunkState.FAILED);
}
downloadSucceeded() {
if (this.requestedState === ChunkState.SYSTEM_MEMORY) {
this.queueManager.moveChunkToFrontend(this);
this.queueManager.updateChunkState(this, ChunkState.SYSTEM_MEMORY);
} else {
this.queueManager.updateChunkState(this, ChunkState.SYSTEM_MEMORY_WORKER);
}
}
freeSystemMemory() {}
serialize(msg: any, _transfers: any[]) {
msg.id = this.key;
msg.source = (<ChunkSource>this.source).rpcId;
msg.new = true;
}
toString() {
return this.key;
}
set state(newState: ChunkState) {
if (newState === this.state_) {
return;
}
const oldState = this.state_;
this.state_ = newState;
this.source!.chunkStateChanged(this, oldState);
}
get state() {
return this.state_;
}
set systemMemoryBytes(bytes: number) {
updateChunkStatistics(this, -1);
this.chunkManager.queueManager.adjustCapacitiesForChunk(this, false);
this.systemMemoryBytes_ = bytes;
this.chunkManager.queueManager.adjustCapacitiesForChunk(this, true);
updateChunkStatistics(this, 1);
this.chunkManager.queueManager.scheduleUpdate();
}
get systemMemoryBytes() {
return this.systemMemoryBytes_;
}
set gpuMemoryBytes(bytes: number) {
updateChunkStatistics(this, -1);
this.chunkManager.queueManager.adjustCapacitiesForChunk(this, false);
this.gpuMemoryBytes_ = bytes;
this.chunkManager.queueManager.adjustCapacitiesForChunk(this, true);
updateChunkStatistics(this, 1);
this.chunkManager.queueManager.scheduleUpdate();
}
get gpuMemoryBytes() {
return this.gpuMemoryBytes_;
}
get downloadSlots() {
return this.downloadSlots_;
}
set downloadSlots(count: number) {
if (count === this.downloadSlots_) return;
updateChunkStatistics(this, -1);
this.chunkManager.queueManager.adjustCapacitiesForChunk(this, false);
this.downloadSlots_ = count;
this.chunkManager.queueManager.adjustCapacitiesForChunk(this, true);
updateChunkStatistics(this, 1);
this.chunkManager.queueManager.scheduleUpdate();
}
registerListener(listener: ChunkStateListener) {
if (!this.source) {
return false;
}
return this.source.registerChunkListener(this.key!, listener);
}
unregisterListener(listener: ChunkStateListener) {
if (!this.source) {
return false;
}
return this.source.unregisterChunkListener(this.key!, listener);
}
static priorityLess(a: Chunk, b: Chunk) {
return a.priority < b.priority;
}
static priorityGreater(a: Chunk, b: Chunk) {
return a.priority > b.priority;
}
}
export interface ChunkConstructor<T extends Chunk> {
new (): T;
}
const numSourceQueueLevels = 2;
/**
* Base class inherited by both ChunkSource, for implementing the backend part of chunk sources that
* also have a frontend-part, as well as other chunk sources, such as the GenericFileSource, that
* has only a backend part.
*/
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export class ChunkSourceBase extends SharedObject {
private listeners_ = new Map<string, ChunkStateListener[]>();
chunks: Map<string, Chunk> = new Map<string, Chunk>();
freeChunks: Chunk[] = new Array<Chunk>();
statistics = new Float64Array(numChunkStatistics);
/**
* sourceQueueLevel must be greater than the sourceQueueLevel of any ChunkSource whose download
* method depends on chunks from this source. A normal ChunkSource with no other dependencies
* should have a level of 0.
*/
sourceQueueLevel = 0;
constructor(public chunkManager: Borrowed<ChunkManager>) {
super();
chunkManager.queueManager.sources.add(this);
}
disposed() {
this.chunkManager.queueManager.sources.delete(this);
super.disposed();
}
getNewChunk_<T extends Chunk>(chunkType: ChunkConstructor<T>): T {
const freeChunks = this.freeChunks;
const freeChunksLength = freeChunks.length;
if (freeChunksLength > 0) {
const chunk = <T>freeChunks[freeChunksLength - 1];
freeChunks.length = freeChunksLength - 1;
chunk.source = this;
return chunk;
}
const chunk = new chunkType();
chunk.source = this;
return chunk;
}
/**
* Adds the specified chunk to the chunk cache.
*
* If the chunk cache was previously empty, also call this.addRef() to increment the reference
* count.
*/
addChunk(chunk: Chunk) {
const { chunks } = this;
if (chunks.size === 0) {
this.addRef();
}
chunks.set(chunk.key!, chunk);
updateChunkStatistics(chunk, 1);
}
/**
* Remove the specified chunk from the chunk cache.
*
* If the chunk cache becomes empty, also call this.dispose() to decrement the reference count.
*/
removeChunk(chunk: Chunk) {
const { chunks, freeChunks } = this;
chunks.delete(chunk.key!);
chunk.dispose();
freeChunks[freeChunks.length] = chunk;
if (chunks.size === 0) {
this.dispose();
}
}
registerChunkListener(key: string, listener: ChunkStateListener) {
if (!this.listeners_.has(key)) {
this.listeners_.set(key, [listener]);
} else {
this.listeners_.get(key)!.push(listener);
}
return true;
}
unregisterChunkListener(key: string, listener: ChunkStateListener) {
if (!this.listeners_.has(key)) {
return false;
}
const keyListeners = this.listeners_.get(key)!;
const idx = keyListeners.indexOf(listener);
if (idx < 0) {
return false;
}
keyListeners.splice(idx, 1);
if (keyListeners.length === 0) {
this.listeners_.delete(key);
}
return true;
}
chunkStateChanged(chunk: Chunk, oldState: ChunkState) {
const { key } = chunk;
if (key === null) return;
const listeners = this.listeners_.get(key);
if (listeners === undefined) return;
for (const listener of listeners.slice()) {
listener(chunk, oldState);
}
}
}
function updateChunkStatistics(chunk: Chunk, sign: number) {
const { statistics } = chunk.source!;
const { systemMemoryBytes, gpuMemoryBytes } = chunk;
const index = getChunkStateStatisticIndex(chunk.state, chunk.priorityTier);
statistics[
index * numChunkMemoryStatistics + ChunkMemoryStatistics.numChunks
] += sign;
statistics[
index * numChunkMemoryStatistics + ChunkMemoryStatistics.systemMemoryBytes
] += sign * systemMemoryBytes;
statistics[
index * numChunkMemoryStatistics + ChunkMemoryStatistics.gpuMemoryBytes
] += sign * gpuMemoryBytes;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export interface ChunkSourceBase {
/**
* Begin downloading the specified the chunk. The returned promise should resolve when the
* downloaded data has been successfully decoded and stored in the chunk, or rejected if the
* download or decoding fails.
*
* Note: This method must be defined by subclasses.
*
* @param chunk Chunk to download.
* @param abortSignal Used to abort download.
*
* TODO(jbms): Move this back to the class definition above and declare this abstract once mixins
* are compatible with abstract classes.
*/
download(chunk: Chunk, abortSignal: AbortSignal): Promise<void>;
}
export class ChunkSource extends ChunkSourceBase {
constructor(rpc: RPC, options: any) {
// No need to add a reference, since the owner counterpart will hold a reference to the owner
// counterpart of chunkManager.
const chunkManager = <ChunkManager>rpc.get(options.chunkManager);
super(chunkManager);
initializeSharedObjectCounterpart(this, rpc, options);
}
}
function startChunkDownload(chunk: Chunk) {
const downloadAbortController = (chunk.downloadAbortController =
new AbortController());
const startTime = Date.now();
chunk.source!.download(chunk, downloadAbortController.signal).then(
() => {
if (chunk.downloadAbortController === downloadAbortController) {
chunk.downloadAbortController = undefined;
const endTime = Date.now();
const { statistics } = chunk.source!;
statistics[
getChunkDownloadStatisticIndex(ChunkDownloadStatistics.totalTime)
] += endTime - startTime;
++statistics[
getChunkDownloadStatisticIndex(ChunkDownloadStatistics.totalChunks)
];
chunk.downloadSucceeded();
}
},
(error: any) => {
if (chunk.downloadAbortController === downloadAbortController) {
chunk.downloadAbortController = undefined;
chunk.downloadFailed(error);
console.log(`Error retrieving chunk ${chunk}: ${error}`);
}
},
);
}
function cancelChunkDownload(chunk: Chunk) {
const controller = chunk.downloadAbortController!;
chunk.downloadAbortController = undefined;
controller.abort();
}
class ChunkPriorityQueue {
/**
* Heap roots for VISIBLE and PREFETCH priority tiers.
*/
private heapRoots: (Chunk | null)[] = [null, null];
/**
* Head node for RECENT linked list.
*/
private recentHead = new Chunk();
constructor(
private heapOperations: PairingHeapOperations<Chunk>,
private linkedListOperations: LinkedListOperations<Chunk>,
) {
linkedListOperations.initializeHead(this.recentHead);
}
add(chunk: Chunk) {
const priorityTier = chunk.priorityTier;
if (priorityTier === ChunkPriorityTier.RECENT) {
this.linkedListOperations.insertAfter(this.recentHead, chunk);
} else {
const { heapRoots } = this;
heapRoots[priorityTier] = this.heapOperations.meld(
heapRoots[priorityTier],
chunk,
);
}
}
*candidates(): Iterator<Chunk> {
if (this.heapOperations.compare === Chunk.priorityLess) {
// Start with least-recently used RECENT chunk.
const { linkedListOperations, recentHead } = this;
while (true) {
const chunk = linkedListOperations.back(recentHead);
if (chunk == null) {
break;
}
yield chunk;
}
const { heapRoots } = this;
for (
let tier = ChunkPriorityTier.LAST_ORDERED_TIER;
tier >= ChunkPriorityTier.FIRST_ORDERED_TIER;
--tier
) {
while (true) {
const root = heapRoots[tier];
if (root == null) {
break;
}
yield root;
}
}
} else {
const heapRoots = this.heapRoots;
for (
let tier = ChunkPriorityTier.FIRST_ORDERED_TIER;
tier <= ChunkPriorityTier.LAST_ORDERED_TIER;
++tier
) {
while (true) {
const root = heapRoots[tier];
if (root == null) {
break;
}
yield root;
}
}
const { linkedListOperations, recentHead } = this;
while (true) {
const chunk = linkedListOperations.front(recentHead);
if (chunk == null) {
break;
}
yield chunk;
}
}
}
/**
* Deletes a chunk from this priority queue.
* @param chunk The chunk to delete from the priority queue.
*/
delete(chunk: Chunk) {
const priorityTier = chunk.priorityTier;
if (priorityTier === ChunkPriorityTier.RECENT) {
this.linkedListOperations.pop(chunk);
} else {
const heapRoots = this.heapRoots;
heapRoots[priorityTier] = this.heapOperations.remove(
<Chunk>heapRoots[priorityTier],
chunk,
);
}
}
}
function makeChunkPriorityQueue0(compare: ComparisonFunction<Chunk>) {
return new ChunkPriorityQueue(new PairingHeap0(compare), LinkedList0);
}
function makeChunkPriorityQueue1(compare: ComparisonFunction<Chunk>) {
return new ChunkPriorityQueue(new PairingHeap1(compare), LinkedList1);
}
function tryToFreeCapacity(
size: number,
capacity: AvailableCapacity,
priorityTier: ChunkPriorityTier,
priority: number,
evictionCandidates: Iterator<Chunk>,
evict: (chunk: Chunk) => void,
) {
while (capacity.availableItems < 1 || capacity.availableSize < size) {
const evictionCandidate = evictionCandidates.next().value;
if (evictionCandidate === undefined) {
// No eviction candidates available, promotions are done.
return false;
}
const evictionTier = evictionCandidate.priorityTier;
if (
evictionTier < priorityTier ||
(evictionTier === priorityTier && evictionCandidate.priority >= priority)
) {
// Lowest priority eviction candidate has priority >= highest
// priority promotion candidate. No more promotions are
// possible.
return false;
}
evict(evictionCandidate);
}
return true;
}
class AvailableCapacity extends RefCounted {
currentSize = 0;
currentItems = 0;
capacityChanged = new NullarySignal();
constructor(
public itemLimit: Borrowed<SharedWatchableValue<number>>,
public sizeLimit: Borrowed<SharedWatchableValue<number>>,
) {
super();
this.registerDisposer(itemLimit.changed.add(this.capacityChanged.dispatch));
this.registerDisposer(sizeLimit.changed.add(this.capacityChanged.dispatch));
}
/**
* Adjust available capacity by the specified amounts.
*/
adjust(items: number, size: number) {
this.currentItems -= items;
this.currentSize -= size;
}
get availableSize() {
return this.sizeLimit.value - this.currentSize;
}
get availableItems() {
return this.itemLimit.value - this.currentItems;
}
toString() {
return (
`bytes=${this.currentSize}/${this.sizeLimit.value},` +
`items=${this.currentItems}/${this.itemLimit.value}`
);
}
}
@registerSharedObject(CHUNK_QUEUE_MANAGER_RPC_ID)
export class ChunkQueueManager extends SharedObjectCounterpart {
gpuMemoryCapacity: AvailableCapacity;
systemMemoryCapacity: AvailableCapacity;
/**
* Download capacity for each sourceQueueLevel.
*/
downloadCapacity: AvailableCapacity[];
computeCapacity: AvailableCapacity;
enablePrefetch: SharedWatchableValue<boolean>;
/**
* Set of chunk sources associated with this queue manager.
*/
sources = new Set<Borrowed<ChunkSource>>();
/**
* Contains all chunks in QUEUED state pending download, for each sourceQueueLevel.
*/
private queuedDownloadPromotionQueue = [
makeChunkPriorityQueue1(Chunk.priorityGreater),
makeChunkPriorityQueue1(Chunk.priorityGreater),
];
/**
* Contains all chunks in QUEUED state pending compute.
*/
private queuedComputePromotionQueue = makeChunkPriorityQueue1(
Chunk.priorityGreater,
);
/**
* Contains all chunks in DOWNLOADING state, for each sourceQueueLevel.
*/
private downloadEvictionQueue = [
makeChunkPriorityQueue1(Chunk.priorityLess),
makeChunkPriorityQueue1(Chunk.priorityLess),
];
/**
* Contains all chunks in COMPUTING state.
*/
private computeEvictionQueue = makeChunkPriorityQueue1(Chunk.priorityLess);
/**
* Contains all chunks that take up memory (DOWNLOADING, SYSTEM_MEMORY,
* GPU_MEMORY).
*/
private systemMemoryEvictionQueue = makeChunkPriorityQueue0(
Chunk.priorityLess,
);
/**
* Contains all chunks in SYSTEM_MEMORY state not in RECENT priority tier.
*/
private gpuMemoryPromotionQueue = makeChunkPriorityQueue1(
Chunk.priorityGreater,
);
/**
* Contains all chunks in GPU_MEMORY state.
*/
private gpuMemoryEvictionQueue = makeChunkPriorityQueue1(Chunk.priorityLess);
// Should be `number|null`, but marked `any` to work around @types/node being pulled in.
private updatePending: any = null;
gpuMemoryChanged = new NullarySignal();
private numQueued = 0;
private numFailed = 0;
private gpuMemoryGeneration = 0;
constructor(rpc: RPC, options: any) {
super(rpc, options);
const getCapacity = (capacity: any) => {
const result = this.registerDisposer(
new AvailableCapacity(
rpc.get(capacity.itemLimit),
rpc.get(capacity.sizeLimit),
),
);
result.capacityChanged.add(() => this.scheduleUpdate());
return result;
};
this.gpuMemoryCapacity = getCapacity(options.gpuMemoryCapacity);
this.systemMemoryCapacity = getCapacity(options.systemMemoryCapacity);
this.enablePrefetch = rpc.get(options.enablePrefetch);
this.downloadCapacity = [
getCapacity(options.downloadCapacity),
getCapacity(options.downloadCapacity),
];
this.computeCapacity = getCapacity(options.computeCapacity);
}
scheduleUpdate() {
if (this.updatePending === null) {
this.updatePending = setTimeout(this.process.bind(this), 0);
}
}
*chunkQueuesForChunk(chunk: Chunk) {
switch (chunk.state) {
case ChunkState.QUEUED:
if (chunk.isComputational) {
yield this.queuedComputePromotionQueue;
} else {
yield this.queuedDownloadPromotionQueue[
chunk.source!.sourceQueueLevel
];
}
break;
case ChunkState.DOWNLOADING:
if (chunk.isComputational) {
yield this.computeEvictionQueue;
} else {
yield this.downloadEvictionQueue[chunk.source!.sourceQueueLevel];
yield this.systemMemoryEvictionQueue;
}
break;
case ChunkState.SYSTEM_MEMORY_WORKER:
case ChunkState.SYSTEM_MEMORY:
yield this.systemMemoryEvictionQueue;
if (chunk.requestedState === ChunkState.GPU_MEMORY) {
yield this.gpuMemoryPromotionQueue;
}
break;
case ChunkState.GPU_MEMORY:
yield this.systemMemoryEvictionQueue;
yield this.gpuMemoryEvictionQueue;
break;
}
}
adjustCapacitiesForChunk(chunk: Chunk, add: boolean) {
const factor = add ? -1 : 1;
switch (chunk.state) {
case ChunkState.FAILED:
this.numFailed -= factor;
break;
case ChunkState.QUEUED:
this.numQueued -= factor;
break;
case ChunkState.DOWNLOADING:
(chunk.isComputational
? this.computeCapacity
: this.downloadCapacity[chunk.source!.sourceQueueLevel]
).adjust(
factor * chunk.downloadSlots,
factor * chunk.systemMemoryBytes,
);
this.systemMemoryCapacity.adjust(
factor,
factor * chunk.systemMemoryBytes,
);
break;
case ChunkState.SYSTEM_MEMORY:
case ChunkState.SYSTEM_MEMORY_WORKER:
this.systemMemoryCapacity.adjust(
factor,
factor * chunk.systemMemoryBytes,
);
break;
case ChunkState.GPU_MEMORY:
this.systemMemoryCapacity.adjust(
factor,
factor * chunk.systemMemoryBytes,
);
this.gpuMemoryCapacity.adjust(factor, factor * chunk.gpuMemoryBytes);
break;
}
}
private removeChunkFromQueues_(chunk: Chunk) {
updateChunkStatistics(chunk, -1);
for (const queue of this.chunkQueuesForChunk(chunk)) {
queue.delete(chunk);
}
}
// var freedChunks = 0;
private addChunkToQueues_(chunk: Chunk) {
if (
chunk.state === ChunkState.QUEUED &&
chunk.priorityTier === ChunkPriorityTier.RECENT
) {
// Delete this chunk.
const { source } = chunk;
source!.removeChunk(chunk);
this.adjustCapacitiesForChunk(chunk, false);
return false;
}
updateChunkStatistics(chunk, 1);
for (const queue of this.chunkQueuesForChunk(chunk)) {
queue.add(chunk);
}
return true;
}
performChunkPriorityUpdate(chunk: Chunk) {
if (
chunk.priorityTier === chunk.newPriorityTier &&
chunk.priority === chunk.newPriority
) {
chunk.newPriorityTier = ChunkPriorityTier.RECENT;
chunk.newPriority = Number.NEGATIVE_INFINITY;
return;
}
if (DEBUG_CHUNK_UPDATES) {
console.log(
`${chunk}: changed priority ${chunk.priorityTier}:` +
`${chunk.priority} -> ${chunk.newPriorityTier}:${chunk.newPriority}`,
);
}
this.removeChunkFromQueues_(chunk);
chunk.updatePriorityProperties();
if (chunk.state === ChunkState.NEW) {
chunk.state = ChunkState.QUEUED;
this.adjustCapacitiesForChunk(chunk, true);
}
this.addChunkToQueues_(chunk);
}
updateChunkState(chunk: Chunk, newState: ChunkState) {
if (newState === chunk.state) {
return;
}
if (DEBUG_CHUNK_UPDATES) {
console.log(
`${chunk}: changed state ${ChunkState[chunk.state]} -> ${
ChunkState[newState]
}`,
);
}
this.adjustCapacitiesForChunk(chunk, false);
this.removeChunkFromQueues_(chunk);
chunk.state = newState;
this.adjustCapacitiesForChunk(chunk, true);
this.addChunkToQueues_(chunk);
this.scheduleUpdate();
}
private processGPUPromotions_() {
const queueManager = this;
function evictFromGPUMemory(chunk: Chunk) {
queueManager.freeChunkGPUMemory(chunk);
chunk.source!.chunkManager.queueManager.updateChunkState(
chunk,
ChunkState.SYSTEM_MEMORY,
);
}
const promotionCandidates = this.gpuMemoryPromotionQueue.candidates();
const evictionCandidates = this.gpuMemoryEvictionQueue.candidates();
const capacity = this.gpuMemoryCapacity;
while (true) {
const promotionCandidate = promotionCandidates.next().value;
if (promotionCandidate === undefined) {
break;
}
const priorityTier = promotionCandidate.priorityTier;
const priority = promotionCandidate.priority;
if (
!tryToFreeCapacity(
promotionCandidate.gpuMemoryBytes,
capacity,
priorityTier,
priority,
evictionCandidates,
evictFromGPUMemory,
)
) {
break;
}
this.copyChunkToGPU(promotionCandidate);
this.updateChunkState(promotionCandidate, ChunkState.GPU_MEMORY);
}
}
freeChunkGPUMemory(chunk: Chunk) {
++this.gpuMemoryGeneration;
this.rpc!.invoke("Chunk.update", {
id: chunk.key,
state: ChunkState.SYSTEM_MEMORY,
source: chunk.source!.rpcId,
});
}
freeChunkSystemMemory(chunk: Chunk) {
if (chunk.state === ChunkState.SYSTEM_MEMORY_WORKER) {
chunk.freeSystemMemory();
} else {
this.rpc!.invoke("Chunk.update", {
id: chunk.key,
state: ChunkState.EXPIRED,
source: chunk.source!.rpcId,
});
}
}
retrieveChunkData(chunk: Chunk) {
return this.rpc!.promiseInvoke<TypedArray>("Chunk.retrieve", {
key: chunk.key!,
source: chunk.source!.rpcId,
});
}
copyChunkToGPU(chunk: Chunk) {
++this.gpuMemoryGeneration;
const rpc = this.rpc!;
if (chunk.state === ChunkState.SYSTEM_MEMORY) {
rpc.invoke("Chunk.update", {
id: chunk.key,
source: chunk.source!.rpcId,
state: ChunkState.GPU_MEMORY,
});
} else {
const msg: any = {};
const transfers: any[] = [];
chunk.serialize(msg, transfers);
msg.state = ChunkState.GPU_MEMORY;
rpc.invoke("Chunk.update", msg, transfers);
}
}
moveChunkToFrontend(chunk: Chunk) {
const rpc = this.rpc!;
const msg: any = {};
const transfers: any[] = [];
chunk.serialize(msg, transfers);
msg.state = ChunkState.SYSTEM_MEMORY;
rpc.invoke("Chunk.update", msg, transfers);
}
private processQueuePromotions_() {
const evict = (chunk: Chunk) => {
switch (chunk.state) {
case ChunkState.DOWNLOADING:
cancelChunkDownload(chunk);
break;
case ChunkState.GPU_MEMORY:
this.freeChunkGPUMemory(chunk);
// fallthrough
case ChunkState.SYSTEM_MEMORY_WORKER:
case ChunkState.SYSTEM_MEMORY:
this.freeChunkSystemMemory(chunk);
break;
}
// Note: After calling this, chunk may no longer be valid.
this.updateChunkState(chunk, ChunkState.QUEUED);
};