-
Notifications
You must be signed in to change notification settings - Fork 208
/
supervisor-subprocess-xsnap.js
323 lines (290 loc) · 8.94 KB
/
supervisor-subprocess-xsnap.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
/* global globalThis WeakRef FinalizationRegistry */
import { assert, Fail } from '@agoric/assert';
import { importBundle } from '@endo/import-bundle';
import { makeMarshal } from '@endo/marshal';
import '../../types-ambient.js';
// grumble... waitUntilQuiescent is exported and closes over ambient authority
import { waitUntilQuiescent } from '../../lib-nodejs/waitUntilQuiescent.js';
import { makeGcAndFinalize } from '../../lib-nodejs/gc-and-finalize.js';
import {
insistVatDeliveryObject,
insistVatSyscallResult,
} from '../../lib/message.js';
import { makeLiveSlots } from '../../liveslots/liveslots.js';
import {
makeSupervisorDispatch,
makeSupervisorSyscall,
makeVatConsole,
} from '../supervisor-helper.js';
const encoder = new TextEncoder();
const decoder = new TextDecoder();
// eslint-disable-next-line no-unused-vars
function workerLog(first, ...args) {
// eslint-disable-next-line
// console.log(`---worker: ${first}`, ...args);
}
workerLog(`supervisor started`);
function makeMeterControl() {
let meteringDisabled = 0;
function isMeteringDisabled() {
return !!meteringDisabled;
}
function assertIsMetered(msg) {
assert(!meteringDisabled, msg);
}
function assertNotMetered(msg) {
assert(!!meteringDisabled, msg);
}
function runWithoutMetering(thunk) {
const limit = globalThis.currentMeterLimit();
const before = globalThis.resetMeter(0, 0);
meteringDisabled += 1;
try {
return thunk();
} finally {
globalThis.resetMeter(limit, before);
meteringDisabled -= 1;
}
}
async function runWithoutMeteringAsync(thunk) {
const limit = globalThis.currentMeterLimit();
const before = globalThis.resetMeter(0, 0);
meteringDisabled += 1;
return Promise.resolve()
.then(() => thunk())
.finally(() => {
globalThis.resetMeter(limit, before);
meteringDisabled -= 1;
});
}
// return a version of f that runs outside metering
function unmetered(f) {
function wrapped(...args) {
return runWithoutMetering(() => f(...args));
}
return harden(wrapped);
}
/** @type { MeterControl } */
const meterControl = {
isMeteringDisabled,
assertIsMetered,
assertNotMetered,
runWithoutMetering,
runWithoutMeteringAsync,
unmetered,
};
return harden(meterControl);
}
const meterControl = makeMeterControl();
/**
* Wrap byte-level protocols with tagged array codec.
*
* @param {(cmd: ArrayBuffer) => ArrayBuffer} issueCommand as from xsnap
* @typedef { [unknown, ...unknown[]] } Tagged tagged array
*/
function managerPort(issueCommand) {
/** @type { (item: Tagged) => ArrayBuffer } */
const encode = item => {
let txt;
try {
txt = JSON.stringify(item);
} catch (nope) {
workerLog(nope.message, item);
throw nope;
}
return encoder.encode(txt).buffer;
};
/** @type { (msg: ArrayBuffer) => any } */
const decodeData = msg => JSON.parse(decoder.decode(msg) || 'null');
/** @type { (msg: ArrayBuffer) => Tagged } */
function decode(msg) {
/** @type { Tagged } */
const item = decodeData(msg);
Array.isArray(item) || Fail`expected array`;
item.length > 0 || Fail`empty array lacks tag`;
return item;
}
return harden({
/** @type { (item: Tagged) => void } */
send: item => {
issueCommand(encode(item));
},
/** @type { (item: Tagged) => unknown } */
call: item => decodeData(issueCommand(encode(item))),
/**
* Wrap an async Tagged handler in the xsnap async reporting idiom.
*
* @param {(item: Tagged) => Promise<Tagged>} f async Tagged handler
* @returns {(msg: ArrayBuffer) => Report<ArrayBuffer>} xsnap style handleCommand
*
* @typedef { { result?: T } } Report<T> report T when idle
* @template T
*/
handlerFrom(f) {
const lastResort = encoder.encode(`exception from ${f.name}`).buffer;
return msg => {
const report = {};
f(decode(msg))
.then(item => {
workerLog('result', item);
report.result = encode(item);
})
.catch(err => {
report.result = encode(['err', err.name, err.message]);
})
.catch(_err => {
report.result = lastResort;
});
return report;
};
},
});
}
// please excuse copy-and-paste from kernel.js
function abbreviateReplacer(_, arg) {
if (typeof arg === 'bigint') {
// since testLog is only for testing, 2^53 is enough.
// precedent: 32a1dd3
return Number(arg);
}
if (typeof arg === 'string' && arg.length >= 40) {
// truncate long strings
return `${arg.slice(0, 15)}...${arg.slice(arg.length - 15)}`;
}
return arg;
}
/**
* @param {ReturnType<typeof managerPort>} port
*/
function makeWorker(port) {
/** @type { ((delivery: VatDeliveryObject) => Promise<VatDeliveryResult>) | null } */
let dispatch = null;
/**
* @param {unknown} vatID
* @param {unknown} bundle
* @param {LiveSlotsOptions} liveSlotsOptions
* @returns {Promise<Tagged>}
*/
async function setBundle(vatID, bundle, liveSlotsOptions) {
/** @type { (vso: VatSyscallObject) => VatSyscallResult } */
function syscallToManager(vatSyscallObject) {
workerLog('doSyscall', vatSyscallObject);
const result = port.call(['syscall', vatSyscallObject]);
workerLog(' ... syscall result:', result);
insistVatSyscallResult(result);
return result;
}
const syscall = makeSupervisorSyscall(syscallToManager, true);
const vatPowers = {
makeMarshal,
testLog: (...args) =>
port.send([
'testLog',
...args.map(arg =>
typeof arg === 'string'
? arg
: JSON.stringify(arg, abbreviateReplacer),
),
]),
};
const gcTools = harden({
WeakRef,
FinalizationRegistry,
waitUntilQuiescent,
gcAndFinalize: makeGcAndFinalize(globalThis.gc),
meterControl,
});
/** @param {string} source */
const makeLogMaker = source => {
/** @param {string} level */
const makeLog = level => {
// Capture the `console.log`, etc.'s `printAll` function.
const printAll = console[level];
assert.typeof(printAll, 'function');
const portSendingPrinter = (...args) => {
port.send(['sourcedConsole', source, level, ...args]);
};
return (...args) => {
// Use the causal console, but output to the port.
//
// FIXME: This is a hack until the start compartment can create
// Console objects that log to a different destination than
// `globalThis.console`.
const { print: savePrinter } = globalThis;
try {
globalThis.print = portSendingPrinter;
printAll(...args);
} finally {
globalThis.print = savePrinter;
}
};
};
return makeLog;
};
const workerEndowments = {
console: makeVatConsole(makeLogMaker('vat')),
assert,
// bootstrap provides HandledPromise
HandledPromise: globalThis.HandledPromise,
TextEncoder,
TextDecoder,
Base64: globalThis.Base64, // Present only in XSnap
};
async function buildVatNamespace(
lsEndowments,
inescapableGlobalProperties,
) {
const vatNS = await importBundle(bundle, {
endowments: { ...workerEndowments, ...lsEndowments },
inescapableGlobalProperties,
});
workerLog(`got vatNS:`, Object.keys(vatNS).join(','));
return vatNS;
}
const ls = makeLiveSlots(
syscall,
vatID,
vatPowers,
liveSlotsOptions,
gcTools,
makeVatConsole(makeLogMaker('ls')),
buildVatNamespace,
);
assert(ls.dispatch);
dispatch = makeSupervisorDispatch(ls.dispatch);
workerLog(`got dispatch`);
return ['dispatchReady'];
}
/** @type { (item: Tagged) => Promise<Tagged> } */
async function handleItem([tag, ...args]) {
workerLog('handleItem', tag, args.length);
switch (tag) {
case 'setBundle': {
assert(!dispatch, 'cannot setBundle again');
const liveSlotsOptions = /** @type LiveSlotsOptions */ (args[2]);
return setBundle(args[0], args[1], liveSlotsOptions);
}
case 'deliver': {
assert(dispatch, 'cannot deliver before setBundle');
const [vatDeliveryObject] = args;
harden(vatDeliveryObject);
insistVatDeliveryObject(vatDeliveryObject);
return dispatch(vatDeliveryObject);
}
default:
workerLog('handleItem: bad tag', tag, args.length);
return ['bad tag', tag];
}
}
return harden({
handleItem,
});
}
// xsnap provides issueCommand global
const port = managerPort(globalThis.issueCommand);
const worker = makeWorker(port);
// Send unexpected console messages to the manager port.
globalThis.print = (...args) => {
port.send(['sourcedConsole', 'xsnap', 'error', ...args]);
};
globalThis.handleCommand = port.handlerFrom(worker.handleItem);