-
Notifications
You must be signed in to change notification settings - Fork 237
/
Copy pathkernelKeeper.js
1636 lines (1466 loc) · 51.9 KB
/
kernelKeeper.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
/* eslint-disable @typescript-eslint/prefer-ts-expect-error -- https://github.com/Agoric/agoric-sdk/issues/4620 */
import { Nat, isNat } from '@endo/nat';
import { assert, Fail } from '@agoric/assert';
import { initializeVatState, makeVatKeeper } from './vatKeeper.js';
import { initializeDeviceState, makeDeviceKeeper } from './deviceKeeper.js';
import { parseReachableAndVatSlot } from './reachable.js';
import { insistStorageAPI } from '../../lib/storageAPI.js';
import {
insistKernelType,
makeKernelSlot,
parseKernelSlot,
} from '../parseKernelSlots.js';
import { insistCapData } from '../../lib/capdata.js';
import { insistMessage } from '../../lib/message.js';
import {
insistDeviceID,
insistVatID,
makeDeviceID,
makeVatID,
makeUpgradeID,
} from '../../lib/id.js';
import { kdebug } from '../../lib/kdebug.js';
import { KERNEL_STATS_METRICS } from '../metrics.js';
import { makeKernelStats } from './stats.js';
import {
enumeratePrefixedKeys,
getPrefixedValues,
deletePrefixedKeys,
} from './storageHelper.js';
const enableKernelGC = true;
/**
* @typedef { import('../../types-external.js').BundleCap } BundleCap
* @typedef { import('../../types-external.js').BundleID } BundleID
* @typedef { import('../../types-external.js').EndoZipBase64Bundle } EndoZipBase64Bundle
* @typedef { import('../../types-external.js').KernelOptions } KernelOptions
* @typedef { import('../../types-external.js').KernelSlog } KernelSlog
* @typedef { import('../../types-external.js').ManagerType } ManagerType
* @typedef { import('../../types-external.js').SnapStore } SnapStore
* @typedef { import('../../types-external.js').TranscriptStore } TranscriptStore
* @typedef { import('../../types-external.js').VatKeeper } VatKeeper
*/
// Kernel state lives in a key-value store supporting key retrieval by
// lexicographic range. All keys and values are strings.
// We simulate a tree by concatenating path-name components with ".". When we
// want to delete a subtree, we tell the store to delete everything from
// "prefix." (inclusive) to "prefix/" (exclusive), which avoids anything using an
// extension of the prefix (e.g., consider [vat1.prefix1, vat1.prefix2, vat15.prefix1]).
//
// The 'local.' namespace is excluded from the kernel activity hash, and is
// allowed to vary between instances in a consensus machine. Everything else
// is required to be deterministic.
//
// The schema is:
//
// vat.names = JSON([names..])
// vat.dynamicIDs = JSON([vatIDs..])
// vat.name.$NAME = $vatID = v$NN
// vat.nextID = $NN
// vat.nextUpgradeID = $NN
// device.names = JSON([names..])
// device.name.$NAME = $deviceID = d$NN
// device.nextID = $NN
// meter.nextID = $NN // used to make m$NN
// namedBundleID.$NAME = bundleID
// bundle.$BUNDLEID = JSON(bundle)
//
// kernel.defaultManagerType = managerType
// kernel.defaultReapInterval = $NN
// kernel.relaxDurabilityRules = missing | 'true'
// kernel.snapshotInitial = $NN
// kernel.snapshotInterval = $NN
// v$NN.source = JSON({ bundle }) or JSON({ bundleName })
// v$NN.options = JSON
// v$NN.o.nextID = $NN
// v$NN.p.nextID = $NN
// v$NN.d.nextID = $NN
// v$NN.c.$kernelSlot = '$R $vatSlot'
// $R is 'R' when reachable, '_' when merely recognizable
// $vatSlot is one of: o+$NN/o-$NN/p+$NN/p-$NN/d+$NN/d-$NN
// v$NN.c.$vatSlot = $kernelSlot = ko$NN/kp$NN/kd$NN
// v$NN.vs.$key = string
// v$NN.meter = m$NN // XXX does this exist?
// v$NN.reapInterval = $NN or 'never'
// v$NN.reapCountdown = $NN or 'never'
// exclude from consensus
// local.*
// m$NN.remaining = $NN // remaining capacity (in computrons) or 'unlimited'
// m$NN.threshold = $NN // notify when .remaining first drops below this
// kernelStats // JSON(various consensus kernel stats of other kernel state)
// local.kernelStats // JSON(various non-consensus kernel stats of other kernel state)
// d$NN.o.nextID = $NN
// d$NN.c.$kernelSlot = $deviceSlot = o-$NN/d+$NN/d-$NN
// d$NN.c.$deviceSlot = $kernelSlot = ko$NN/kd$NN
// d$NN.deviceState = JSON
// d$NN.source = JSON({ bundle }) or JSON({ bundleName })
// d$NN.options = JSON
// crankNumber = $NN
// runQueue = JSON([$head, $tail])
// runQueue.$NN = JSON(item)
// acceptanceQueue = JSON([$head, $tail])
// acceptanceQueue.$NN = JSON(item)
// gcActions = JSON(gcActions)
// reapQueue = JSON([vatIDs...])
// pinnedObjects = ko$NN[,ko$NN..]
// ko.nextID = $NN
// ko$NN.owner = $vatID
// ko$NN.refCount = $NN,$MM // reachable count, recognizable count
// kd.nextID = $NN
// kd$NN.owner = $vatID
// kp.nextID = $NN
// kp$NN.state = unresolved | fulfilled | rejected
// kp$NN.refCount = $NN
// // if unresolved:
// kp$NN.decider = missing | '' | $vatID
// kp$NN.policy = missing (=ignore) | ignore | logAlways | logFailure | panic
// kp$NN.subscribers = '' | $vatID[,$vatID..]
// kp$NN.queue.$NN = JSON(msg)
// kp$NN.queue.nextID = $NN
// // if fulfilled or rejected:
// kp$NN.data.body = missing | JSON
// kp$NN.data.slots = '' | $vatID[,$vatID..]
//
// Prefix reserved for host written data:
// host.
export function commaSplit(s) {
if (s === '') {
return [];
}
return s.split(',');
}
function insistMeterID(m) {
assert.typeof(m, 'string');
assert.equal(m[0], 'm');
Nat(BigInt(m.slice(1)));
}
// we use different starting index values for the various vNN/koNN/kdNN/kpNN
// slots, to reduce confusing overlap when looking at debug messages (e.g.
// seeing both kp1 and ko1, which are completely unrelated despite having the
// same integer), and as a weak safety mechanism to guard against slots being
// misinterpreted (if "kp1" is somehow transmuted to "ko1", then there is
// probably already a real ko1 in the table, but "kp40" being corrupted into
// "ko40" is marginally less likely to collide with koNN that start at a
// different index). The safety mechanism is only likely to help during very
// limited unit tests, where we only allocate a handful of items, but it's
// proven useful even there.
const FIRST_VAT_ID = 1n;
const FIRST_DEVICE_ID = 7n;
const FIRST_OBJECT_ID = 20n;
const FIRST_DEVNODE_ID = 30n;
const FIRST_PROMISE_ID = 40n;
const FIRST_CRANK_NUMBER = 0n;
const FIRST_METER_ID = 1n;
/**
* @param {SwingStoreKernelStorage} kernelStorage
* @param {KernelSlog|null} kernelSlog
*/
export default function makeKernelKeeper(kernelStorage, kernelSlog) {
const { kvStore, transcriptStore, snapStore, bundleStore } = kernelStorage;
insistStorageAPI(kvStore);
/**
* @param {string} key
* @returns {string}
*/
function getRequired(key) {
kvStore.has(key) || Fail`storage lacks required key ${key}`;
// @ts-ignore already checked .has()
return kvStore.get(key);
}
const {
incStat,
decStat,
getStats,
getSerializedStats,
initializeStats,
loadFromSerializedStats,
} = makeKernelStats(KERNEL_STATS_METRICS);
function saveStats() {
const { consensusStats, localStats } = getSerializedStats();
kvStore.set('kernelStats', consensusStats);
kvStore.set('local.kernelStats', localStats);
}
function loadStats() {
loadFromSerializedStats({
consensusStats: getRequired('kernelStats'),
localStats: kvStore.get('local.kernelStats'),
});
}
function startCrank() {
kernelStorage.startCrank();
}
function establishCrankSavepoint(savepoint) {
kernelStorage.establishCrankSavepoint(savepoint);
}
function rollbackCrank(savepoint) {
kernelStorage.rollbackCrank(savepoint);
loadStats();
}
function emitCrankHashes() {
saveStats();
return kernelStorage.emitCrankHashes();
}
function endCrank() {
kernelStorage.endCrank();
}
const ephemeral = harden({
/** @type { Map<string, VatKeeper> } */
vatKeepers: new Map(),
deviceKeepers: new Map(), // deviceID -> deviceKeeper
});
function getInitialized() {
return !!kvStore.get('initialized');
}
function setInitialized() {
kvStore.set('initialized', 'true');
}
function getCrankNumber() {
return Nat(BigInt(getRequired('crankNumber')));
}
function incrementCrankNumber() {
const crankNumber = Nat(BigInt(getRequired('crankNumber')));
kvStore.set('crankNumber', `${crankNumber + 1n}`);
}
function initQueue(queue) {
kvStore.set(`${queue}`, JSON.stringify([1, 1]));
}
function enqueue(queue, item) {
const [head, tail] = JSON.parse(getRequired(`${queue}`));
kvStore.set(`${queue}.${tail}`, JSON.stringify(item));
kvStore.set(`${queue}`, JSON.stringify([head, tail + 1]));
incStat(`${queue}Length`);
}
function dequeue(queue) {
const [head, tail] = JSON.parse(getRequired(`${queue}`));
if (head < tail) {
const itemKey = `${queue}.${head}`;
const item = JSON.parse(getRequired(itemKey));
kvStore.delete(itemKey);
kvStore.set(`${queue}`, JSON.stringify([head + 1, tail]));
decStat(`${queue}Length`);
return item;
} else {
return undefined;
}
}
function queueLength(queue) {
const [head, tail] = JSON.parse(getRequired(`${queue}`));
return tail - head;
}
function dumpQueue(queue) {
const [head, tail] = JSON.parse(getRequired(`${queue}`));
const result = [];
for (let i = head; i < tail; i += 1) {
result.push(JSON.parse(getRequired(`${queue}.${i}`)));
}
return result;
}
/**
* @param {KernelOptions} kernelOptions
*/
function createStartingKernelState(kernelOptions) {
const {
defaultManagerType = 'local',
defaultReapInterval = 1,
relaxDurabilityRules = false,
snapshotInitial = 3,
snapshotInterval = 200,
} = kernelOptions;
kvStore.set('vat.names', '[]');
kvStore.set('vat.dynamicIDs', '[]');
kvStore.set('vat.nextID', `${FIRST_VAT_ID}`);
kvStore.set('vat.nextUpgradeID', `1`);
kvStore.set('device.names', '[]');
kvStore.set('device.nextID', `${FIRST_DEVICE_ID}`);
kvStore.set('ko.nextID', `${FIRST_OBJECT_ID}`);
kvStore.set('kd.nextID', `${FIRST_DEVNODE_ID}`);
kvStore.set('kp.nextID', `${FIRST_PROMISE_ID}`);
kvStore.set('meter.nextID', `${FIRST_METER_ID}`);
kvStore.set('gcActions', '[]');
kvStore.set('reapQueue', '[]');
initQueue('runQueue');
initQueue('acceptanceQueue');
kvStore.set('crankNumber', `${FIRST_CRANK_NUMBER}`);
kvStore.set('kernel.defaultManagerType', defaultManagerType);
kvStore.set('kernel.defaultReapInterval', `${defaultReapInterval}`);
kvStore.set('kernel.snapshotInitial', `${snapshotInitial}`);
kvStore.set('kernel.snapshotInterval', `${snapshotInterval}`);
if (relaxDurabilityRules) {
kvStore.set('kernel.relaxDurabilityRules', 'true');
}
// Will be saved in the bootstrap commit
initializeStats();
}
/**
*
* @param {string} mt
* @returns {asserts mt is ManagerType}
*/
function insistManagerType(mt) {
assert(['local', 'node-subprocess', 'xsnap', 'xs-worker'].includes(mt));
}
function getDefaultManagerType() {
const mt = getRequired('kernel.defaultManagerType');
insistManagerType(mt);
return mt;
}
/**
* @returns {boolean}
*/
function getRelaxDurabilityRules() {
return !!kvStore.get('kernel.relaxDurabilityRules');
}
/**
*
* @returns {number | 'never'}
*/
function getDefaultReapInterval() {
const r = getRequired('kernel.defaultReapInterval');
const ri = r === 'never' ? r : Number.parseInt(r, 10);
assert(ri === 'never' || typeof ri === 'number', `k.dri is '${ri}'`);
return ri;
}
function setDefaultReapInterval(interval) {
assert(
interval === 'never' || isNat(interval),
'invalid defaultReapInterval value',
);
kvStore.set('kernel.defaultReapInterval', `${interval}`);
}
function getNat(key) {
const result = Number.parseInt(getRequired(key), 10);
assert(isNat(result));
return result;
}
function getSnapshotInitial() {
return getNat('kernel.snapshotInitial');
}
function getSnapshotInterval() {
return getNat('kernel.snapshotInterval');
}
function setSnapshotInterval(interval) {
assert(isNat(interval), 'invalid snapshotInterval value');
kvStore.set('kernel.snapshotInterval', `${interval}`);
}
const bundleIDRE = new RegExp('^b1-[0-9a-f]{128}$');
/**
* @param {string} name
* @param {BundleID} bundleID
* @returns {void}
*/
function addNamedBundleID(name, bundleID) {
assert.typeof(bundleID, 'string');
bundleIDRE.test(bundleID) || Fail`${bundleID} is not a bundleID`;
kvStore.set(`namedBundleID.${name}`, bundleID);
}
/**
* @param {string} name
* @returns {BundleID}
*/
function getNamedBundleID(name) {
return harden(getRequired(`namedBundleID.${name}`));
}
/**
* Store a bundle (by ID) in the kernel DB.
*
* @param {BundleID} bundleID The claimed bundleID: the caller
* (controller.js) must validate it first, we assume it is correct.
* @param {EndoZipBase64Bundle} bundle The code bundle, whose format must
* be 'endoZipBase64'.
*/
function addBundle(bundleID, bundle) {
assert(!bundleStore.hasBundle(bundleID), 'bundleID already installed');
bundleStore.addBundle(bundleID, bundle);
}
/**
* @param {BundleID} bundleID
* @returns {boolean}
*/
function hasBundle(bundleID) {
return bundleStore.hasBundle(bundleID);
}
/**
* @param {BundleID} bundleID
* @returns {EndoZipBase64Bundle | undefined}
*/
function getBundle(bundleID) {
if (bundleStore.hasBundle(bundleID)) {
const bundle = bundleStore.getBundle(bundleID);
if (bundle.moduleFormat !== 'endoZipBase64') {
throw Fail`unsupported module format ${bundle.moduleFormat}`;
}
return bundle;
} else {
return undefined;
}
}
function getGCActions() {
return new Set(JSON.parse(getRequired(`gcActions`)));
}
function setGCActions(actions) {
const a = Array.from(actions);
a.sort();
kvStore.set('gcActions', JSON.stringify(a));
}
function addGCActions(newActions) {
const actions = getGCActions();
for (const action of newActions) {
assert.typeof(action, 'string', 'addGCActions given bad action');
const [vatID, type, koid] = action.split(' ');
insistVatID(vatID);
['dropExport', 'retireExport', 'retireImport'].includes(type) ||
Fail`bad GCAction ${action} (type='${type}')`;
insistKernelType('object', koid);
actions.add(action);
}
setGCActions(actions);
}
function scheduleReap(vatID) {
const reapQueue = JSON.parse(getRequired('reapQueue'));
if (!reapQueue.includes(vatID)) {
reapQueue.push(vatID);
kvStore.set('reapQueue', JSON.stringify(reapQueue));
}
}
function nextReapAction() {
const reapQueue = JSON.parse(getRequired('reapQueue'));
if (reapQueue.length > 0) {
const vatID = reapQueue.shift();
kvStore.set('reapQueue', JSON.stringify(reapQueue));
return harden({ type: 'bringOutYourDead', vatID });
} else {
return undefined;
}
}
/**
* @param {string} vatID
* @param {string} kernelSlot
*/
function getReachableAndVatSlot(vatID, kernelSlot) {
const kernelKey = `${vatID}.c.${kernelSlot}`;
return parseReachableAndVatSlot(kvStore.get(kernelKey));
}
function getObjectRefCount(kernelSlot) {
const data = kvStore.get(`${kernelSlot}.refCount`);
data || Fail`getObjectRefCount(${kernelSlot}) was missing`;
const [reachable, recognizable] = commaSplit(data).map(Number);
reachable <= recognizable ||
Fail`refmismatch(get) ${kernelSlot} ${reachable},${recognizable}`;
return { reachable, recognizable };
}
function setObjectRefCount(kernelSlot, { reachable, recognizable }) {
assert.typeof(reachable, 'number');
assert.typeof(recognizable, 'number');
(reachable >= 0 && recognizable >= 0) ||
Fail`${kernelSlot} underflow ${reachable},${recognizable}`;
reachable <= recognizable ||
Fail`refmismatch(set) ${kernelSlot} ${reachable},${recognizable}`;
kvStore.set(`${kernelSlot}.refCount`, `${reachable},${recognizable}`);
}
/**
* Iterate over non-durable objects exported by a vat.
*
* @param {string} vatID
* @yields {{kref: string, vref: string}}
*/
function* enumerateNonDurableObjectExports(vatID) {
insistVatID(vatID);
// vrefs for exported objects start with o+NN (ephemeral),
// o+vNN/MM (merely-virtual), or o+dNN/MM (durable).
// We iterate through all ephemeral and virtual entries so the kernel
// can ensure that they are abandoned by a vat being upgraded.
const prefix = `${vatID}.c.`;
const ephStart = `${prefix}o+`;
const durStart = `${prefix}o+d`;
const virStart = `${prefix}o+v`;
/** @type {[string, string?][]} */
const ranges = [[ephStart, durStart], [virStart]];
for (const range of ranges) {
for (const k of enumeratePrefixedKeys(kvStore, ...range)) {
const vref = k.slice(prefix.length);
// exclude the root object, which is replaced by upgrade
if (vref !== 'o+0') {
const kref = kvStore.get(k);
assert.typeof(kref, 'string');
yield { kref, vref };
}
}
}
}
/**
* Allocate a new koid.
*
* @param {string} ownerID
* @param {bigint} [id]
* @returns {string}
*/
function addKernelObject(ownerID, id) {
// providing id= is only for unit tests
insistVatID(ownerID);
if (id === undefined) {
id = Nat(BigInt(getRequired('ko.nextID')));
kvStore.set('ko.nextID', `${id + 1n}`);
}
kdebug(`Adding kernel object ko${id} for ${ownerID}`);
const s = makeKernelSlot('object', id);
kvStore.set(`${s}.owner`, ownerID);
setObjectRefCount(s, { reachable: 0, recognizable: 0 });
incStat('kernelObjects');
return s;
}
function kernelObjectExists(kref) {
return kvStore.has(`${kref}.refCount`);
}
function ownerOfKernelObject(kernelSlot) {
insistKernelType('object', kernelSlot);
const owner = kvStore.get(`${kernelSlot}.owner`);
if (owner) {
insistVatID(owner);
}
return owner;
}
function orphanKernelObject(kref, oldVat) {
const ownerKey = `${kref}.owner`;
const ownerVat = kvStore.get(ownerKey);
ownerVat === oldVat || Fail`export ${kref} not owned by old vat`;
kvStore.delete(ownerKey);
// note that we do not delete the object here: it will be
// collected if/when all other references are dropped
}
function deleteKernelObject(koid) {
kvStore.delete(`${koid}.owner`);
kvStore.delete(`${koid}.refCount`);
decStat('kernelObjects');
// TODO: decref auxdata slots and delete auxdata, when #2069 is added
}
function addKernelDeviceNode(deviceID) {
insistDeviceID(deviceID);
const id = Nat(BigInt(getRequired('kd.nextID')));
kdebug(`Adding kernel device kd${id} for ${deviceID}`);
kvStore.set('kd.nextID', `${id + 1n}`);
const s = makeKernelSlot('device', id);
kvStore.set(`${s}.owner`, deviceID);
incStat('kernelDevices');
return s;
}
function ownerOfKernelDevice(kernelSlot) {
insistKernelType('device', kernelSlot);
const owner = kvStore.get(`${kernelSlot}.owner`);
insistDeviceID(owner);
return owner;
}
function addKernelPromise(policy) {
const kpidNum = Nat(BigInt(getRequired('kp.nextID')));
kvStore.set('kp.nextID', `${kpidNum + 1n}`);
const kpid = makeKernelSlot('promise', kpidNum);
kvStore.set(`${kpid}.state`, 'unresolved');
kvStore.set(`${kpid}.subscribers`, '');
kvStore.set(`${kpid}.queue.nextID`, `0`);
kvStore.set(`${kpid}.refCount`, `0`);
kvStore.set(`${kpid}.decider`, '');
if (policy && policy !== 'ignore') {
kvStore.set(`${kpid}.policy`, policy);
}
// queue is empty, so no state[kp$NN.queue.$NN] keys yet
incStat('kernelPromises');
incStat('kpUnresolved');
return kpid;
}
function addKernelPromiseForVat(deciderVatID) {
insistVatID(deciderVatID);
const kpid = addKernelPromise();
kdebug(`Adding kernel promise ${kpid} for ${deciderVatID}`);
kvStore.set(`${kpid}.decider`, deciderVatID);
return kpid;
}
function getKernelPromise(kernelSlot) {
insistKernelType('promise', kernelSlot);
const p = { state: getRequired(`${kernelSlot}.state`) };
switch (p.state) {
case undefined: {
throw Fail`unknown kernelPromise '${kernelSlot}'`;
}
case 'unresolved': {
p.refCount = Number(kvStore.get(`${kernelSlot}.refCount`));
p.decider = kvStore.get(`${kernelSlot}.decider`);
if (p.decider === '') {
p.decider = undefined;
}
p.policy = kvStore.get(`${kernelSlot}.policy`) || 'ignore';
p.subscribers = commaSplit(kvStore.get(`${kernelSlot}.subscribers`));
p.queue = Array.from(
getPrefixedValues(kvStore, `${kernelSlot}.queue.`),
).map(s => JSON.parse(s));
break;
}
case 'fulfilled':
case 'rejected': {
p.refCount = Number(kvStore.get(`${kernelSlot}.refCount`));
p.data = {
body: kvStore.get(`${kernelSlot}.data.body`),
slots: commaSplit(kvStore.get(`${kernelSlot}.data.slots`)),
};
for (const s of p.data.slots) {
parseKernelSlot(s);
}
break;
}
default: {
throw Fail`unknown state for ${kernelSlot}: ${p.state}`;
}
}
return harden(p);
}
function getResolveablePromise(kpid, expectedDecider) {
insistKernelType('promise', kpid);
if (expectedDecider) {
insistVatID(expectedDecider);
}
const p = getKernelPromise(kpid);
p.state === 'unresolved' || Fail`${kpid} was already resolved`;
if (expectedDecider) {
p.decider === expectedDecider ||
Fail`${kpid} is decided by ${p.decider}, not ${expectedDecider}`;
} else {
!p.decider || Fail`${kpid} is decided by ${p.decider}, not the kernel`;
}
return p;
}
function hasKernelPromise(kernelSlot) {
insistKernelType('promise', kernelSlot);
return kvStore.has(`${kernelSlot}.state`);
}
function deleteKernelPromiseState(kpid) {
kvStore.delete(`${kpid}.state`);
kvStore.delete(`${kpid}.decider`);
kvStore.delete(`${kpid}.subscribers`);
kvStore.delete(`${kpid}.policy`);
deletePrefixedKeys(kvStore, `${kpid}.queue.`);
kvStore.delete(`${kpid}.queue.nextID`);
kvStore.delete(`${kpid}.data.body`);
kvStore.delete(`${kpid}.data.slots`);
}
function deleteKernelPromise(kpid) {
const state = getRequired(`${kpid}.state`);
switch (state) {
case 'unresolved':
decStat('kpUnresolved');
break;
case 'fulfilled':
decStat('kpFulfilled');
break;
case 'rejected':
decStat('kpRejected');
break;
default:
Fail`unknown state for ${kpid}: ${state}`;
}
decStat('kernelPromises');
deleteKernelPromiseState(kpid);
kvStore.delete(`${kpid}.refCount`);
}
function requeueKernelPromise(kernelSlot) {
insistKernelType('promise', kernelSlot);
// Re-queue all messages, so they can be delivered to the resolution if the
// promise was resolved, or to the pipelining vat if the decider was
// updated.
// This is a lateral move, so we retain their original refcounts. TODO:
// this is slightly lazy, sending the message back to the same promise
// that just got resolved. When this message makes it to the front of the
// run-queue, we'll look up the resolution. Instead, we could maybe look
// up the resolution *now* and set the correct target early. Doing that
// might make it easier to remove the Promise Table entry earlier.
const p = getKernelPromise(kernelSlot);
for (const msg of p.queue) {
const entry = harden({ type: 'send', target: kernelSlot, msg });
enqueue('acceptanceQueue', entry);
}
decStat('promiseQueuesLength', p.queue.length);
deletePrefixedKeys(kvStore, `${kernelSlot}.queue.`);
kvStore.set(`${kernelSlot}.queue.nextID`, `0`);
}
function resolveKernelPromise(kernelSlot, rejected, capdata) {
insistKernelType('promise', kernelSlot);
insistCapData(capdata);
let idx = 0;
for (const dataSlot of capdata.slots) {
// eslint-disable-next-line no-use-before-define
incrementRefCount(dataSlot, `resolve|${kernelSlot}|s${idx}`);
idx += 1;
}
requeueKernelPromise(kernelSlot);
deleteKernelPromiseState(kernelSlot);
decStat('kpUnresolved');
if (rejected) {
incStat('kpRejected');
kvStore.set(`${kernelSlot}.state`, 'rejected');
} else {
incStat('kpFulfilled');
kvStore.set(`${kernelSlot}.state`, 'fulfilled');
}
kvStore.set(`${kernelSlot}.data.body`, capdata.body);
kvStore.set(`${kernelSlot}.data.slots`, capdata.slots.join(','));
}
function cleanupAfterTerminatedVat(vatID) {
insistVatID(vatID);
// eslint-disable-next-line no-use-before-define
const vatKeeper = provideVatKeeper(vatID);
const exportPrefix = `${vatID}.c.o+`;
const importPrefix = `${vatID}.c.o-`;
vatKeeper.deleteSnapshotsAndTranscript();
// Note: ASCII order is "+,-./", and we rely upon this to split the
// keyspace into the various o+NN/o-NN/etc spaces. If we were using a
// more sophisticated database, we'd keep each section in a separate
// table.
// The current store semantics ensure this iteration is lexicographic.
// Any changes to the creation of the list of promises to be rejected (and
// thus to the order in which they *get* rejected) need to preserve this
// ordering in order to preserve determinism. TODO: we would like to
// shift to a different deterministic ordering scheme that is less fragile
// in the face of potential changes in the nature of the database being
// used.
// first, scan for exported objects, which must be orphaned
for (const k of enumeratePrefixedKeys(kvStore, exportPrefix)) {
// The void for an object exported by a vat will always be of the form
// `o+NN`. The '+' means that the vat exported the object (rather than
// importing it) and therefore the object is owned by (i.e., within) the
// vat. The corresponding void->koid c-list entry will thus always
// begin with `vMM.c.o+`. In addition to deleting the c-list entry, we
// must also delete the corresponding kernel owner entry for the object,
// since the object will no longer be accessible.
const kref = kvStore.get(k);
orphanKernelObject(kref, vatID);
}
// then scan for imported objects, which must be decrefed
for (const k of enumeratePrefixedKeys(kvStore, importPrefix)) {
// abandoned imports: delete the clist entry as if the vat did a
// drop+retire
const kref = kvStore.get(k) || Fail`getNextKey ensures get`;
const vref = k.slice(`${vatID}.c.`.length);
vatKeeper.deleteCListEntry(kref, vref);
// that will also delete both db keys
}
// the caller used enumeratePromisesByDecider() before calling us,
// so they already know the orphaned promises to reject
// now loop back through everything and delete it all
for (const k of enumeratePrefixedKeys(kvStore, `${vatID}.`)) {
kvStore.delete(k);
}
// TODO: deleting entries from the dynamic vat IDs list requires a linear
// scan of the list; arguably this collection ought to be represented in a
// different way that makes it efficient to remove an entry from it, though
// for the time being the linear list should be OK enough as long as we keep
// the list short.
const DYNAMIC_IDS_KEY = 'vat.dynamicIDs';
const oldDynamicVatIDs = JSON.parse(getRequired(DYNAMIC_IDS_KEY));
const newDynamicVatIDs = oldDynamicVatIDs.filter(v => v !== vatID);
if (newDynamicVatIDs.length !== oldDynamicVatIDs.length) {
kvStore.set(DYNAMIC_IDS_KEY, JSON.stringify(newDynamicVatIDs));
} else {
kdebug(`removing static vat ${vatID}`);
for (const k of enumeratePrefixedKeys(kvStore, 'vat.name.')) {
if (kvStore.get(k) === vatID) {
kvStore.delete(k);
const VAT_NAMES_KEY = 'vat.names';
const name = k.slice('vat.name.'.length);
const oldStaticVatNames = JSON.parse(getRequired(VAT_NAMES_KEY));
const newStaticVatNames = oldStaticVatNames.filter(v => v !== name);
kvStore.set(VAT_NAMES_KEY, JSON.stringify(newStaticVatNames));
break;
}
}
decStat('vats');
}
}
function addMessageToPromiseQueue(kernelSlot, msg) {
insistKernelType('promise', kernelSlot);
insistMessage(msg);
// Each message on a promise's queue maintains a refcount to the promise
// itself. This isn't strictly necessary (the promise will be kept alive
// by the deciding vat's clist, or the queued message that holds this
// promise as its result), but it matches our policy with run-queue
// messages (each holds a refcount on its target).
//
// Messages are enqueued on a promise queue in 2 cases:
// - A message routed from the acceptance queue
// - A pipelined message had a decider change while in the run-queue
// Messages are dequeued from a promise queue in 2 cases:
// - The promise is resolved
// - The promise's decider is changed to a pipelining vat
// In all cases the messages are just moved from one queue to another so
// the caller should not need to change the refcounts when moving messages
// sent to promises between queues. Only when re-targeting after resolution
// would the targets refcount be updated (but not the result or slots).
//
// Since messages are moved from queue to queue, the tag describing the ref
// does not designate which current queue the message sits on, but that
// there is some kernel queue holding the message and its content.
const p = getKernelPromise(kernelSlot);
p.state === 'unresolved' ||
Fail`${kernelSlot} is '${p.state}', not 'unresolved'`;
const nkey = `${kernelSlot}.queue.nextID`;
const nextID = Nat(BigInt(getRequired(nkey)));
kvStore.set(nkey, `${nextID + 1n}`);
const qid = `${kernelSlot}.queue.${nextID}`;
kvStore.set(qid, JSON.stringify(msg));
incStat('promiseQueuesLength');
}
function setDecider(kpid, decider) {
insistVatID(decider);
const p = getKernelPromise(kpid);
p.state === 'unresolved' || Fail`${kpid} was already resolved`;
!p.decider || Fail`${kpid} has decider ${p.decider}, not empty`;
kvStore.set(`${kpid}.decider`, decider);
}
function clearDecider(kpid) {
const p = getKernelPromise(kpid);
p.state === 'unresolved' || Fail`${kpid} was already resolved`;
p.decider || Fail`${kpid} does not have a decider`;
kvStore.set(`${kpid}.decider`, '');
}
function* enumeratePromisesByDecider(vatID) {
insistVatID(vatID);
const promisePrefix = `${vatID}.c.p`;
for (const k of enumeratePrefixedKeys(kvStore, promisePrefix)) {
// The vpid for a promise imported or exported by a vat (and thus
// potentially a promise for which the vat *might* be the decider) will
// always be of the form `p+NN` or `p-NN`. The corresponding vpid->kpid
// c-list entry will thus always begin with `vMM.c.p`. Decider-ship is
// independent of whether the promise was imported or exported, so we
// have to look up the corresponding kernel promise table entry to see
// whether the vat is the decider or not. If it is, we add the promise
// to the list of promises that must be rejected because the dead vat
// will never be able to act upon them.
const kpid = kvStore.get(k);
const p = getKernelPromise(kpid);
if (p.state === 'unresolved' && p.decider === vatID) {
yield kpid;
}
}
}
function addSubscriberToPromise(kernelSlot, vatID) {
insistKernelType('promise', kernelSlot);
insistVatID(vatID);
const p = getKernelPromise(kernelSlot);
const s = new Set(p.subscribers);
s.add(vatID);
const v = Array.from(s).sort().join(',');
kvStore.set(`${kernelSlot}.subscribers`, v);
}
function addToRunQueue(msg) {
enqueue('runQueue', msg);
}
function getRunQueueLength() {
return queueLength('runQueue');
}
function getNextRunQueueMsg() {
return dequeue('runQueue');
}
function addToAcceptanceQueue(msg) {
enqueue('acceptanceQueue', msg);
}
function getAcceptanceQueueLength() {
return queueLength('acceptanceQueue');
}
function getNextAcceptanceQueueMsg() {
return dequeue('acceptanceQueue');
}
function allocateMeter(remaining, threshold) {
if (remaining !== 'unlimited') {
assert.typeof(remaining, 'bigint');
Nat(remaining);
}
assert.typeof(threshold, 'bigint');
Nat(threshold);
const nextID = Nat(BigInt(getRequired('meter.nextID')));
kvStore.set('meter.nextID', `${nextID + 1n}`);
const meterID = `m${nextID}`;
kvStore.set(`${meterID}.remaining`, `${remaining}`);
kvStore.set(`${meterID}.threshold`, `${threshold}`);
return meterID;
}
function addMeterRemaining(meterID, delta) {
insistMeterID(meterID);
assert.typeof(delta, 'bigint');
Nat(delta);
/** @type { bigint | string } */
let remaining = getRequired(`${meterID}.remaining`);
if (remaining !== 'unlimited') {
remaining = Nat(BigInt(remaining));
kvStore.set(`${meterID}.remaining`, `${remaining + delta}`);
}
}