-
Notifications
You must be signed in to change notification settings - Fork 3
/
runner.js
58 lines (52 loc) · 1.36 KB
/
runner.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
import { promises as fs } from 'fs'
import os from 'os'
import path from 'path'
import { xsnap } from '@agoric/xsnap'
import { spawn } from 'child_process'
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export function createRunner () {
let isInitialized = false
let worker
return {
initiailize,
runCommand,
getSystemState,
close
}
async function initiailize () {
worker = xsnap({
os: os.type(),
spawn
})
const kernelSrc = await fs.readFile(path.join(__dirname, 'kernel.js'), 'utf8')
await worker.evaluate(kernelSrc)
console.log('initialized kernel')
isInitialized = true
}
async function runCommand (authorId, command) {
if (!isInitialized) {
await initiailize()
}
let response
try {
response = await worker.issueStringCommand(JSON.stringify({ authorId, command }))
} catch (err) {
err.fatal = true
return { error: err }
}
return JSON.parse(response.reply)
}
async function getSystemState () {
const response = await worker.issueStringCommand(JSON.stringify({ authorId: 'system', command: 'systemState' }))
return JSON.parse(response.reply)
}
async function close () {
try {
await worker.close()
} catch (error) {
console.warn(error)
await worker.terminate()
}
}
}