Unitech / pm2

Node.js Production Process Manager with a built-in Load Balancer.
https://pm2.keymetrics.io/docs/usage/quick-start/
Other
41.59k stars 2.62k forks source link

the types and behavior for sendDataToProcessId is confused #4888

Open leanllg opened 4 years ago

leanllg commented 4 years ago

What's going wrong?

The type for sendDataToProcessId is function sendDataToProcessId(proc_id: number, packet: object, cb: ErrResultCallback): void. However, from the doc and the test code for sendDataToProcessId, we can use sendDataToProcessId as below:

pm2.sendDataToProcessId({
  id: proc1.pm2_env.pm_id,
  topic : 'process:msg',
  data : {
    some : 'data',
    hello : true
  }
}, function(err, res) {
});

So the typescript definition should add overloads support for sendDataToProcessId function. And the behavior of these two function is also defferent, pm2.sendDataToProcessId(packet, cb) will send message to current process, pm2.sendDataToProcessId(id, packet, cb) won't. For example:

// we start this program use pm2 --no-daemon -i 2
function a() {
  pm2.connect(() => {
    pm2.list((err, list) => {
      for (const proc of list) {
        // change to any here, otherwise, it will result in typescript error
        (pm2 as any).sendDataToProcessId(
          {
            type: 'type',
            topic: 'topic',
            data: {
              hello: 'hello',
            },
            id: proc.pm_id,
          },
          function (error: unknown) {
            console.log(error);
            console.log('message sent');
          }
        );
      }
      pm2.disconnect();
    });
  });
}

process.on('message', function (packet) {
  if (packet.type === 'type') {
    console.log('emit message', packet.data, packet.type);
  }
});

// when run a() in process 1.
process 1: emit message
process 2: emit message

// when we start program in this one
function b() {
  pm2.connect(() => {
    pm2.list((err, list) => {
      for (const proc of list) {
         pm2.sendDataToProcessId(
            id: proc.pm_id,
          {
            type: 'type',
            topic: 'topic',
            data: {
              hello: 'hello',
            }
          },
          function (error: unknown) {
            console.log(error);
            console.log('message sent');
          }
        );
      }
      pm2.disconnect();
    });
  });
}

process.on('message', function (packet) {
  if (packet.type === 'type') {
    console.log('emit message', packet.data, packet.type); // it will only trigger twice.
  }
});

// when run a() in process 1.
process 1: // no console
process 2: emit message

How could we reproduce this issue?

As the example show above

Supporting information

pm2d version         : 4.5.0
node version         : 12.19.0
Tobjoern commented 3 years ago

I just stumbled into this issue as well, I'd appreciate someone looking into this.