GithubHelp home page GithubHelp logo

gritzkoo / nodejs-health-checker Goto Github PK

View Code? Open in Web Editor NEW
43.0 4.0 12.0 1016 KB

This is a Node package that allows you to track the health of your application providing readiness and liveness functionalities.

Home Page: https://www.npmjs.com/package/nodejs-health-checker

License: MIT License

JavaScript 2.15% TypeScript 97.31% Dockerfile 0.54%
nodejs nodemodule npm-package health-check healthcheck typescript node-typescript hacktoberfest hacktoberfest2020 liveness-probe

nodejs-health-checker's Introduction

nodejs-health-checker

npm
npm version test Coverage Status License Status Issues Status Tag Status Languages Status Repo Size Status


Contributors

contributors

Made with contributors-img.


This is a Node package that allows you to track the health of your application, providing two ways of checking:

Simple: will respond to a JSON as below and that allows you to check if your application is online and responding without checking any kind of integration.

{
  "status": "fully functional"
}

Detailed: will respond a JSON as below and that allows you to check if your application is up and running and check if all of your integrations informed in the configuration list is up and running.

{
    "name": "My node application",
    "version": "my version",
    "status": true,
    "date": "2020-09-18T15:29:41.616Z",
    "duration": 0.523,
    "integrations": [
        {
            "name": "redis integration",
            "kind": "Redis DB integration",
            "status": true,
            "response_time": 0.044,
            "url": "redis:6379"
        },
        {
            "name": "My memcache integration",
            "kind": "Memcached integraton",
            "status": true,
            "response_time": 0.038,
            "url": "memcache:11211"
        },
        {
            "name": "my web api integration",
            "kind": "Web integrated API",
            "status": true,
            "response_time": 0.511,
            "url": "https://github.com/status"
        },
        {
            "name": "my dynamo",
            "kind": "AWS Dynamo DB",
            "status": true,
            "response_time": 0.004,
            "url": "http://localhost:8000",
        }
    ]
}

How to install

npm i nodejs-health-checker

Available integrations

  • Redis
  • Memcached
  • Web integration (https)
  • AWS DynamoDB
  • Sequelize (authored by @MikeG96)
  • Custom integration support (authored by @youngpayters)

How to use

Example using Nodejs + Express

import express from "express";
import {
  HealthcheckerDetailedCheck,
  HealthcheckerSimpleCheck
} from "./healthchecker/healthchecker";
import { Dialects, HealthTypes } from "./interfaces/types";

const server = express();

server.get("/health-check/liveness", (_, res) => {
  res.send(HealthcheckerSimpleCheck());
});

server.get("/health-check/readiness", async (_, res) => {
  res.send(
    await HealthcheckerDetailedCheck({
      name: "My node application",
      version: "my version",
      // here you will inform all of your external dependencies
      // that your application must be checked to keep healthy
      // available integration types: [
      //   HealthTypes.Redis,
      //   HealthTypes.Memcached,
      //   HealthTypes.Web
      //   HealthTypes.Custom
      // ]
      integrations: [
        {
          type: HealthTypes.Redis,
          name: "redis integration",
          host: "redis",
        },
        {
          type: HealthTypes.Memcached,
          name: "My memcache integration",
          host: "memcache:11211",
        },
        {
          type: HealthTypes.Web,
          name: "my web api integration",
          host: "https://github.com/status",
          headers: [{ key: "Accept", value: "application/json" }],
        },
        {
          type: HealthTypes.Dynamo,
          name: "my dynamo",
          host: "http://localhost",
          port: 8000,
          Aws: {
            region: "us-east-1",
            access_key_id: "",
            secret_access_key: "",
          },
        },
        {
          type: HealthTypes.Database,
          name: "my database",
          host: "localhost",
          dbPort: 5432,
          dbName: "postgres",
          dbUser: "postgres",
          dbPwd: "root",
          dbDialect: Dialects.postgres,
        },
        {
          type: HealthTypes.Custom,
          name: "my custom integration",
          host: "localhost",
          customCheckerFunction: () => { return { status: true, error: {} }},
        },
      ],
    })
  );
});

export default server;

And then, you could call these endpoints manually to see your application health, but, if you are using modern Kubernetes deployment, you can config your chart to check your application with the setup below. There is an Example on runkit too.

