git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 2fb975398cfb471a241d9576050158a86e8eff04

Files: 2fb975398cfb471a241d9576050158a86e8eff04 / portManager.js

6805 bytesRaw
1const DeleteMessage = require('./deleteMessage')
2
3// decides which message to go first
4function messageArbiter (nameA, nameB) {
5 const a = this.ports[nameA].messages[0]
6 const b = this.ports[nameB].messages[0]
7
8 if (!a) {
9 return nameB
10 } else if (!b) {
11 return nameA
12 }
13
14 // order by number of ticks if messages have different number of ticks
15 if (a._fromTicks !== b._fromTicks) {
16 return a._fromTicks < b._fromTicks ? nameA : nameB
17 } else {
18 // insertion order
19 return nameA
20 }
21}
22
23module.exports = class PortManager {
24 /**
25 * The port manager manages the the ports. This inculdes creation, deletion
26 * fetching and waiting on ports
27 * @param {Object} opts
28 * @param {Object} opts.state
29 * @param {Object} opts.hypervisor
30 * @param {Object} opts.exoInterface
31 */
32 constructor (opts) {
33 Object.assign(this, opts)
34 this.ports = this.state.ports
35 // tracks unbounded ports that we have
36 this._unboundPorts = new Set()
37 this._saturationPromise = new Promise((resolve, reject) => {
38 this._saturationResolve = resolve
39 })
40 this._oldestMessagePromise = new Promise((resolve, reject) => {
41 this._oldestMessageResolve = resolve
42 })
43 }
44
45 /**
46 * binds a port to a name
47 * @param {Object} port - the port to bind
48 * @param {String} name - the name of the port
49 */
50 async bind (name, port) {
51 if (this.isBound(port)) {
52 throw new Error('cannot bind a port that is already bound')
53 } else if (this.ports[name]) {
54 throw new Error('cannot bind port to a name that is alread bound')
55 } else {
56 this._unboundPorts.delete(port)
57
58 port.messages.forEach(message => {
59 message._fromPort = port
60 message.fromName = name
61 })
62
63 // save the port instance
64 this.ports[name] = port
65
66 // update the dest port
67 const destPort = await this.hypervisor.getDestPort(port)
68 destPort.destName = name
69 destPort.destId = this.id
70 delete destPort.destPort
71 }
72 }
73
74 /**
75 * unbinds a port given its name
76 * @param {string} name
77 * @returns {Promise}
78 */
79 async unbind (name) {
80 const port = this.ports[name]
81 delete this.ports[name]
82 this._unboundPorts.add(port)
83 this.hypervisor.addNodeToCheck(this.id)
84
85 // update the destination port
86 const destPort = await this.hypervisor.getDestPort(port)
87 delete destPort.destName
88 delete destPort.destId
89 destPort.destPort = port
90 return port
91 }
92
93 /**
94 * delete an port given the name it is bound to
95 * @param {string} name
96 */
97 delete (name) {
98 const port = this.ports[name]
99 this._delete(name)
100 return this.kernel.send(port, new DeleteMessage())
101 }
102
103 _delete (name) {
104 this.hypervisor.addNodeToCheck(this.id)
105 delete this.ports[name]
106 }
107
108 /**
109 * clears any unbounded ports referances
110 */
111 clearUnboundedPorts () {
112 const waits = []
113 this._unboundPorts.forEach(port => {
114 waits.push(this.kernel.send(port, new DeleteMessage()))
115 })
116 this._unboundPorts.clear()
117 return Promise.all(waits)
118 }
119
120 /**
121 * check if a port object is still valid
122 * @param {Object} port
123 * @return {Boolean}
124 */
125 isBound (port) {
126 return !this._unboundPorts.has(port)
127 }
128
129 /**
130 * queues a message on a port
131 * @param {Message} message
132 */
133 queue (name, message) {
134 const port = this.ports[name]
135
136 message._fromPort = port
137 message.fromName = name
138
139 if (port.messages.push(message) === 1) {
140 if (this._isSaturated()) {
141 this._saturationResolve()
142 this._saturationPromise = new Promise((resolve, reject) => {
143 this._saturationResolve = resolve
144 })
145 }
146
147 if (message._fromTicks < this._messageTickThreshold) {
148 this._oldestMessageResolve(message)
149 this._oldestMessagePromise = new Promise((resolve, reject) => {
150 this._oldestMessageResolve = resolve
151 })
152 this._messageTickThreshold = Infinity
153 }
154 }
155 }
156
157 /**
158 * gets a port given it's name
159 * @param {String} name
160 * @return {Object}
161 */
162 get (name) {
163 return this.ports[name]
164 }
165
166 /**
167 * creates a channel returns the created ports in an Array
168 * @returns {array}
169 */
170 createChannel () {
171 const port1 = {
172 messages: []
173 }
174
175 const port2 = {
176 messages: [],
177 destPort: port1
178 }
179
180 port1.destPort = port2
181 this._unboundPorts.add(port1)
182 this._unboundPorts.add(port2)
183 return [port1, port2]
184 }
185
186 // find and returns the next message
187 _peekNextMessage () {
188 const names = Object.keys(this.ports)
189 if (names.length) {
190 const portName = names.reduce(messageArbiter.bind(this))
191 const port = this.ports[portName]
192 return port.messages[0]
193 }
194 }
195
196 /**
197 * Waits for the the next message if any
198 * @returns {Promise}
199 */
200 async getNextMessage () {
201 let message = this._peekNextMessage()
202 let saturated = this._isSaturated()
203 let oldestTime = this.hypervisor.scheduler.oldest()
204
205 while (!saturated && // end if there are messages on all the ports
206 // end if we have a message older then slowest containers
207 !((message && oldestTime >= message._fromTicks) ||
208 // end if there are no messages and this container is the oldest contaner
209 (!message && oldestTime === this.kernel.ticks))) {
210 const ticksToWait = message ? message._fromTicks : this.kernel.ticks
211
212 await Promise.race([
213 this.hypervisor.scheduler.wait(ticksToWait, this.id).then(() => {
214 message = this._peekNextMessage()
215 }),
216 this._olderMessage(message).then(m => {
217 message = m
218 }),
219 this._whenSaturated().then(() => {
220 saturated = true
221 message = this._peekNextMessage()
222 })
223 ])
224
225 oldestTime = this.hypervisor.scheduler.oldest()
226 }
227
228 return message
229 }
230
231 // tests wether or not all the ports have a message
232 _isSaturated () {
233 const keys = Object.keys(this.ports)
234 return keys.length ? keys.every(name => this.ports[name].messages.length) : 0
235 }
236
237 // returns a promise that resolve when the ports are saturated
238 _whenSaturated () {
239 return this._saturationPromise
240 }
241
242 // returns a promise that resolve when a message older then the given message
243 // is recived
244 _olderMessage (message) {
245 this._messageTickThreshold = message ? message._fromTicks : -1
246 return this._oldestMessagePromise
247 }
248
249 removeSentPorts (message) {
250 message.ports.forEach(port => this._unboundPorts.delete(port))
251 }
252
253 addReceivedPorts (message) {
254 message.ports.forEach(port => this._unboundPorts.add(port))
255 }
256
257 checkSendingPorts (message) {
258 for (const port of message.ports) {
259 if (this.isBound(port)) {
260 throw new Error('message must not contain bound ports')
261 }
262 }
263 }
264}
265

Built with git-ssb-web