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