-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsystem.js
More file actions
54 lines (48 loc) · 1.23 KB
/
system.js
File metadata and controls
54 lines (48 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict';
const actors = new Map();
class ActorSystem {
static register(actor) {
const ready = [];
const instances = [];
const queue = [];
actors.set(actor.name, { actor, ready, instances, queue });
}
static start(name, count = 1) {
require(`./actors/${name.toLowerCase()}.js`);
const record = actors.get(name);
if (record) {
const ActorClass = record.actor;
const { ready, instances } = record;
for (let i = 0; i < count; i++) {
const instance = new ActorClass();
ready.push(instance);
instances.push(instance);
}
}
}
static async stop(name) {
const record = actors.get(name);
if (record) {
const { instances } = record;
await Promise.all(instances.map((instance) => instance.exit()));
}
}
static async send(name, data) {
const record = actors.get(name);
if (record) {
const { ready, queue } = record;
const actor = ready.shift();
if (!actor) {
queue.push(data);
return;
}
await actor.message(data);
ready.push(actor);
if (queue.length > 0) {
const next = queue.shift();
this.send(name, next);
}
}
}
}
module.exports = ActorSystem;