Files: 5abe6750505a23791da65e54301ec095a9551bb6 / creationService.js
2102 bytesRaw
1 | const Message = require('primea-message') |
2 | const DeleteMessage = require('./deleteMessage.js') |
3 | |
4 | module.exports = class CreationService { |
5 | constructor (opts) { |
6 | this.hypervisor = opts.hypervisor |
7 | this.scheduler = this.hypervisor.scheduler |
8 | } |
9 | |
10 | queue (port, message) { |
11 | if (message.data[0] === 0x00) { |
12 | let id |
13 | if (message.fromId) { |
14 | const creator = this.scheduler.getInstance(message.fromId) |
15 | id = creator.generateNextId() |
16 | } |
17 | return this.createInstance(message, id) |
18 | } else if (message.responsePort && !(message instanceof DeleteMessage)) { |
19 | this.send(message.responsePort, new Message({ |
20 | ports: [this.getPort()] |
21 | })) |
22 | } |
23 | } |
24 | |
25 | getPort () { |
26 | return { |
27 | messages: [], |
28 | destId: 0 |
29 | } |
30 | } |
31 | |
32 | send (port, message) { |
33 | message._hops++ |
34 | message._fromTicks = this.ticks |
35 | message.fromId = this.id |
36 | |
37 | return this.hypervisor.send(port, message) |
38 | } |
39 | |
40 | /** |
41 | * creates an new container instances and save it in the state |
42 | * @returns {Promise} |
43 | */ |
44 | async createInstance (message, id = {nonce: 0, parent: null}) { |
45 | const encoded = encodedID(id) |
46 | const idHash = await this._getHashFromObj(encoded) |
47 | const state = { |
48 | nonce: 0, |
49 | ports: {}, |
50 | type: message.data[1] |
51 | } |
52 | |
53 | const code = message.data.slice(2) |
54 | if (code.length) { |
55 | state.code = code |
56 | } |
57 | |
58 | // create the container instance |
59 | const instance = await this.hypervisor._loadInstance(idHash, state) |
60 | |
61 | // send the intialization message |
62 | await instance.create(message) |
63 | |
64 | // save the container in the state |
65 | await this.hypervisor.tree.set(idHash, state) |
66 | |
67 | if (!Object.keys(instance.ports.ports).length) { |
68 | this.hypervisor.addNodeToCheck(instance.id) |
69 | } |
70 | |
71 | return instance |
72 | } |
73 | |
74 | get state () { |
75 | return {} |
76 | } |
77 | |
78 | // get a hash from a POJO |
79 | _getHashFromObj (obj) { |
80 | return this.hypervisor.tree.constructor.getMerkleLink(obj) |
81 | } |
82 | } |
83 | |
84 | function encodedID (id) { |
85 | const nonce = Buffer.from([id.nonce]) |
86 | if (id.parent) { |
87 | return Buffer.concat([nonce, id.parent]) |
88 | } else { |
89 | return nonce |
90 | } |
91 | } |
92 |
Built with git-ssb-web