graceful.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import {onAbortedSignal} from '../utils/abort-signal.js';
  2. import {sendAbort} from '../ipc/graceful.js';
  3. import {killOnTimeout} from './kill.js';
  4. // Validate the `gracefulCancel` option
  5. export const validateGracefulCancel = ({gracefulCancel, cancelSignal, ipc, serialization}) => {
  6. if (!gracefulCancel) {
  7. return;
  8. }
  9. if (cancelSignal === undefined) {
  10. throw new Error('The `cancelSignal` option must be defined when setting the `gracefulCancel` option.');
  11. }
  12. if (!ipc) {
  13. throw new Error('The `ipc` option cannot be false when setting the `gracefulCancel` option.');
  14. }
  15. if (serialization === 'json') {
  16. throw new Error('The `serialization` option cannot be \'json\' when setting the `gracefulCancel` option.');
  17. }
  18. };
  19. // Send abort reason to the subprocess when aborting the `cancelSignal` option and `gracefulCancel` is `true`
  20. export const throwOnGracefulCancel = ({
  21. subprocess,
  22. cancelSignal,
  23. gracefulCancel,
  24. forceKillAfterDelay,
  25. context,
  26. controller,
  27. }) => gracefulCancel
  28. ? [sendOnAbort({
  29. subprocess,
  30. cancelSignal,
  31. forceKillAfterDelay,
  32. context,
  33. controller,
  34. })]
  35. : [];
  36. const sendOnAbort = async ({subprocess, cancelSignal, forceKillAfterDelay, context, controller: {signal}}) => {
  37. await onAbortedSignal(cancelSignal, signal);
  38. const reason = getReason(cancelSignal);
  39. await sendAbort(subprocess, reason);
  40. killOnTimeout({
  41. kill: subprocess.kill,
  42. forceKillAfterDelay,
  43. context,
  44. controllerSignal: signal,
  45. });
  46. context.terminationReason ??= 'gracefulCancel';
  47. throw cancelSignal.reason;
  48. };
  49. // The default `reason` is a DOMException, which is not serializable with V8
  50. // See https://github.com/nodejs/node/issues/53225
  51. const getReason = ({reason}) => {
  52. if (!(reason instanceof DOMException)) {
  53. return reason;
  54. }
  55. const error = new Error(reason.message);
  56. Object.defineProperty(error, 'stack', {
  57. value: reason.stack,
  58. enumerable: false,
  59. configurable: true,
  60. writable: true,
  61. });
  62. return error;
  63. };