git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: f22f4faca05d5fe9f3c3e32dfb4d78ac9d5acb21

Files: f22f4faca05d5fe9f3c3e32dfb4d78ac9d5acb21 / creationService.js

2105 bytesRaw
1const Message = require('primea-message')
2const DeleteMessage = require('./deleteMessage.js')
3
4module.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.type) {
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.type
51 }
52
53 if (message.data.code && message.data.code.length) {
54 state.code = message.data.code
55 }
56
57 // create the container instance
58 const instance = await this.hypervisor._loadInstance(idHash, state)
59
60 // send the intialization message
61 await instance.create(message)
62
63 // save the container in the state
64 await this.hypervisor.tree.set(idHash, state)
65
66 if (!Object.keys(instance.ports.ports).length) {
67 this.hypervisor.addNodeToCheck(instance.id)
68 }
69
70 return instance
71 }
72
73 get state () {
74 return {}
75 }
76
77 // get a hash from a POJO
78 _getHashFromObj (obj) {
79 return this.hypervisor.tree.constructor.getMerkleLink(obj)
80 }
81}
82
83function encodedID (id) {
84 const nonce = Buffer.from([id.nonce])
85 if (id.parent) {
86 return Buffer.concat([nonce, id.parent])
87 } else {
88 return nonce
89 }
90}
91

Built with git-ssb-web