git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: eacc6aefd1d880bdcfc1c451260d67651c742adb

Files: eacc6aefd1d880bdcfc1c451260d67651c742adb / index.js

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

Built with git-ssb-web