gajus / turbowatch

Extremely fast file change detector and task orchestrator for Node.js.
Other
938 stars 23 forks source link

Provide greater abstraction for graceful shutdown #10

Closed gajus closed 1 year ago

gajus commented 1 year ago

The current implementation relies on user providing an abort signal and triggering that signal on SIGINT.

import { watch } from 'turbowatch';

+const abortController = new AbortController();

void watch({
+  abortSignal: abortController.signal,
  project: __dirname,
  triggers: [
    {
      expression: ['match', '*.ts', 'basename'],
      name: 'build',
      onChange: async ({ spawn }) => {
        await spawn`tsc`;
      },
      onTeardown: async () => {
        await spawn`rm -fr ./dist`;
      },
    },
  ],
});

+process.on('SIGINT', () => {
+  abortController.abort();
+});

While this works for the vast majority of use cases, it introduces a fair bit of boilerplate code.

It would be nice to provide an abstraction that reduces the boilerplate code. This could be as simple as:

import {
  watch,
+  gracefulAbortSignal,
} from 'turbowatch';

void watch({
+  abortSignal: gracefulAbortSignal(),
  project: __dirname,
  triggers: [
    {
      expression: ['match', '*.ts', 'basename'],
      name: 'build',
      onChange: async ({ spawn }) => {
        await spawn`tsc`;
      },
      onTeardown: async () => {
        await spawn`rm -fr ./dist`;
      },
    },
  ],
});

We could also take a step further and just provide a fallback logic if no abortSignal is provided.

Pros: Keeps the API simple Cons: Introduces an element of surprise if Turbowatch is used programmatically

gajus commented 1 year ago

Added https://github.com/gajus/turbowatch/releases/tag/v1.9.0