|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const threads = require('worker_threads'); |
| 4 | +const { Worker } = threads; |
| 5 | + |
| 6 | +const actors = new Map(); |
| 7 | + |
| 8 | +class MasterSystem { |
| 9 | + static start(name, count = 1) { |
| 10 | + if (!actors.has(name)) { |
| 11 | + const ready = []; |
| 12 | + const instances = []; |
| 13 | + const queue = []; |
| 14 | + actors.set(name, { ready, instances, queue }); |
| 15 | + } |
| 16 | + const { ready, instances } = actors.get(name); |
| 17 | + for (let i = 0; i < count; i++) { |
| 18 | + const actor = new Worker('./system.js'); |
| 19 | + console.log({ actor }); |
| 20 | + MasterSystem.subscribe(actor); |
| 21 | + ready.push(actor); |
| 22 | + instances.push(actor); |
| 23 | + actor.postMessage({ command: 'start', name }); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + static stop(name) { |
| 28 | + const record = actors.get(name); |
| 29 | + if (record) { |
| 30 | + const { instances } = record; |
| 31 | + for (const actor of instances) { |
| 32 | + actor.postMessage({ command: 'stop' }); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + static send(name, data) { |
| 38 | + const record = actors.get(name); |
| 39 | + if (record) { |
| 40 | + const { ready, queue } = record; |
| 41 | + const actor = ready.shift(); |
| 42 | + if (!actor) { |
| 43 | + queue.push(data); |
| 44 | + return; |
| 45 | + } |
| 46 | + actor.postMessage({ command: 'message', data }); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + static subscribe(actor) { |
| 51 | + actor.on('message', message => { |
| 52 | + const { command, name } = message; |
| 53 | + if (command === 'message') { |
| 54 | + const { data } = message; |
| 55 | + MasterSystem.send(name, data); |
| 56 | + return; |
| 57 | + } |
| 58 | + if (command === 'start') { |
| 59 | + const { count } = message; |
| 60 | + MasterSystem.start(name, count); |
| 61 | + return; |
| 62 | + } |
| 63 | + if (command === 'stop') { |
| 64 | + MasterSystem.stop(name); |
| 65 | + return; |
| 66 | + } |
| 67 | + if (command === 'ready') { |
| 68 | + const { id } = message; |
| 69 | + const record = actors.get(name); |
| 70 | + if (record) { |
| 71 | + const { ready, instances, queue } = record; |
| 72 | + for (const actor of instances) { |
| 73 | + if (actor.id === id) ready.push(actor); |
| 74 | + } |
| 75 | + if (queue.length > 0) { |
| 76 | + const next = queue.shift(); |
| 77 | + MasterSystem.send(name, next); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + }); |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +module.exports = MasterSystem; |
0 commit comments