git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: b17f430cb428dc0322dc3915948f9c7802107eda

Files: b17f430cb428dc0322dc3915948f9c7802107eda / index.js

5419 bytesRaw
1const Tree = require('merkle-radix-tree')
2const Graph = require('ipld-graph-builder')
3const chunk = require('chunk')
4const Message = require('primea-message')
5const Kernel = require('./kernel.js')
6const Scheduler = require('./scheduler.js')
7const DFSchecker = require('./dfsChecker.js')
8
9module.exports = class Hypervisor {
10 /**
11 * The Hypervisor manages the container instances by instantiating them and
12 * destorying them when possible. It also facilitates localating Containers
13 * @param {Graph} dag an instance of [ipfs.dag](https://github.com/ipfs/interface-ipfs-core/tree/master/API/dag#dag-api)
14 * @param {object} state - the starting state
15 */
16 constructor (dag, state = {'/': Tree.emptyTreeState}) {
17 this.graph = new Graph(dag)
18 this.tree = new Tree({
19 graph: this.graph,
20 root: state
21 })
22 this.scheduler = new Scheduler()
23 this.state = state
24 this._containerTypes = {}
25 this._nodesToCheck = new Set()
26
27 this.ROOT_ID = 'zdpuAm6aTdLVMUuiZypxkwtA7sKm7BWERy8MPbaCrFsmiyzxr'
28 this.MAX_DATA_BYTES = 65533
29 }
30
31 /**
32 * add a potaintail node in the state graph to check for garbage collection
33 * @param {string} id
34 */
35 addNodeToCheck (id) {
36 this._nodesToCheck.add(id)
37 }
38
39 /**
40 * given a port, this finds the corridsponeding endpoint port of the channel
41 * @param {object} port
42 * @returns {Promise}
43 */
44 async getDestPort (port) {
45 if (port.destPort) {
46 return port.destPort
47 } else {
48 const containerState = await this.tree.get(port.destId)
49 return this.graph.get(containerState, `ports/${port.destName}`)
50 }
51 }
52
53 async send (port, message) {
54 if (port.destId) {
55 const id = port.destId
56 const instance = await this.getInstance(id)
57 return instance.queue(port.destName, message)
58 } else {
59 // port is unbound
60 port.destPort.messages.push(message)
61 }
62 }
63
64 // loads an instance of a container from the state
65 async _loadInstance (id) {
66 const state = await this.tree.get(id)
67 const container = this._containerTypes[state.type]
68 let code
69
70 // checks if the code stored in the state is an array and that the elements
71 // are merkle link
72 if (state.code && state.code[0]['/']) {
73 await this.graph.tree(state.code, 1)
74 code = state.code.map(a => a['/']).reduce((a, b) => a + b)
75 } else {
76 code = state.code
77 }
78
79 // create a new kernel instance
80 const kernel = new Kernel({
81 hypervisor: this,
82 state: state,
83 code: code,
84 container: container,
85 id: id
86 })
87
88 // save the newly created instance
89 this.scheduler.update(kernel)
90 return kernel
91 }
92
93 // get a hash from a POJO
94 _getHashFromObj (obj) {
95 return this.graph.flush(obj).then(obj => obj['/'])
96 }
97
98 /**
99 * gets an existsing container instances
100 * @param {string} id - the containers ID
101 * @returns {Promise}
102 */
103 async getInstance (id) {
104 let instance = this.scheduler.getInstance(id)
105 if (instance) {
106 return instance
107 } else {
108 const resolve = this.scheduler.getLock(id)
109 const instance = await this._loadInstance(id)
110 await instance.startup()
111 resolve(instance)
112 return instance
113 }
114 }
115
116 /**
117 * creates an new container instances and save it in the state
118 * @param {string} type - the type of container to create
119 * @param {*} code
120 * @param {array} entryPorts
121 * @param {object} id
122 * @param {object} id.nonce
123 * @param {object} id.parent
124 * @returns {Promise}
125 */
126 async createInstance (type, message = new Message(), id = {nonce: 0, parent: null}) {
127 // create a lock to prevent the scheduler from reloving waits before the
128 // new container is loaded
129 const resolve = this.scheduler.getLock(id)
130 const idHash = await this._getHashFromObj(id)
131 // const code = message.data.byteLength ? message.data : undefined
132 const state = {
133 nonce: [0],
134 ports: {},
135 type: type
136 }
137
138 if (message.data.length) {
139 state.code = message.data
140 }
141
142 // save the container in the state
143 await this.tree.set(idHash, state)
144 // create the container instance
145 const instance = await this._loadInstance(idHash)
146 resolve(instance)
147 // send the intialization message
148 await instance.create(message)
149
150 if (state.code && state.code.length > this.MAX_DATA_BYTES) {
151 state.code = chunk(state.code, this.MAX_DATA_BYTES).map(chk => {
152 return {
153 '/': chk
154 }
155 })
156 }
157
158 return instance
159 }
160
161 /**
162 * creates a state root starting from a given container and a given number of
163 * ticks
164 * @param {Number} ticks the number of ticks at which to create the state root
165 * @returns {Promise}
166 */
167 async createStateRoot (ticks) {
168 await this.scheduler.wait(ticks)
169 const unlinked = await DFSchecker(this.tree, this.ROOT_ID, this._nodesToCheck)
170 unlinked.forEach(id => {
171 this.tree.delete(id)
172 })
173 return this.graph.flush(this.state)
174 }
175
176 /**
177 * regirsters a container with the hypervisor
178 * @param {Class} Constructor - a Class for instantiating the container
179 * @param {*} args - any args that the contructor takes
180 * @param {interger} typeId - the container's type identification ID
181 */
182 registerContainer (Constructor, args, typeId = Constructor.typeId) {
183 this._containerTypes[typeId] = {
184 Constructor: Constructor,
185 args: args
186 }
187 }
188}
189

Built with git-ssb-web