git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 05c4e2d027ee79f709d87c92e48f83e9cb3489ad

Files: 05c4e2d027ee79f709d87c92e48f83e9cb3489ad / index.js

2514 bytesRaw
1const Vertex = require('merkle-trie')
2const imports = require('./EVMinterface.js')
3const codeHandler = require('./codeHandler.js')
4const MessageQueue = require('./messageQueue')
5
6const PARENT_SYMBOL = Symbol('parent')
7const ROOT_SYMBOL = Symbol('root')
8
9module.exports = class Kernel {
10 constructor (opts = {}) {
11 const state = this.state = opts.state || new Vertex()
12 state.value = opts.code || state.value
13 this.imports = opts.imports || [imports]
14 this.parent = opts.parent
15 // RENAME agent
16 this._vm = (opts.codeHandler || codeHandler).init(state.value)
17 this._messageQueue = new MessageQueue(this)
18 this._instanceCache = new Map()
19 }
20
21 static get PARENT () {
22 return PARENT_SYMBOL
23 }
24
25 static get ROOT () {
26 return ROOT_SYMBOL
27 }
28
29 get PARENT () {
30 return PARENT_SYMBOL
31 }
32
33 get ROOT () {
34 return ROOT_SYMBOL
35 }
36
37 /**
38 * run the kernels code with a given enviroment
39 * The Kernel Stores all of its state in the Environment. The Interface is used
40 * to by the VM to retrive infromation from the Environment.
41 */
42 async run (message, imports = this.imports) {
43 const state = this.state.copy()
44
45 // const stateInterface = new StateInterface(state)
46 const result = await this._vm.run(message, this, imports)
47 if (!result.execption) {
48 // update the state
49 await this.state.set([], state)
50 }
51 return result
52 }
53
54 async recieve (message) {
55 if (message.isCyclic(this)) {
56 const result = await this.run(message)
57 message.finished()
58 return result
59 } else {
60 return this._messageQueue.add(message)
61 }
62 }
63
64 async send (port, message) {
65 message.sending(this, this._messageQueue.currentMessage)
66 // replace root with parent path to root
67 if (port === ROOT_SYMBOL) {
68 port = PARENT_SYMBOL
69 message.to = new Array(this.state.path.length - 1).fill(PARENT_SYMBOL).concat(message.to)
70 }
71
72 if (port === PARENT_SYMBOL) {
73 message.from.push(this.state.name)
74 } else {
75 message.from.push(this.PARENT)
76 }
77
78 const dest = await this.getPort(port)
79 return dest.recieve(message)
80 }
81
82 async getPort (port) {
83 if (this._instanceCache.has(port)) {
84 return this._instanceCache.get(port)
85 } else {
86 const destState = await (port === this.PARENT
87 ? this.state.getParent()
88 : this.state.get([port]))
89
90 const kernel = new Kernel({
91 state: destState
92 })
93 this._instanceCache.set(port, kernel)
94 return kernel
95 }
96 }
97}
98

Built with git-ssb-web