git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 3caa963721b6de8700ae2769edf1ce8f78bc0718

Files: 3caa963721b6de8700ae2769edf1ce8f78bc0718 / portManager.js

2489 bytesRaw
1const Port = require('./port.js')
2const ENTRY = Symbol('entry')
3
4// decides which message to go firts
5function messageArbiter (pairA, pairB) {
6 const a = pairA[1].peek()
7 const b = pairB[1].peek()
8
9 if (!a) {
10 return pairB
11 } else if (!b) {
12 return pairA
13 }
14
15 const aGasPrice = a.resources.gasPrice
16 const bGasPrice = b.resources.gasPrice
17 if (a.ticks !== b.ticks) {
18 return a.ticks < b.ticks ? pairA : pairB
19 } else if (aGasPrice === bGasPrice) {
20 return a.hash() > b.hash() ? pairA : pairB
21 } else {
22 return aGasPrice > bGasPrice ? pairA : pairB
23 }
24}
25
26module.exports = class PortManager {
27 constructor (opts) {
28 Object.assign(this, opts)
29 this._portMap = new Map()
30 }
31
32 async start () {
33 // map ports to thier id's
34 let ports = Object.keys(this.ports).map(name => {
35 const port = this.ports[name]
36 this._mapPort(name, port)
37 })
38
39 // create the parent port
40 await Promise.all(ports)
41 const id = await this.hypervisor.generateID(this.parentPort)
42 this._portMap.set(id, new Port(ENTRY))
43 }
44
45 async _mapPort (name, port) {
46 const id = await this.hypervisor.generateID(port)
47 port = new Port(name)
48 this._portMap.set(id, port)
49 }
50
51 queue (message) {
52 this._portMap.get(message.fromPort).queue(message)
53 }
54
55 set (name, port) {
56 this.ports[name] = port
57 return this._mapPort(name, port)
58 }
59
60 async get (port) {
61 const id = await this.hypervisor.generateID(port)
62 return this._portMap.get(id)
63 }
64
65 getRef (key) {
66 return this.ports[key]
67 }
68
69 // waits till all ports have reached a threshold tick count
70 async wait (threshold, fromPort) {
71 // console.log('wait', threshold, 'id', this.entryPort)
72 // find the ports that have a smaller tick count then the threshold tick count
73 const unkownPorts = [...this._portMap].filter(([id, port]) => {
74 return (port.hasSent || port.name === ENTRY) &&
75 port.ticks < threshold &&
76 fromPort !== port
77 })
78
79 const promises = unkownPorts.map(async ([id, port]) => {
80 const portObj = port.name === ENTRY ? this.parentPort : this.ports[port.name]
81 // update the port's tick count
82 port.ticks = await this.hypervisor.wait(portObj, threshold, this.entryPort)
83 })
84 return Promise.all(promises)
85 }
86
87 async getNextMessage () {
88 await this.wait(this.kernel.ticks, this.entryPort)
89 const portMap = [...this._portMap].reduce(messageArbiter)
90 if (portMap) {
91 return portMap[1].shift()
92 }
93 }
94}
95

Built with git-ssb-web