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