Files: 4b635551d20b7713c297b8e2e30ac37c8b830837 / portManager.js
2367 bytesRaw
1 | const Port = require('./port.js') |
2 | const PARENT = Symbol('parent') |
3 | |
4 | // decides which message to go firts |
5 | function 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 | |
26 | module.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 parentID = await this.hypervisor.generateID(this.parentPort) |
42 | this._portMap.set(parentID, new Port(PARENT)) |
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) { |
71 | // find the ports that have a smaller tick count then the threshold tick count |
72 | const unkownPorts = [...this._portMap].filter(([id, port]) => { |
73 | return (port.hasSent || port.name === PARENT) && port.ticks < threshold |
74 | }) |
75 | |
76 | const promises = unkownPorts.map(async ([id, port]) => { |
77 | const portObj = port.name === PARENT ? this.parentPort : this.ports[port.name] |
78 | // update the port's tick count |
79 | port.ticks = await this.hypervisor.wait(portObj, threshold) |
80 | }) |
81 | return Promise.all(promises) |
82 | } |
83 | |
84 | async getNextMessage () { |
85 | await this.wait(this.kernel.ticks) |
86 | const portMap = [...this._portMap].reduce(messageArbiter) |
87 | if (portMap) { |
88 | return portMap[1].shift() |
89 | } |
90 | } |
91 | } |
92 |
Built with git-ssb-web