Giter VIP home page Giter VIP logo

graceful's Introduction

build status code style styled with prettier made with lass license

Gracefully exit HTTP servers (Express/Koa/Fastify/etc), databases (Mongo/Mongoose), Redis clients, Bree job schedulers, and custom handlers.

Table of Contents

Install

npm:

npm install @ladjs/graceful

Usage

See the Express, Koa, Fastify, or Other code snippet examples and Instance Options below.

You can pass Instance Options to customize your graceful handler (e.g. if you have more than one server, or wish to close both a Redis connection and a server at the same time).

const Graceful = require('@ladjs/graceful');

//
// ...
//

//
// see Instance Options in the README below and examples for different projects (e.g. Koa or Express)
//
const graceful = new Graceful({
  //
  // http or net servers
  // (this supports Express/Koa/Fastify/etc)
  // (basically anything created with http.createServer or net.createServer)
  // <https://github.com/expressjs/express>
  // <https://github.com/koajs/koa>
  // <https://github.com/fastify/fastify>
  //
  servers: [],

  // bree clients
  // <https://github.com/breejs/bree>
  brees: [],

  // redis clients
  // <https://github.com/luin/ioredis>
  // <https://github.com/redis/node-redis>
  redisClients: [],

  // mongoose clients
  // <https://github.com/Automattic/mongoose>
  mongooses: [],

  // custom handlers to invoke upon shutdown
  customHandlers: [],

  // logger
  logger: console,

  // how long to wait in ms for exit to finish
  timeoutMs: 5000,

  // options to pass to `lil-http-terminator` to override defaults
  lilHttpTerminator: {},

  //
  // appends a `true` boolean value to a property of this name in the logger meta object
  // (this is useful for Cabin/Axe as it will prevent a log from being created in MongoDB)
  // (and instead of having a DB log created upon graceful exit, it will simply log to console)
  // (defer to the Forward Email codebase, specifically the logger helper)
  //
  // NOTE: if you set this to `false` then this will be ignored and no meta property will be populated
  //
  ignoreHook: 'ignore_hook',

  //
  // appends a `true` boolean value to a property of this name in the logger meta object
  // (this is useful for Cabin/Axe as it will prevent the meta object from being outputted to the logger)
  //
  hideMeta: 'hide_meta'
});

//
// NOTE: YOU MUST INVOKE `graceful.listen()` IN ORDER FOR THIS TO WORK!
//
graceful.listen();

