reference.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // By default, Node.js keeps the subprocess alive while it has a `message` or `disconnect` listener.
  2. // We replicate the same logic for the events that we proxy.
  3. // This ensures the subprocess is kept alive while `getOneMessage()` and `getEachMessage()` are ongoing.
  4. // This is not a problem with `sendMessage()` since Node.js handles that method automatically.
  5. // We do not use `anyProcess.channel.ref()` since this would prevent the automatic `.channel.refCounted()` Node.js is doing.
  6. // We keep a reference to `anyProcess.channel` since it might be `null` while `getOneMessage()` or `getEachMessage()` is still processing debounced messages.
  7. // See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L547
  8. export const addReference = (channel, reference) => {
  9. if (reference) {
  10. addReferenceCount(channel);
  11. }
  12. };
  13. const addReferenceCount = channel => {
  14. channel.refCounted();
  15. };
  16. export const removeReference = (channel, reference) => {
  17. if (reference) {
  18. removeReferenceCount(channel);
  19. }
  20. };
  21. const removeReferenceCount = channel => {
  22. channel.unrefCounted();
  23. };
  24. // To proxy events, we setup some global listeners on the `message` and `disconnect` events.
  25. // Those should not keep the subprocess alive, so we remove the automatic counting that Node.js is doing.
  26. // See https://github.com/nodejs/node/blob/1b965270a9c273d4cf70e8808e9d28b9ada7844f/lib/child_process.js#L180
  27. export const undoAddedReferences = (channel, isSubprocess) => {
  28. if (isSubprocess) {
  29. removeReferenceCount(channel);
  30. removeReferenceCount(channel);
  31. }
  32. };
  33. // Reverse it during `disconnect`
  34. export const redoAddedReferences = (channel, isSubprocess) => {
  35. if (isSubprocess) {
  36. addReferenceCount(channel);
  37. addReferenceCount(channel);
  38. }
  39. };