git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: fb80c5e51c634a7cd505d71b34160b19f451cd16

Files: fb80c5e51c634a7cd505d71b34160b19f451cd16 / portManager.js

1676 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.state = state
9 this.sentMessage = []
10 this.Kernel = KernelContructor
11 // set up the parent port
12 const parentPort = new Port()
13 parentPort.on('message', message => {
14 this.emit('message', message)
15 })
16 // create the cache
17 this.cache = new Map()
18 this.cache.set(common.PARENT, parentPort)
19 }
20
21 async get (name) {
22 let port = this.cache.get(name)
23 if (!port) {
24 port = new Port()
25 port.on('message', message => {
26 this.emit('message', message)
27 })
28 // create destination kernel
29 const state = await this.state.get(name)
30 const destKernel = new this.Kernel({
31 state: state,
32 parent: port
33 })
34
35 // shutdown the kernel when it is done doing it work
36 destKernel.on('idle', () => {
37 destKernel.shutdown()
38 this.cache.delete(name)
39 })
40
41 // find and connect the destination port
42 const destPort = await destKernel.ports.get(common.PARENT)
43 port.connect(destPort)
44 this.cache.set(name, port)
45 }
46 return port
47 }
48
49 // dequeues the first message that is waiting on a port
50 async dequeue () {
51 // clear the outbox
52 this.sentMessage = []
53 for (let port in this.cache) {
54 const message = port.dequeue()
55 if (message) {
56 return message
57 }
58 }
59 }
60
61 close () {
62 for (let port in this.cache) {
63 port.emit('close')
64 }
65 this.cache.clear()
66 }
67}
68

Built with git-ssb-web