Using this package will bind process event listeners when graceful.listen() is called:

  • process.on('warning') - will output via config.logger.warn
  • process.on('unhandledRejection') - bubbles up to uncaughtException (will output via config.logger.error and process.exit(1) (does not exit gracefully)
  • process.once('uncaughtException') - will output via config.logger.error and process.exit(1) (does not exit gracefully)
  • process.on('message') - support Windows (e.g. signals not available) and listen for message of shutdown and then exit gracefully
  • process.once('SIGTERM') - will exit gracefully
  • process.once('SIGHUP') - will exit gracefully
  • process.once('SIGINT') - will exit gracefully
  • process.once('SIGUSR2') - will exit gracefully (nodemon support)

This package also prevents multiple process/SIG events from triggering multiple graceful exits. Only one graceful exit can occur at a time.

For servers passed, we use lil-http-terminator under the hood. Default configuration options can be overridden by passing a lilHttpTerminator configuration object. See index.js for more insight.

Express

const express = require('express');
const Graceful = require('@ladjs/graceful');

const app = express();
const server = app.listen();
const graceful = new Graceful({ servers: [server] });
graceful.listen();

Koa

const Koa = require('koa');
const Graceful = require('@ladjs/graceful');

const app = new Koa();
const server = app.listen();
const graceful = new Graceful({ servers: [server] });
graceful.listen();

Fastify

const fastify = require('fastify');
const Graceful = require('@ladjs/graceful');

const app = fastify();
app.listen();

//
// NOTE: @ladjs/graceful is smart and detects `app.server` automatically
//
const graceful = new Graceful({ servers: [app] });
graceful.listen();

Other

This package works with any server created with http.createServer or net.createServer (Node's internal HTTP and Net packages).

Please defer to the test folder files for example usage.

Instance Options

Here is the full list of options and their defaults. See index.js for more insight if necessary.

Property Type Default Value Description
servers Array [] An array of HTTP or NET servers to gracefully close on exit
brees Array [] An array of Bree instances to gracefully exit
redisClients Array [] An array of Redis client instances to gracefully exit
mongooses Array [] An array of Mongoose connections to gracefully exit
customHandlers Array [] An array of functions (custom handlers) to invoke upon graceful exit
logger Object console This is the default logger. We recommend using Cabin instead of using console as your default logger. Set this value to false to disable logging entirely (uses noop function)
timeoutMs Number 5000 A number in milliseconds for how long to wait to gracefully exit
lilHttpTerminator Object {} An object of options to pass to lil-http-terminator to override default options provided
ignoreHook String or false Boolean "ignore_hook" Appends a true boolean property to a property with this value in logs, e.g. console.log('graceful exiting', { ignore_hook: true }); which is useful for preventing logs from being written to a database in hooks (this is meant for usage with Cabin and Axe and made for Forward Email). If you pass a false value then this property will not get populated.
hideMeta String or false Boolean "hide_meta" Appends a true boolean property to a property with this value in logs, e.g. console.log('graceful exiting', { hide_meta: true }); which is useful for preventing metadata object from being invoked as the second argument (this is meant for usage with Cabin and Axe and made for Forward Email). If you pass a false value then this property will not get populated.

Examples

You can refer Forward Email for more complex usage:

Additionally you can also refer to Lad usage:

You can also read more about Bree at https://github.com/breejs/bree.

Contributors

Name Website
Nick Baugh http://niftylettuce.com/
Felix Mosheev https://github.com/felixmosh
Nicholai Nissen https://nicholai.dev
Spencer Snyder https://spencersnyder.io

License

MIT © Nick Baugh

graceful's People

Contributors

felixmosh avatar nicholaiii avatar niftylettuce avatar shadowgate15 avatar titanism avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

graceful's Issues

Is it ok to expose `config` field in TS types?

My usage is a bit different, I'm creating an instance of Graceful and then pass it to services so they will register themself.

const graceful = new Graceful();

await createPendingPromotionsWorker({ db, graceful });
await createBulkChangePromotionsWorker({ db, graceful });
await createPriceQuotesWorker({ db, graceful });

graceful.listen();

Each one of these functions registers a shutdown function using graceful.config.servers / graceful.config.customHandlers.

Since config is a class property maybe it will be Ok to expose it as well in types?

If so, I'll prepare a PR for this :]

[feat] node-cron example

Describe the feature

It would be great if there could be documentation on node-cron support.

Checklist

  • I have searched through GitHub issues for similar issues.
  • I have completely read through the README and documentation.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organiszation’s settings page, under Installed GitHub Apps.

Feature request: Allow custom handlers

I want to close mysql connection, I'm using Knex as an abstraction above it.

Knex has destroy method.

Instead of saving a list of services which should be terminated (and each time add new one) it is better to allow to pass a method which can return a promise, and inside, it will do it's cleanup.

No hideMeta options in constructor Graceful

Describe the bug

Node.js version: v20.5.0

OS version: ubuntu 22.04

Description: There is no options for hideMeta when create new Graceful class????

Actual behavior

Object literal may only specify known properties, and 'hideMeta' does not exist in type 'GracefulOptions'.ts(2353)

Expected behavior

should be able to define hideMeta options in constructor

Code to reproduce

const graceful = new Graceful({
  logger: logger,
  servers: [server],
  customHandlers: [
    async () => {
      await mongoManager.disconnect();
      cronjobManager.stop();
      // this close all socket conneted to server and close server
      socketServer.close();
    },
  ],
  hideMeta : false,
});

Checklist

  • I have searched through GitHub issues for similar issues.
  • I have completely read through the README and documentation.
  • I have tested my code with the latest version of Node.js and this package and confirmed it is still not working.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.