@financial-times/health-check

中文文档
4.0.0发布于 2024/05/20MITCommonJS近 30 天下载 6183

Build health check functions which comply with the FT health check standard

原始使用文档
文档目录15 节
  1. Table Of Contents
  2. Usage
  3. Requirements
  4. API Documentation
  5. new HealthCheck( [options] )
  6. new HealthCheck.Check( [options] )
  7. Options
  8. Health Check Configurations
  9. Examples
  10. Node Fetch
  11. Contributing
  12. Publishing
  13. Migration guide
  14. Contact
  15. Licence

Node Health Check NPM version MIT licensed

Build health check functions which comply with the FT health check standard.

Table Of Contents

Usage

Requirements

Running the Health Check module requires Node.js and npm. You can install with:

npm install @financial-times/health-check

API Documentation

This library makes use of promises – familiarity is assumed in the rest of the API documentation. You'll also need to require the module with:

const HealthCheck = require('@financial-times/health-check');

new HealthCheck( [options] )

This function returns a new health check object. You can configure the health checks with an options object if you need to override any defaults.

const health = new HealthCheck({
    checks: [
        // ...
    ]
});

The given checks start polling immediately at the intervals that you specify. The returned instance has several methods for reading this data.

health.checks()

This returns a health check function that's compatible with the Express Web Service module. The returned function returns a promise which resolves to a JSON-friendly copy of the health check data.

Assuming you've already included Express and Express Web Service:

app.use(expressWebService({
    healthCheck: health.checks()
}));

health.gtg()

This returns a good-to-go function that's compatible with the Express Web Service module. The returned function returns a promise which resolves to either true or false.

false will be the resolved value if any of the health checks with severity 1 are failing.

Assuming you've already included Express and Express Web Service:

app.use(expressWebService({
    goodToGoTest: health.gtg()
}));

health.toJSON()

Get the health check output as an array that's safe for converting to JSON. You can use this if you don't intend on using the Express Web Service module.

health.stop()

This stops all of the checks from running. This is useful if the health checks are keeping the Node.js process open and you need it to close. E.g. after integration tests.

health.stop();

new HealthCheck.Check( [options] )

This class is used to create custom health checks. You'll need to extend this class in order to use it, and can pass instances directly into HealthCheck when you instantiate it. E.g.

class MyHealthCheck extends HealthCheck.Check {

    constructor(options) {
        super(options);
    }

    // Must return a promise
    run() {
        return new Promise(resolve => {
            // Must set these properties
            this.ok = true;
            this.checkOutput = '';
            this.lastUpdated = new Date();
            resolve();
        });
    }

}

See examples for more information, or look through lib/check for more classes which already extend the base Check class.

Options

The Health Check module can be configured with a variety of options, passed in as an object to the HealthCheck constructor. The available options are as follows:

Health Check Configurations

Each health check can be configured as an object. These follow the FT health check standard, which has more information, and there are examples available to help you out. No matter what type of check you're adding, there are some common required properties:

  • type: The type of the check. One of cpu, disk-space, memory, ping-url, tcp-ip. Additional configurations required by these types are documented below
  • businessImpact: The business impact of the health check as a string
  • id: The unique ID of the health check as a string. Must use only lowercase alphanumeric characters and hyphens.
  • name: The name of the health check as a string.
  • panicGuide: The panic guide for the health check as a string.
  • technicalSummary: The technical summary for the health check as a string.

There are also some common optional properties:

  • severity: The severity level of the health check if it is failing. Must be one of 1 (high), 2 (medium), 3 (low)
  • interval: The number of milliseconds to wait between checks. Defaults to 30000 (30 seconds)

Different types of check may have additional config properties. These are documented below.

Check Type: CPU

The cpu type accepts some additional configuration:

  • threshold: The maximum CPU usage (as a percentage) that is allowed before the check will fail. Defaults to 50

Check Type: Disk Space