apiVersion: v1
kind: Pod
metadata:
  labels:
    test: liveness
  name: liveness-http
spec:
  containers:
  - name: liveness
    image: 'node' #your application image
    args:
    - /server
    livenessProbe:
      httpGet:
        path: /health-check/liveness
        port: 80
        httpHeaders:
        - name: Custom-Header
          value: Awesome
      initialDelaySeconds: 3
      periodSeconds: 3
  - name: readiness
    image: 'node' #your application image
    args:
    - /server
    readinessProbe:
      httpGet:
        path: /health-check/readiness
        port: 80
        httpHeaders:
        - name: Custom-Header
          value: Awesome
      initialDelaySeconds: 3
      periodSeconds: 3

Import using require

If your application needs to use the require instead of ECMAScript, you should import on this way:

const express = require('express');
const {
    HealthcheckerSimpleCheck,
    HealthcheckerDetailedCheck
} = require("nodejs-health-checker/dist/healthchecker/healthchecker");
const { HealthTypes } = require("nodejs-health-checker/dist/interfaces/types");
const server = express();
server.get('/', (req, res) => {
    res.json({ status: "I'm alive!" });
})
server.get('/health-check/liveness', (req, res) => {
    res.json(HealthcheckerSimpleCheck())
})
server.get('/health-check/readiness', async (req, res) => {
    let result = await HealthcheckerDetailedCheck({
        name: 'example',
        version: 'v1.0.0',
        integrations: [
            {
                type: HealthTypes.Web,
                name: 'A simple api integration check',
                host: 'https://github.com/status'
            }
        ]
    });
    res.json(result);
})
server.listen(3000, () => {
    console.log('server started at port 3000')
})

nodejs-health-checker's People

Contributors

danilolutz avatar dependabot[bot] avatar gritzkoo avatar joaomantovani avatar mikeg96 avatar visoft avatar youngpayters 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

Watchers

 avatar  avatar  avatar  avatar

nodejs-health-checker's Issues

avoid SELF_SIGNED_CERT_IN_CHAIN

Hi,
Great work guys!
But i have question:

Is any way to switch off checking certificates, without writing custom checker?

I have environment with self-signed certs which are not pass HealthTypes.Web

Best regards
Lukasz

Drivers dependencies as peerDependencies

First of all : thank you for your library.
We are using nodejs-health-checker to check that our application can connect to a Redis cluster and it's awesome.

Last week, we tried to update your library but we got into a node-gyp hell. From an unknown reason, we weren't able to download sqlite binaries so npm tried to build sqlite from sources.

As we don't use sqlite, it took us a while to track down our problem to nodejs-health-checker.

To prevent such problem and to lower application bundle size, why not switching dependencies to peerDependencies?
IMHO, if someone checks that its application can connect to Redis, it means that its application already has a dependency on Redis driver, isn't it?

Thank you.

Fix tar vulnerability [sqlite3]

When installing the new update, npm audit on my project.

The following vulnerability was found:

High            Arbitrary File Creation/Overwrite via insufficient symlink    
                  protection due to directory cache poisoning                   
                                                                                
  Package         tar                                                           
                                                                                
  Patched in      >=3.2.3 <4.0.0 || >=4.4.15  <5.0.0 || >=5.0.7 <6.0.0 ||       
                  >=6.1.2                                                       
                                                                                
  Dependency of   nodejs-health-checker                                         
                                                                                
  Path            nodejs-health-checker > sqlite3 > node-gyp > tar              
                                                                                
  More info       https://npmjs.com/advisories/1771                             
                                                                                

The version of package.json is different from github release

The releases on github page:
image

The package version on package.json
image

There is an example of working pipeline:
https://github.com/penseapp/useLocalStorage/blob/master/.github/workflows/deploy.yml

This action will bump on package.json

      - name: "Automated Version Bump"
        uses: "phips28/gh-action-bump-version@master"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          skip-tag: "true"

and this action will bump on github page:

      - name: release on Github
        uses: rymndhng/release-on-push-action@master
        with:
          bump_version_scheme: patch

Pckg Import

Are you sure nodejs-health-checker pkg can be normally imported from another space than './' ?

Feature request: support ioredis

