1 | 'use strict';
|
2 | const Emittery = require('emittery');
|
3 |
|
4 | const emitter = new Emittery();
|
5 | process.on('message', message => {
|
6 | if (!message.ava) {
|
7 | return;
|
8 | }
|
9 |
|
10 | switch (message.ava.type) {
|
11 | case 'options':
|
12 | emitter.emit('options', message.ava.options);
|
13 | break;
|
14 | case 'peer-failed':
|
15 | emitter.emit('peerFailed');
|
16 | break;
|
17 | case 'pong':
|
18 | emitter.emit('pong');
|
19 | break;
|
20 | default:
|
21 | break;
|
22 | }
|
23 | });
|
24 |
|
25 | exports.options = emitter.once('options');
|
26 | exports.peerFailed = emitter.once('peerFailed');
|
27 |
|
28 | function send(evt) {
|
29 | if (process.connected) {
|
30 | process.send({ava: evt});
|
31 | }
|
32 | }
|
33 |
|
34 | exports.send = send;
|
35 |
|
36 | function unref() {
|
37 | process.channel.unref();
|
38 | }
|
39 |
|
40 | exports.unref = unref;
|
41 |
|
42 | let pendingPings = Promise.resolve();
|
43 | async function flush() {
|
44 | process.channel.ref();
|
45 | const promise = pendingPings.then(async () => {
|
46 | send({type: 'ping'});
|
47 | await emitter.once('pong');
|
48 | if (promise === pendingPings) {
|
49 | unref();
|
50 | }
|
51 | });
|
52 | pendingPings = promise;
|
53 | await promise;
|
54 | }
|
55 |
|
56 | exports.flush = flush;
|