The disk-space type accepts some additional configuration:

  • threshold: The maximum disk space usage (as a percentage) that is allowed before the check will fail. Defaults to 75

Check Type: Memory

The memory type accepts some additional configuration:

  • threshold: The maximum memory usage (as a percentage) that is allowed before the check will fail. Defaults to 75

Check Type: Ping URL

The ping-url type requires some additional configuration:

  • url: The URL that the check should ping. This accepts a string or a function that returns a string
  • method: The HTTP method to use when pinging the URL. Defaults to "HEAD"
  • headers: The HTTP headers to be sent with the request. This accepts an object with key value pair. Defaults to empty object

Check Type: TCP/IP

The tcp-ip type requires some additional configuration:

  • host: The hostname that the check should ping
  • port: The TCP port to use when pinging the hostname. Defaults to 80

See examples for sample usage.

Examples

You can find example implementations of health checks in the examples folder of this repo:

  • Basic: create and run some simple health checks:

    node examples/basic
    

    Source File

  • Custom: create and run some custom health checks:

    node examples/custom
    

    Source File

Node Fetch

If a project is using node-fetch as a npm dependency, there is a potential gotcha to be aware of, as without having a response for a custom healthcheck in the body, it will introduce a memory leak that will build up over time and crash the app due to not having a response in place.

There is a work-around this is to implement. This would be to either put in a response.json or a response.text in the custom healthcheck like below:

const fetch = require('node-fetch');

class MyHealthCheck extends HealthCheck.Check {
    async run() {
        try {
            const response = await fetch('https://some.api-address.com', {
                method: 'GET',
                headers: {
                    'apikey': 'your api key here'
                }
            });

            if (response.status !== 200) {
                throw new Error('Unable to access API');
            }

            if (response.status === 200) {
                this.ok = true;
                this.checkOutput = 'OK';
                response.text(); // read the body so it can be garbage collected
            }

        } catch (error) {
            this.ok = false;
            this.checkOutput = error.toString();
        }
    }
}

Contributing

This module has a full suite of unit tests, and is verified with ESLint. You can use the following commands to check your code before opening a pull request.

make verify  # verify JavaScript code with ESLint
make test    # run the unit tests and check coverage

Publishing

New versions of the module are published automatically by CI when a new tag is created matching the pattern /v.*/.

Migration guide

StateMajor VersionLast Minor ReleaseMigration guide
✨ active4N/Amigrate to v4
╳ deprecated3N/Amigrate to v3
╳ deprecated2.1N/Amigrate to v2
╳ deprecated11.11N/A

Contact

If you have any questions or comments about this module, or need help using it, please either raise an issue, visit #origami-support or email Origami Support.

Licence

This software is published by the Financial Times under the MIT licence.

版本与发布记录

@financial-times/health-check 共发布 40 个版本,首次发布于 2017/04/24;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.0.0latest2024/05/202 年前
3.0.02024/01/272 年前
2.1.102022/03/024 年前
2.1.92021/03/045 年前
2.1.82021/02/025 年前
2.1.72021/01/285 年前

关于 @financial-times/health-check 的常见问题

@financial-times/health-check 是什么?

Build health check functions which comply with the FT health check standard

如何安装 @financial-times/health-check?

在项目目录运行 npm install @financial-times/health-check,或使用 pnpm add / yarn add / bun add。

@financial-times/health-check 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/financial-times__health-check 是否存在。

@financial-times/health-check 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@financial-times/health-check 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@financial-times/health-check 可以商用吗?

@financial-times/health-check 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@financial-times/health-check 的下载量有多少?

根据 npm 官方下载统计,@financial-times/health-check 在 2026/10/15 – 2026/11/13 这 30 天内被下载 6,183 次,日均约 206 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@financial-times/health-check 还在维护吗?

最新版本 4.0.0 发布于 2024/05/20(2 年前);至今共发布 40 个版本,其中过去 12 个月发布了 0 个;首次发布于 2017/04/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。