Files: 0a8350a93125e32b15276e387bc08d9e51610c0c / creationService.js
1698 bytesRaw
1 | const chunk = require('chunk') |
2 | |
3 | const MAX_DATA_BYTES = 65533 |
4 | |
5 | module.exports = class CreationService { |
6 | constructor (opts) { |
7 | this.hypervisor = opts.hypervisor |
8 | this.scheduler = this.hypervisor.scheduler |
9 | } |
10 | |
11 | queue (port, message) { |
12 | if (message.data.type) { |
13 | const creator = this.scheduler.getInstance(message.fromId) |
14 | const id = creator.generateNextId() |
15 | return this.createInstance(message, id) |
16 | } |
17 | } |
18 | |
19 | getPort () { |
20 | return { |
21 | messages: [], |
22 | destId: 0 |
23 | } |
24 | } |
25 | |
26 | /** |
27 | * creates an new container instances and save it in the state |
28 | * @returns {Promise} |
29 | */ |
30 | async createInstance (message, id = {nonce: 0, parent: null}) { |
31 | const idHash = await this._getHashFromObj(id) |
32 | const state = { |
33 | nonce: [0], |
34 | ports: {}, |
35 | type: message.data.type |
36 | } |
37 | |
38 | if (message.data.code && message.data.code.length) { |
39 | state.code = message.data.code |
40 | } |
41 | |
42 | // create the container instance |
43 | const instance = await this.hypervisor._loadInstance(idHash, state) |
44 | |
45 | // send the intialization message |
46 | await instance.create(message) |
47 | |
48 | if (Object.keys(instance.ports.ports).length || instance.id === this.hypervisor.ROOT_ID) { |
49 | if (state.code && state.code.length > MAX_DATA_BYTES) { |
50 | state.code = chunk(state.code, MAX_DATA_BYTES).map(chk => { |
51 | return { |
52 | '/': chk |
53 | } |
54 | }) |
55 | } |
56 | // save the container in the state |
57 | await this.hypervisor.tree.set(idHash, state) |
58 | } else { |
59 | this.scheduler.done(idHash) |
60 | } |
61 | |
62 | return instance |
63 | } |
64 | |
65 | // get a hash from a POJO |
66 | _getHashFromObj (obj) { |
67 | return this.hypervisor.graph.flush(obj).then(obj => obj['/']) |
68 | } |
69 | } |
70 |
Built with git-ssb-web