git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 48df42c8ab634c0d9fc7597e52106352878124fa

Files: 48df42c8ab634c0d9fc7597e52106352878124fa / portManager.js

1696 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 console.log(name)
29 let port = this.cache.get(name)
30 if (!port) {
31 port = new Port(name)
32 port.on('message', message => {
33 this._recieveMessage(message)
34 })
35 // create destination kernel
36 const state = await this.state.get(name)
37 const destKernel = new this.Kernel({
38 state: state,
39 parent: port
40 })
41
42 // shutdown the kernel when it is done doing it work
43 destKernel.on('idle', () => {
44 destKernel.shutdown()
45 this.cache.delete(name)
46 })
47
48 // find and connect the destination port
49 const destPort = await destKernel.ports.get(common.PARENT)
50 port.connect(destPort)
51 this.cache.set(name, port)
52 }
53 return port
54 }
55
56 async peek (index = 0) {
57 return this._queue[index]
58 }
59
60 remove (index) {
61 return this._queue.splice(index, index + 1)
62 }
63
64 close () {
65 for (let port in this.cache) {
66 port.emit('close')
67 }
68 this.cache.clear()
69 }
70}
71

Built with git-ssb-web