It would be great if you could also support ioredis, which is a very popular redis client. ideally, when supporting it, you could also accept an existing client.

Import Issue

import {
HealthcheckerDetailedCheck,
HealthcheckerSimpleCheck
} from "./healthchecker/healthchecker";
Is this the correct way of importing a node_module in the project because I am facing error while doing it

Can't add password redis

i connect redis is okie but when usenodejs-health-checker for check integration i don't see where to put password
and rep always return false

Upgrade DynamoDB SDK

Hi, Thank you for your work on this project.

I've noticed that while using we get an alert for an old dependency warning, and I was wondering if there was any chance of it getting updated or if that would cause too much trouble/issues.

"@aws-sdk/client-dynamodb": "^1.0.0-rc.5" current version is 3.131.0

Make dependencies more modular

We are currently looking at adding health-checks to several NodeJS services at DataCamp. This library caught our eyes with its support for integrations. However, we found that adding it to a project is often heavier than it needs to be:

In the case of a very simple service with no integration (no database, no memcache, etc..), adding this package will add a lot of dependencies:

  • @aws-sdk/client-dynamodb
  • mariadb
  • memcached
  • mysql2
  • node-fetch
  • pg
  • pg-hstore
  • redis
  • sequelize
  • sqlite3

Moreover, sqlite3 needs to build upon install, a process that does slow down build, especially in CI.

We would like to contribute to this project and propose a few changes:

  • Define all dependencies as optional. Very much like sequelize, we would mark all dependencies optional. See their package.json.
  • Refactor integrations, so they can be imported separately. Currently, these imports force to have all integration dependencies installed, as they're all imported. Instead, we suggest to let users import these separately. This way only the required dependencies are imported.
  • More strict types: currently, all integrations are using IntegrationConfig. A single type for all means many fields need to be set as optional. Other fields, like host, are not always needed. We suggest to define a type per integration, leading to improved type safety and user experience.

That many changes will require a major, v2.0.0

From a user's perspective, it would look like this:

import express from "express";
import { HealthcheckerSimpleCheck } from "./simpleCheck";
import { HealthcheckerDetailedCheck } from "nodejs-health-checker/dist/detailedCheck";
import { redisCheck } from "nodejs-health-checker/dist/integrations/redis";
import { memcacheCheck } from "nodejs-health-checker/dist/integrations/memcache";
import { webCheck } from "nodejs-health-checker/dist/integrations/web";
import { dynamoCheck } from "nodejs-health-checker/dist/integrations/dynamo";
import { databaseCheck } from "nodejs-health-checker/dist/integrations/database";
import { customCheck } from "nodejs-health-checker/dist/integrations/custom";

const server = express();

server.get("/health-check/liveness", (_, res) => {
  res.send(HealthcheckerSimpleCheck());
});

server.get("/health-check/readiness", async (_, res) => {
  res.send(
    await HealthcheckerDetailedCheck({
      name: "My node application",
      version: "my version",
      integrations: [
        redisCheck({
          name: "redis integration",
          host: REDIS_HOST,
        }),
        memcacheCheck({
          name: "my memcache integration false",
          host: `${MEMCACHED_HOST}:11211`,
        }),
        webCheck({
          name: "my web api integration",
          url: WEB_HOST,
          headers: [{ key: "Accept", value: "application/json" }],
        }),
        dynamoCheck({
          name: "my dynamo",
          host: DYNAMO_HOST,
          port: 8000,
          Aws: {
            region: "us-east-1",
            access_key_id: "",
            secret_access_key: "",
          },
        }),
        databaseCheck({
          name: "my database",
          host: DATABASE_HOST,
          port: 5432,
          dbName: "postgres",
          dbUser: "postgres",
          dbPwd: "root",
          dbDialect: Dialects.postgres,
        }),
        customCheck({
          name: "my custom check",
          customCheckerFunction: async (): Promise<HTTPChecker> => {
            return new Promise((resolve, _) => {
              resolve({
                status: true,
                error: null,
              });
            });
          },
        }),
      ],
    })
  );
});

You can already get an idea of the implementation here. We're in the process of creating an official fork under the datacamp namespace and we will submit a PR once ready.

We would love to hear your thoughts about going in this direction.

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.