Files: 535100729b49473f07a4c560fa6b81aa2b369544 / index.js
1892 bytesRaw
1 | const Graph = require('ipld-graph-builder') |
2 | const Kernel = require('./kernel.js') |
3 | |
4 | module.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 | await kernel.wait(threshold) |
56 | return kernel |
57 | } |
58 | |
59 | createPort (type, payload = {}, id = {nonce: [0], parent: null}) { |
60 | const VM = this._opts.VMs[type] |
61 | return { |
62 | 'messages': [], |
63 | 'id': { |
64 | '/': id |
65 | }, |
66 | 'type': type, |
67 | 'link': { |
68 | '/': VM.createState(payload) |
69 | } |
70 | } |
71 | } |
72 | |
73 | async createStateRoot (port, ticks) { |
74 | await this.wait(port, ticks) |
75 | return this.graph.flush(port) |
76 | } |
77 | |
78 | async generateID (port) { |
79 | const id = await this.graph.flush(port.id) |
80 | return id['/'] |
81 | } |
82 | |
83 | addVM (type, vm) { |
84 | this._opts.VMs[type] = vm |
85 | } |
86 | } |
87 |
Built with git-ssb-web