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