git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: b95b6a5752781c6cea64703d51e548ffddfb48ac

Files: b95b6a5752781c6cea64703d51e548ffddfb48ac / index.js

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

Built with git-ssb-web