git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: c2c35a4216304056cc0acac26cf1f3791353f429

Files: c2c35a4216304056cc0acac26cf1f3791353f429 / portManager.js

1839 bytesRaw
1const EventEmitter = require('events')
2const Port = require('./port.js')
3const common = require('./common.js')
4
5module.exports = class PortManager extends EventEmitter {
6 constructor (state, destParentPort, KernelContructor) {
7 super()
8 this._queue = []
9 this.state = state
10 this.Kernel = KernelContructor
11 // set up the parent port
12 const parentPort = new Port(common.PARENT)
13 parentPort.on('message', message => {
14 this._recieveMessage(message)
15 })
16
17 // create the cache
18 this.cache = new Map()
19 this.cache.set(common.PARENT, parentPort)
20 }
21
22 _recieveMessage (message) {
23 const index = this._queue.push(message) - 1
24 this.emit('message', index)
25 }
26
27 async get (name) {
28 let port = this.cache.get(name)
29 if (!port) {
30 port = new Port(name)
31 port.on('message', message => {
32 this._recieveMessage(message)
33 })
34 // create destination kernel
35 const state = await this.state.get(name)
36 const destKernel = new this.Kernel({
37 state: state,
38 parentPort: port
39 })
40
41 // shutdown the kernel when it is done doing it work
42 destKernel.on('idle', () => {
43 destKernel.shutdown()
44 this.cache.delete(name)
45 })
46
47 // find and connect the destination port
48 const destPort = await destKernel.ports.get(common.PARENT)
49 port.connect(destPort)
50 this.cache.set(name, port)
51 }
52 return port
53 }
54
55 async peek (index = 0) {
56 return this._queue[index]
57 }
58
59 remove (index) {
60 return this._queue.splice(index, index + 1)
61 }
62
63 async send (message) {
64 let portName = message.nextPort()
65 const port = await this.get(portName)
66 port.send(message)
67 return message.result()
68 }
69
70 close () {
71 for (let port in this.cache) {
72 port.emit('close')
73 }
74 this.cache.clear()
75 }
76}
77

Built with git-ssb-web