A task register for facilitating graceful shutdown.
In the world of continuous deployment applications are being started and stopped more frequently than ever. Stopping a process is normally achived by sending a 'SIGINT' or 'SIGTERM' signal. Your node application can listen for this and perform a gracesful shutdown by stopping listeners and closing connections, ensuring that new http requests are rejected, but in-flight ones can complete. But what happens to asynchronous processes that are not part of a request/response workflow, e.g.
In truth there's nothing you can do to completely prevent this scenario.
SIGKILL will kill your application instantly and cannot be listened for, but since most deployment mechanism try
SIGTERM first and wait for a bit before invoking
SIGKILL why not be a good citizen and wait until the asynchronous operations are complete?
This is where
outstanding comes in handy. Outstanding assists with graceful shutdown of node.js applications by providing a way to track asynchronous tasks and block shutdown until they complete or an optional timeout expires.
const Outstanding =const outstanding = timeout: '5s'const signals = 'SIGINT' 'SIGTERM'signalsoutstanding
Sometimes you want to pass a function wrapped with outstanding to an executor.
var wrapped = outstandingasync
wrap an asynchronous task,
outstanding keeps track of the function name so you can at least log incomplete tasks on shutdown. If you use anonymous functions or prefer a custom label you can add an extra argument to both these functions, e.g.
Getting current tasks
outstanding.list(). This will return a map of tokens to task details, e.g.
Checking whether outstanding has been shutdown
outstanding.isClosed(). Returns false until
outstanding.shutdown(cb) has been invoked, after which it returns true
Low Level API
The simplest way to use
outstanding is to run or wrap tasks, but you can also use the api synchronously and asynchronously. In this case you need to explicitly use a label.
const token = tasklistif tokenelseconsole