git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 4a1f9a53b0854ec031013d473ac2f51e826d4dc5

Files: 4a1f9a53b0854ec031013d473ac2f51e826d4dc5 / index.js

2100 bytesRaw
1const Graph = require('ipld-graph-builder')
2const multibase = require('multibase')
3const Kernel = require('./kernel.js')
4
5class Root {
6 queue () {
7 console.log('root queued!')
8 }
9}
10
11module.exports = class Hypervisor {
12 constructor (opts) {
13 this._opts = {
14 VMs: {}
15 }
16
17 this.graph = new Graph(opts.dag)
18 delete opts.dag
19 this.root = new Root()
20 this._vmInstances = new Map([[null, new Root()]])
21 Object.assign(this._opts, opts)
22 }
23
24 async getInstance (port) {
25 let id = await this.generateID(port)
26 let kernel = this._vmInstances.get(id)
27 if (!kernel) {
28 // load the container from the state
29 await this.graph.tree(port, 2)
30
31 // create a new kernel instance
32 const VM = this._opts.VMs[port.type]
33
34 kernel = new Kernel({
35 parentPort: port,
36 hypervisor: this,
37 VM: VM
38 })
39
40 await kernel.start()
41 kernel.on('idle', () => {
42 this._vmInstances.delete(id)
43 })
44 this._vmInstances.set(id, kernel)
45 }
46 return kernel
47 }
48
49 async send (port, message) {
50 const vm = await this.getInstance(port)
51 const id = await this.generateID(port)
52 message._fromPort = id
53 vm.queue(message)
54 }
55
56 // given a port, wait untill its source contract has reached the threshold
57 // tick count
58 async wait (port, threshold) {
59 let kernel = await this.getInstance(port)
60 return kernel.wait(threshold)
61 }
62
63 createPort (type, id = {nonce: [0], parent: null}) {
64 const VM = this._opts.VMs[type]
65 return {
66 'messages': [],
67 'id': {
68 '/': id
69 },
70 'type': type,
71 'link': {
72 '/': VM.createState()
73 }
74 }
75 }
76
77 async createStateRoot (port, ticks) {
78 await this.wait(port, ticks)
79 return this.graph.flush(port)
80 }
81
82 async generateID (port) {
83 // root id
84 if (!port) {
85 return null
86 }
87
88 let id = await this.graph.flush(port.id)
89 id = id['/']
90 if (Buffer.isBuffer(id)) {
91 id = multibase.encode('base58btc', id).toString()
92 }
93 return id
94 }
95
96 addVM (type, vm) {
97 this._opts.VMs[type] = vm
98 }
99}
100

Built with git-ssb-web