├── .nvmrc ├── .npmrc ├── examples ├── .gitignore ├── hapi │ ├── package.json │ ├── config.js │ ├── README.md │ └── index.js ├── express │ ├── package.json │ ├── config.js │ ├── README.md │ └── index.js └── koa │ ├── package.json │ ├── config.js │ ├── README.md │ └── index.js ├── src ├── helper │ ├── index.ts │ └── make-request.ts ├── logger │ ├── index.ts │ ├── logger.spec.ts │ └── logger.ts ├── middleware │ ├── hapi │ │ ├── index.ts │ │ ├── prometheus-metrics.ts │ │ ├── prometheus-metrics.spec.ts │ │ ├── health-check.ts │ │ └── health-check.spec.ts │ ├── index.ts │ ├── express │ │ ├── index.ts │ │ ├── prometheus-metrics.ts │ │ ├── error-handler.ts │ │ ├── request-validator.ts │ │ ├── health-check.ts │ │ ├── request-validator.spec.ts │ │ ├── error-handler.spec.ts │ │ └── health-check.spec.ts │ └── koa │ │ ├── index.ts │ │ ├── prometheus-metrics-exporter.ts │ │ ├── error-handler.ts │ │ ├── request-validator.ts │ │ ├── health-check.ts │ │ ├── request-validator.spec.ts │ │ ├── error-handler.spec.ts │ │ ├── request-logger.ts │ │ └── health-check.spec.ts ├── index.ts ├── config │ ├── index.ts │ ├── environment.ts │ └── pino.ts ├── graceful-shutdown.ts ├── catch-errors.spec.ts └── catch-errors.ts ├── .prettierrc.json ├── .github ├── CODEOWNERS ├── PULL_REQUEST_TEMPLATE.md ├── ISSUE_TEMPLATE.md └── CONTRIBUTING.md ├── .npmignore ├── .gitignore ├── tslint.json ├── tsconfig.json ├── .circleci └── config.yml ├── package.json ├── LICENSE └── README.md /.nvmrc: -------------------------------------------------------------------------------- 1 | v14 2 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | save-exact=true 2 | -------------------------------------------------------------------------------- /examples/.gitignore: -------------------------------------------------------------------------------- 1 | package-lock.json 2 | -------------------------------------------------------------------------------- /src/helper/index.ts: -------------------------------------------------------------------------------- 1 | export { default as makeRequest } from './make-request' 2 | -------------------------------------------------------------------------------- /src/logger/index.ts: -------------------------------------------------------------------------------- 1 | export * from './logger' 2 | export { default } from './logger' 3 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "printWidth": 120, 4 | "singleQuote": true, 5 | "trailingComma": "es5", 6 | "arrowParens": "always" 7 | } 8 | -------------------------------------------------------------------------------- /src/middleware/hapi/index.ts: -------------------------------------------------------------------------------- 1 | export { default as healthCheck } from './health-check' 2 | export { default as prometheusMetrics } from './prometheus-metrics' 3 | -------------------------------------------------------------------------------- /src/middleware/index.ts: -------------------------------------------------------------------------------- 1 | import * as express from './express' 2 | import * as hapi from './hapi' 3 | import * as koa from './koa' 4 | export { express, hapi, koa } 5 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Each line is a file pattern followed by one or more owners. 2 | # https://help.github.com/articles/about-codeowners/ 3 | 4 | # These owners will be the default owners for everything in 5 | # the repo. Unless a later match takes precedence. 6 | @tothandras 7 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Dependency directory 6 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 7 | node_modules 8 | 9 | # Misc 10 | .env 11 | .github 12 | .circleci 13 | 14 | # Test coverage report 15 | coverage 16 | -------------------------------------------------------------------------------- /examples/hapi/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@banzaicloud/service-tools-hapi-example", 3 | "main": "index.js", 4 | "dependencies": { 5 | "@banzaicloud/service-tools": "../../", 6 | "@hapi/hapi": "19.1.1", 7 | "joi": "17.4.0", 8 | "stoppable": "1.1.0" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/middleware/express/index.ts: -------------------------------------------------------------------------------- 1 | export { default as errorHandler } from './error-handler' 2 | export { default as healthCheck } from './health-check' 3 | export { default as prometheusMetrics } from './prometheus-metrics' 4 | export { default as requestValidator } from './request-validator' 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Dependency directory 6 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 7 | node_modules 8 | 9 | # Build 10 | dist 11 | 12 | # Misc 13 | .env 14 | 15 | # Test coverage report 16 | coverage 17 | -------------------------------------------------------------------------------- /examples/express/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@banzaicloud/service-tools-express-example", 3 | "main": "index.js", 4 | "dependencies": { 5 | "@banzaicloud/service-tools": "../../", 6 | "joi": "17.4.0", 7 | "express": "4.17.1", 8 | "stoppable": "1.1.0" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { default as config } from './config' 2 | export { default as logger } from './logger' 3 | export { default as catchErrors } from './catch-errors' 4 | export { default as gracefulShutdown } from './graceful-shutdown' 5 | import * as middleware from './middleware' 6 | export { middleware } 7 | -------------------------------------------------------------------------------- /examples/koa/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@banzaicloud/service-tools-koa-example", 3 | "main": "index.js", 4 | "dependencies": { 5 | "@banzaicloud/service-tools": "../../", 6 | "joi": "17.4.0", 7 | "koa": "2.11.0", 8 | "koa-router": "8.0.8", 9 | "stoppable": "1.1.0" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["tslint:latest", "tslint-config-prettier"], 3 | "rules": { 4 | "array-type": [true, "generic"], 5 | "no-submodule-imports": false, 6 | "no-console": false, 7 | "object-literal-sort-keys": false, 8 | "prefer-object-spread": false, 9 | "no-implicit-dependencies": [true, "dev", "optional"] 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/middleware/koa/index.ts: -------------------------------------------------------------------------------- 1 | export { default as errorHandler } from './error-handler' 2 | export { default as healthCheck } from './health-check' 3 | export { default as prometheusMetrics, default as prometheusMetricsExporter } from './prometheus-metrics-exporter' 4 | export { default as requestLogger } from './request-logger' 5 | export { default as requestValidator } from './request-validator' 6 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Before sending a pull-request please open an issue to discuss new features or non-trivial changes. 2 | 3 | Checklist: 4 | 5 | - [ ] tests must pass (`npm test`) 6 | - [ ] follow existing coding style (`npm run fmt`) 7 | - [ ] if you add a feature, add documentation to `README` 8 | - [ ] if you fix a bug, add a test 9 | 10 | ### Thank you for your contribution! 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "experimentalDecorators": true, 4 | "resolveJsonModule": true, 5 | "target": "es6", 6 | "module": "commonjs", 7 | "moduleResolution": "node", 8 | "sourceMap": true, 9 | "declaration": true, 10 | "declarationMap": true, 11 | "strict": true, 12 | "outDir": "./dist", 13 | "baseUrl": ".", 14 | "lib": ["es2017", "dom"] 15 | }, 16 | "include": ["src/**/*"], 17 | "exclude": ["node_modules", "**/*.spec.ts"] 18 | } 19 | -------------------------------------------------------------------------------- /examples/hapi/config.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const joi = require('joi') 4 | 5 | const schema = joi 6 | .object({ 7 | PORT: joi.number().integer().min(0).max(65535).default(3000), 8 | }) 9 | .unknown() 10 | .required() 11 | 12 | const { value: envVars, error } = schema.validate(process.env, { 13 | abortEarly: false, 14 | }) 15 | if (error) { 16 | // don't expose environment variables 17 | delete error._object 18 | throw error 19 | } 20 | 21 | const config = { 22 | server: { 23 | port: envVars.PORT, 24 | }, 25 | } 26 | 27 | module.exports = config 28 | -------------------------------------------------------------------------------- /examples/koa/config.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const joi = require('joi') 4 | 5 | const schema = joi 6 | .object({ 7 | PORT: joi.number().integer().min(0).max(65535).default(3000), 8 | }) 9 | .unknown() 10 | .required() 11 | 12 | const { value: envVars, error } = schema.validate(process.env, { 13 | abortEarly: false, 14 | }) 15 | if (error) { 16 | // don't expose environment variables 17 | delete error._object 18 | throw error 19 | } 20 | 21 | const config = { 22 | server: { 23 | port: envVars.PORT, 24 | }, 25 | } 26 | 27 | module.exports = config 28 | -------------------------------------------------------------------------------- /examples/express/config.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const joi = require('joi') 4 | 5 | const schema = joi 6 | .object({ 7 | PORT: joi.number().integer().min(0).max(65535).default(3000), 8 | }) 9 | .unknown() 10 | .required() 11 | 12 | const { value: envVars, error } = schema.validate(process.env, { 13 | abortEarly: false, 14 | }) 15 | if (error) { 16 | // don't expose environment variables 17 | delete error._object 18 | throw error 19 | } 20 | 21 | const config = { 22 | server: { 23 | port: envVars.PORT, 24 | }, 25 | } 26 | 27 | module.exports = config 28 | -------------------------------------------------------------------------------- /src/config/index.ts: -------------------------------------------------------------------------------- 1 | import { LoggerOptions } from 'pino' 2 | import getEnvironmentConfig from './environment' 3 | import getPinoConfig from './pino' 4 | 5 | let environmentConfig: { 6 | nodeEnv: string 7 | } 8 | let pinoConfig: LoggerOptions 9 | 10 | const config = { 11 | get environment() { 12 | if (!environmentConfig) { 13 | environmentConfig = getEnvironmentConfig() 14 | } 15 | 16 | return environmentConfig 17 | }, 18 | 19 | get pino() { 20 | if (!pinoConfig) { 21 | pinoConfig = getPinoConfig() 22 | } 23 | 24 | return pinoConfig 25 | }, 26 | } 27 | export default config 28 | -------------------------------------------------------------------------------- /examples/hapi/README.md: -------------------------------------------------------------------------------- 1 | # Hapi example 2 | 3 | ```sh 4 | $ npm install 5 | $ PORT=8080 node . 6 | # > {"level":30,"time":1534324546995,"msg":"server is listening on port 8080","pid":7453,"hostname":"andras-imac.t.hu","v":1} 7 | 8 | # 1. call the metrics endpoint (can be consumed by Prometheus) 9 | $ curl http://localhost:8080/metrics 10 | 11 | # 2. call the health check endpoint (the fake check fails 20% of the times) 12 | $ curl http://localhost:8080/health 13 | 14 | # 3. hit ctrl+C to kill the application 15 | $ ^C 16 | # > {"level":30,"time":xxx,"msg":"got kill signal (SIGINT), starting graceful shut down","pid":1,"hostname":"local","v":1} 17 | ``` 18 | -------------------------------------------------------------------------------- /examples/koa/README.md: -------------------------------------------------------------------------------- 1 | # Koa example 2 | 3 | ```sh 4 | $ npm install 5 | $ PORT=8080 node . 6 | # > {"level":30,"time":1534324546995,"msg":"server is listening on port 8080","pid":7453,"hostname":"andras-imac.t.hu","v":1} 7 | 8 | # 1. call the metrics endpoint (can be consumed by Prometheus) 9 | $ curl http://localhost:8080/metrics 10 | 11 | # 2. call the health check endpoint (the fake check fails 20% of the times) 12 | $ curl http://localhost:8080/health 13 | 14 | # 3. hit ctrl+C to kill the application 15 | $ ^C 16 | # > {"level":30,"time":xxx,"msg":"got kill signal (SIGINT), starting graceful shut down","pid":1,"hostname":"local","v":1} 17 | ``` 18 | -------------------------------------------------------------------------------- /examples/express/README.md: -------------------------------------------------------------------------------- 1 | # Express example 2 | 3 | ```sh 4 | $ npm install 5 | $ PORT=8080 node . 6 | # > {"level":30,"time":1534324546995,"msg":"server is listening on port 8080","pid":7453,"hostname":"andras-imac.t.hu","v":1} 7 | 8 | # 1. call the metrics endpoint (can be consumed by Prometheus) 9 | $ curl http://localhost:8080/metrics 10 | 11 | # 2. call the health check endpoint (the fake check fails 20% of the times) 12 | $ curl http://localhost:8080/health 13 | 14 | # 3. hit ctrl+C to kill the application 15 | $ ^C 16 | # > {"level":30,"time":xxx,"msg":"got kill signal (SIGINT), starting graceful shut down","pid":1,"hostname":"local","v":1} 17 | ``` 18 | -------------------------------------------------------------------------------- /src/middleware/koa/prometheus-metrics-exporter.ts: -------------------------------------------------------------------------------- 1 | import { Context } from 'koa' 2 | import * as promClient from 'prom-client' 3 | 4 | export default function prometheusMetricsExporterFactory({ 5 | client = promClient, 6 | collectDefaultMetrics = true, 7 | defaultLabels = {}, 8 | } = {}) { 9 | if (collectDefaultMetrics) { 10 | client.collectDefaultMetrics() 11 | } 12 | 13 | if (Object.keys(defaultLabels).length) { 14 | client.register.setDefaultLabels(defaultLabels) 15 | } 16 | 17 | return async function prometheusMetricsExporter(ctx: Context) { 18 | ctx.set('Content-Type', client.register.contentType) 19 | ctx.body = client.register.metrics() 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/middleware/express/prometheus-metrics.ts: -------------------------------------------------------------------------------- 1 | import { Request, RequestHandler, Response } from 'express' 2 | import * as promClient from 'prom-client' 3 | 4 | export default function prometheusMetricsFactory({ 5 | client = promClient, 6 | collectDefaultMetrics = true, 7 | defaultLabels = {}, 8 | } = {}): RequestHandler { 9 | if (collectDefaultMetrics) { 10 | client.collectDefaultMetrics() 11 | } 12 | 13 | if (Object.keys(defaultLabels).length) { 14 | client.register.setDefaultLabels(defaultLabels) 15 | } 16 | 17 | return function prometheusMetrics(req: Request, res: Response) { 18 | const metrics = client.register.metrics() 19 | res.set('Content-Type', client.register.contentType).send(metrics) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Overview of the Issue 2 | 3 | Give a short description of the issue. 4 | 5 | ```javascript 6 | If an error was thrown, paste here the stack trace. 7 | ``` 8 | 9 | ## Reproduce the Error 10 | 11 | Provide an unambiguous set of steps, Node version, package version, etc. 12 | 13 | Steps to reproduce: 14 | 15 | 1. step 16 | 2. step 17 | 3. step 18 | 19 | Node version: `x.x.x` 20 | `npm` | `yarn` version: `x.x.x` 21 | Package version: `x.x.x` 22 | 23 | ## Related Issues 24 | 25 | Has a similar issue been reported before? 26 | 27 | ## Suggest a Fix 28 | 29 | If you can't fix the bug yourself, perhaps you can point to what might be causing the problem (line of code or commit). 30 | 31 | ### Thank you for your contribution! 32 | -------------------------------------------------------------------------------- /src/config/environment.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Exports the runtime environment 3 | * Uses the `NODE_ENV` environment variable 4 | */ 5 | 6 | import * as joi from 'joi' 7 | 8 | const schema = joi 9 | .object({ 10 | // runtime environment. Valid values are: production, development, test 11 | NODE_ENV: joi.string().valid('production', 'development', 'test').default('production'), 12 | }) 13 | .unknown() 14 | .required() 15 | 16 | export default function getConfig() { 17 | const { value: envVars, error } = schema.validate(process.env, { abortEarly: false }) 18 | if (error) { 19 | // don't expose environment variables in stack traces / logs 20 | delete error._original 21 | throw error 22 | } 23 | 24 | return { 25 | nodeEnv: envVars.NODE_ENV as string, 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/middleware/express/error-handler.ts: -------------------------------------------------------------------------------- 1 | import { ErrorRequestHandler, NextFunction, Request, Response } from 'express' 2 | import * as createError from 'http-errors' 3 | import defaultLogger from '../../logger' 4 | 5 | export default function errorHandlerFactory({ 6 | logger = defaultLogger.error.bind(defaultLogger), 7 | } = {}): ErrorRequestHandler { 8 | return function errorHandler(err: Error, req: Request, res: Response, next: NextFunction) { 9 | const httpErr = createError(err) 10 | 11 | if (httpErr.statusCode >= 500 && logger) { 12 | logger(httpErr) 13 | } 14 | 15 | const body = httpErr.statusCode < 500 || httpErr.expose ? httpErr : createError(httpErr.status) 16 | if (httpErr.headers) { 17 | res.set(httpErr.headers) 18 | } 19 | res.status(httpErr.statusCode).send(body) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/middleware/koa/error-handler.ts: -------------------------------------------------------------------------------- 1 | import * as createError from 'http-errors' 2 | import { Context } from 'koa' 3 | import defaultLogger from '../../logger' 4 | 5 | export default function errorHandlerFactory({ logger = defaultLogger.error.bind(defaultLogger) } = {}) { 6 | return async function errorHandler(ctx: Context, next: () => void) { 7 | try { 8 | await next() 9 | } catch (err) { 10 | err = createError(err) 11 | 12 | if (err.statusCode >= 500 && logger) { 13 | logger(err) 14 | } 15 | 16 | ctx.status = err.statusCode 17 | if (err.headers) { 18 | for (const name of Object.keys(err.headers)) { 19 | ctx.set(name, err.headers[name]) 20 | } 21 | } 22 | ctx.body = err.statusCode < 500 || err.expose ? err : createError(err.status) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/logger/logger.spec.ts: -------------------------------------------------------------------------------- 1 | import * as mockConsole from 'jest-mock-console' 2 | import logger from './' 3 | 4 | describe('logger', () => { 5 | let restoreConsole: RestoreConsole 6 | 7 | beforeAll(() => { 8 | restoreConsole = mockConsole() 9 | }) 10 | 11 | afterAll(() => { 12 | restoreConsole() 13 | }) 14 | 15 | afterEach(() => { 16 | logger.restoreConsole() 17 | }) 18 | 19 | it('should intercept console calls', () => { 20 | jest.spyOn(logger, 'info') 21 | console.log('foo') 22 | expect(logger.info).not.toHaveBeenCalled() 23 | logger.interceptConsole() 24 | console.log('foo') 25 | expect(logger.info).toHaveBeenCalledWith('foo') 26 | }) 27 | 28 | it('should intercept console calls', () => { 29 | jest.spyOn(logger, 'error') 30 | console.error('foo') 31 | expect(logger.error).not.toHaveBeenCalled() 32 | logger.interceptConsole(['error']) 33 | console.error('foo') 34 | expect(logger.error).toHaveBeenCalledWith('foo') 35 | }) 36 | }) 37 | -------------------------------------------------------------------------------- /src/middleware/express/request-validator.ts: -------------------------------------------------------------------------------- 1 | import * as joi from 'joi' 2 | import { NextFunction, Request, RequestHandler, Response } from 'express' 3 | import { BadRequest } from 'http-errors' 4 | 5 | export default function requestValidatorFactory({ 6 | params = joi.any(), 7 | query = joi.any(), 8 | body = joi.any(), 9 | } = {}): RequestHandler { 10 | const schema = joi 11 | .object({ 12 | params, 13 | query, 14 | body, 15 | }) 16 | .required() 17 | 18 | return function requestValidator(req: Request, res: Response, next: NextFunction) { 19 | const { value: validated, error } = schema.validate( 20 | { 21 | params: req.params, 22 | query: req.query, 23 | body: req.body, 24 | }, 25 | { abortEarly: false } 26 | ) 27 | if (error) { 28 | const err = Object.assign(new BadRequest('validation error'), { details: error.details }) 29 | return next(err) 30 | } 31 | 32 | Object.assign(req, validated) 33 | next() 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/middleware/express/health-check.ts: -------------------------------------------------------------------------------- 1 | import { Request, RequestHandler, Response } from 'express' 2 | import defaultLogger from '../../logger' 3 | 4 | export default function healthCheckFactory( 5 | checks: Array<() => Promise> = [], 6 | { logger = defaultLogger.error.bind(defaultLogger) } = {} 7 | ): RequestHandler { 8 | // respond with '503 Service Unavailable' once the termination signal is received 9 | let shuttingDown = false 10 | process.once('SIGTERM', () => { 11 | shuttingDown = true 12 | }) 13 | 14 | return async function healthCheck(req: Request, res: Response) { 15 | if (shuttingDown) { 16 | res.status(503).send({ 17 | status: 'error', 18 | details: { 19 | reason: 'service is shutting down', 20 | }, 21 | }) 22 | return 23 | } 24 | 25 | for (const check of checks) { 26 | try { 27 | await check() 28 | } catch (err) { 29 | logger(err, 'health check failed') 30 | res.status(500).send({ 31 | status: 'error', 32 | }) 33 | return 34 | } 35 | } 36 | 37 | res.status(200).send({ 38 | status: 'ok', 39 | }) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/middleware/koa/request-validator.ts: -------------------------------------------------------------------------------- 1 | import * as joi from 'joi' 2 | import { BadRequest } from 'http-errors' 3 | import { Context, Request } from 'koa' 4 | 5 | interface IContextWithRequest extends Context { 6 | params?: object 7 | request: Request & { 8 | params?: object 9 | body?: object 10 | query?: object 11 | } 12 | } 13 | 14 | export default function requestValidatorFactory({ params = joi.any(), query = joi.any(), body = joi.any() } = {}) { 15 | const schema = joi 16 | .object({ 17 | params, 18 | query, 19 | body, 20 | }) 21 | .required() 22 | 23 | return async function requestValidator(ctx: IContextWithRequest, next: () => void) { 24 | const { value: validated, error } = schema.validate( 25 | { 26 | params: ctx.params || (ctx.request && ctx.request.params), 27 | query: ctx.query || (ctx.request && ctx.request.query), 28 | body: ctx.request && ctx.request.body, 29 | }, 30 | { abortEarly: false } 31 | ) 32 | if (error) { 33 | throw Object.assign(new BadRequest('validation error'), { details: error.details }) 34 | } 35 | 36 | ctx.state = Object.assign({}, ctx.state, { validated }) 37 | await next() 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/middleware/koa/health-check.ts: -------------------------------------------------------------------------------- 1 | import { Context } from 'koa' 2 | import defaultLogger from '../../logger' 3 | 4 | export default function healthCheckFactory( 5 | checks: Array<() => Promise> = [], 6 | { logger = defaultLogger.error.bind(defaultLogger), serviceUnavailableOnTermination = true } = {} 7 | ) { 8 | let shuttingDown = false 9 | if (serviceUnavailableOnTermination) { 10 | // respond with '503 Service Unavailable' once the termination signal is received 11 | process.once('SIGTERM', () => { 12 | shuttingDown = true 13 | }) 14 | } 15 | 16 | return async function healthCheck(ctx: Context) { 17 | if (shuttingDown) { 18 | ctx.status = 503 19 | ctx.body = { 20 | status: 'error', 21 | details: { 22 | reason: 'service is shutting down', 23 | }, 24 | } 25 | return 26 | } 27 | 28 | for (const check of checks) { 29 | try { 30 | await check() 31 | } catch (err) { 32 | logger(err, 'health check failed') 33 | ctx.status = 500 34 | ctx.body = { 35 | status: 'error', 36 | } 37 | return 38 | } 39 | } 40 | 41 | ctx.status = 200 42 | ctx.body = { status: 'ok' } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/middleware/hapi/prometheus-metrics.ts: -------------------------------------------------------------------------------- 1 | import * as Hapi from '@hapi/hapi' 2 | import * as promClient from 'prom-client' 3 | import * as pgk from '../../../package.json' 4 | 5 | interface IOptions { 6 | path: string 7 | client?: typeof promClient 8 | collectDefaultMetrics?: boolean 9 | timeout?: number 10 | defaultLabels?: object 11 | } 12 | 13 | const prometheusMetrics: Hapi.Plugin = { 14 | name: `${pgk.name}/prometheus-metrics`, 15 | version: pgk.version, 16 | async register( 17 | server: Hapi.Server, 18 | { path, client = promClient, collectDefaultMetrics = true, defaultLabels = {} }: IOptions 19 | ) { 20 | if (typeof path !== 'string') { 21 | throw new TypeError('path in options is required') 22 | } 23 | 24 | if (collectDefaultMetrics) { 25 | client.collectDefaultMetrics() 26 | } 27 | 28 | if (Object.keys(defaultLabels).length) { 29 | client.register.setDefaultLabels(defaultLabels) 30 | } 31 | 32 | server.route({ 33 | method: 'GET', 34 | path, 35 | handler(req, h) { 36 | const metrics = client.register.metrics() 37 | return h.response(metrics).header('Content-Type', client.register.contentType) 38 | }, 39 | }) 40 | }, 41 | } 42 | 43 | export default prometheusMetrics 44 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Issues: got a question or problem? 4 | 5 | Before you submit your issue search the archive, maybe your question was already answered. 6 | 7 | If your issue appears to be a bug, and hasn't been reported, open a new issue. 8 | Help us to maximize the effort we can spend fixing issues and adding new 9 | features, by not reporting duplicate issues. Providing the following information will increase the 10 | chances of your issue being dealt with quickly: 11 | 12 | - **Overview of the Issue** 13 | - **Reproduce the Error** 14 | - **Related Issues** 15 | - **Suggest a Fix** 16 | 17 | ## Submitting a Pull Request 18 | 19 | 1. Fork the project (if you don't have write access to the repository) 20 | 2. Make your changes in a new git branch: 21 | 22 | ```shell 23 | git checkout -b fix/my-branch master 24 | ``` 25 | 26 | 3. Commit your changes using a descriptive commit message that follows the [Angular commit message format](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#commit-message-format) 27 | 28 | ```shell 29 | git commit -a 30 | ``` 31 | 32 | 4. Push your branch to GitHub: 33 | 34 | ```shell 35 | git push origin fix/my-branch 36 | ``` 37 | 38 | 5. In GitHub, send a pull request to `master` 39 | 40 | #### Thank you for your contribution! 41 | -------------------------------------------------------------------------------- /src/logger/logger.ts: -------------------------------------------------------------------------------- 1 | import * as pino from 'pino' 2 | import config from '../config' 3 | 4 | const logger = pino(config.pino) 5 | 6 | let originals: INameToValueMap 7 | export default Object.assign(logger, { 8 | interceptConsole(levels = ['log', 'debug', 'info', 'warn', 'error']) { 9 | const useLogger = (level: string) => { 10 | const log = (logger[level] ? logger[level] : logger.info).bind(logger) 11 | return (...args: Array) => { 12 | if (args.length > 0) { 13 | if (typeof args[0] === 'string' && typeof args[1] === 'object') { 14 | log(args[1], args[0], ...args.slice(2)) 15 | } else { 16 | log(args[0], ...args.slice(1)) 17 | } 18 | } else { 19 | log(args[0]) 20 | } 21 | } 22 | } 23 | 24 | originals = {} 25 | for (const level of levels) { 26 | originals[level] = (console as INameToValueMap)[level] 27 | Object.assign(console, { 28 | [level]: useLogger(level), 29 | }) 30 | } 31 | }, 32 | 33 | restoreConsole() { 34 | for (const level of Object.keys(originals)) { 35 | Object.assign(console, { 36 | [level]: originals[level], 37 | }) 38 | } 39 | }, 40 | }) 41 | 42 | interface INameToValueMap { 43 | [key: string]: any 44 | } 45 | -------------------------------------------------------------------------------- /src/helper/make-request.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Request function for testing routes on localhost 3 | */ 4 | 5 | import * as http from 'http' 6 | import { AddressInfo } from 'net' 7 | import got, { Options } from 'got' 8 | import { promisify } from 'util' 9 | 10 | /** 11 | * Starts the server on localhost and makes a request with the specified options 12 | */ 13 | export default async function makeRequest( 14 | server: http.Server, 15 | options?: Options & { endpoint?: string }, 16 | ) { 17 | if (!(server instanceof http.Server)) { 18 | throw new TypeError('Parameter server is required to be an http.Server instance') 19 | } 20 | 21 | const serverListen: any = promisify(server.listen).bind(server) 22 | const serverClose = promisify(server.close).bind(server) 23 | 24 | // bind the server to a free port on localhost 25 | const hostname = '127.0.0.1' 26 | await serverListen(0, hostname) 27 | const { port } = server.address() as AddressInfo 28 | 29 | // make the request 30 | const { endpoint = '', ...requestOptions } = options || {} 31 | const response = await got(endpoint, { 32 | prefixUrl: `http://${hostname}:${port}`, 33 | responseType: 'json', 34 | throwHttpErrors: false, 35 | ...requestOptions, 36 | }) 37 | 38 | // close the server 39 | await serverClose() 40 | 41 | return response 42 | } 43 | -------------------------------------------------------------------------------- /src/middleware/express/request-validator.spec.ts: -------------------------------------------------------------------------------- 1 | import * as joi from 'joi' 2 | import * as express from 'express' 3 | import * as http from 'http' 4 | import makeRequest from '../../helper/make-request' 5 | import { requestValidator } from './' 6 | 7 | describe('express request validator middleware', () => { 8 | let app: express.Application 9 | beforeEach(() => { 10 | app = express() 11 | }) 12 | 13 | it('should respond with 400 when validation fails', async () => { 14 | app.get('/', requestValidator({ query: joi.object({ foo: joi.string().required() }).required() }), (req, res) => { 15 | res.status(200).end() 16 | }) 17 | 18 | const server = http.createServer(app) 19 | const response = await makeRequest(server, { endpoint: '?bar=foo' }) 20 | expect(response.statusCode).toEqual(400) 21 | }) 22 | 23 | it('should continue when validation passes', async () => { 24 | app.get('/', requestValidator({ query: joi.object({ foo: joi.string().required() }).required() }), (req, res) => { 25 | res.status(200).send({ query: req.query }) 26 | }) 27 | 28 | const server = http.createServer(app) 29 | const response = await makeRequest(server, { endpoint: '?foo=bar' }) 30 | expect(response.statusCode).toEqual(200) 31 | expect(response.body).toEqual({ query: { foo: 'bar' } }) 32 | }) 33 | }) 34 | -------------------------------------------------------------------------------- /src/middleware/koa/request-validator.spec.ts: -------------------------------------------------------------------------------- 1 | import * as http from 'http' 2 | import * as joi from 'joi' 3 | import * as Koa from 'koa' 4 | import makeRequest from '../../helper/make-request' 5 | import { requestValidator } from './' 6 | 7 | describe('koa request validator middleware', () => { 8 | let app: Koa 9 | beforeEach(() => { 10 | app = new Koa() 11 | }) 12 | 13 | it('should respond with 400 when validation fails', async () => { 14 | app.use(requestValidator({ query: joi.object({ foo: joi.string().required() }).required() })) 15 | app.use((ctx: Koa.Context) => { 16 | ctx.status = 200 17 | }) 18 | 19 | const server = http.createServer(app.callback()) 20 | const response = await makeRequest(server, { endpoint: '?bar=foo' }) 21 | expect(response.statusCode).toEqual(400) 22 | }) 23 | 24 | it('should continue when validation passes', async () => { 25 | app.use(requestValidator({ query: joi.object({ foo: joi.string().required() }).required() })) 26 | app.use((ctx: Koa.Context) => { 27 | const { validated = {} } = ctx.state || {} 28 | ctx.status = 200 29 | ctx.body = validated 30 | }) 31 | 32 | const server = http.createServer(app.callback()) 33 | const response = await makeRequest(server, { endpoint: '?foo=bar' }) 34 | expect(response.statusCode).toEqual(200) 35 | expect(response.body).toEqual({ query: { foo: 'bar' } }) 36 | }) 37 | }) 38 | -------------------------------------------------------------------------------- /src/middleware/koa/error-handler.spec.ts: -------------------------------------------------------------------------------- 1 | import * as http from 'http' 2 | import * as createError from 'http-errors' 3 | import * as Koa from 'koa' 4 | import makeRequest from '../../helper/make-request' 5 | import { errorHandler } from './' 6 | 7 | describe('koa error handler middleware', () => { 8 | const logger: any = jest.fn((...args: any[]) => undefined) 9 | 10 | let app: Koa 11 | beforeEach(() => { 12 | app = new Koa() 13 | app.use(errorHandler({ logger })) 14 | }) 15 | 16 | it('should use the proper status code and body of a HttpError (status: 4xx)', async () => { 17 | app.use((ctx) => { 18 | throw new createError.Forbidden() 19 | }) 20 | 21 | const server = http.createServer(app.callback()) 22 | const response = await makeRequest(server) 23 | expect(response.statusCode).toEqual(403) 24 | expect(response.body).toEqual({ message: 'Forbidden' }) 25 | expect(logger).not.toHaveBeenCalled() 26 | }) 27 | 28 | it('should use the proper status code and body of a HttpError (status: 5xx)', async () => { 29 | app.use((ctx) => { 30 | throw new Error('Error message') 31 | }) 32 | 33 | const server = http.createServer(app.callback()) 34 | const response = await makeRequest(server) 35 | expect(response.statusCode).toEqual(500) 36 | expect(response.body).toEqual({ message: 'Internal Server Error' }) 37 | expect(logger).toHaveBeenCalled() 38 | }) 39 | }) 40 | -------------------------------------------------------------------------------- /src/middleware/express/error-handler.spec.ts: -------------------------------------------------------------------------------- 1 | import * as express from 'express' 2 | import * as http from 'http' 3 | import * as createError from 'http-errors' 4 | import makeRequest from '../../helper/make-request' 5 | import { errorHandler } from './' 6 | 7 | describe('express error handler middleware', () => { 8 | const logger: any = jest.fn((...args: any[]) => undefined) 9 | 10 | let app: express.Application 11 | beforeEach(() => { 12 | app = express() 13 | }) 14 | 15 | it('should use the proper status code and body of a HttpError (status: 4xx)', async () => { 16 | app.get('/', () => { 17 | throw new createError.Forbidden() 18 | }) 19 | app.use(errorHandler({ logger })) 20 | 21 | const server = http.createServer(app) 22 | const response = await makeRequest(server) 23 | expect(response.statusCode).toEqual(403) 24 | expect(response.body).toEqual({ message: 'Forbidden' }) 25 | expect(logger).not.toHaveBeenCalled() 26 | }) 27 | 28 | it('should use the proper status code and body of a HttpError (status: 5xx)', async () => { 29 | app.get('/', () => { 30 | throw new Error('Error message') 31 | }) 32 | app.use(errorHandler({ logger })) 33 | 34 | const server = http.createServer(app) 35 | const response = await makeRequest(server) 36 | expect(response.statusCode).toEqual(500) 37 | expect(response.body).toEqual({ message: 'Internal Server Error' }) 38 | expect(logger).toHaveBeenCalled() 39 | }) 40 | }) 41 | -------------------------------------------------------------------------------- /src/middleware/koa/request-logger.ts: -------------------------------------------------------------------------------- 1 | import { Context, Request } from 'koa' 2 | import * as fp from 'lodash/fp' 3 | import { LogFn } from 'pino' 4 | import { Stream } from 'stream' 5 | import defaultLogger from '../../logger' 6 | 7 | export default function requestLoggerFactory({ 8 | logger = defaultLogger.debug.bind(defaultLogger) as LogFn, 9 | }: { logger?: LogFn } = {}) { 10 | return async function requestLogger(ctx: Context, next: () => void) { 11 | const start = Date.now() 12 | 13 | const { 14 | method, 15 | originalUrl, 16 | headers: requestHeaders, 17 | body: requestBody, 18 | ip: remoteIp, 19 | }: Request & { body?: any } = ctx.request 20 | const httpRequest = fp.omitBy(fp.isNil, { 21 | method, 22 | remoteIp, 23 | url: originalUrl, 24 | referrer: ctx.request.get('referer'), 25 | userAgent: ctx.request.get('user-agent'), 26 | headers: requestHeaders, 27 | body: requestBody, 28 | }) 29 | 30 | await next() 31 | 32 | const ms = Date.now() - start 33 | const { status, headers: responseHeaders, body: responseBody = '' } = ctx.response 34 | const httpResponse = fp.omitBy(fp.isNil, { 35 | status, 36 | headers: responseHeaders, 37 | body: responseBody instanceof Stream ? '[Stream]' : responseBody, 38 | }) 39 | 40 | logger( 41 | { 42 | httpRequest, 43 | httpResponse, 44 | duration: `${ms}ms`, 45 | }, 46 | `${method}: ${originalUrl}` 47 | ) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/middleware/hapi/prometheus-metrics.spec.ts: -------------------------------------------------------------------------------- 1 | import * as Hapi from '@hapi/hapi' 2 | import * as http from 'http' 3 | import makeRequest from '../../helper/make-request' 4 | import { prometheusMetrics } from './' 5 | 6 | describe('hapi prometheus metrics plugin', () => { 7 | let server: Hapi.Server 8 | beforeEach(() => { 9 | server = Hapi.server() 10 | }) 11 | 12 | it('should serve metrics with default client', async () => { 13 | server.register({ plugin: prometheusMetrics, options: { path: '/metrics' } }) 14 | const response = await makeRequest(server.listener, { endpoint: 'metrics', responseType: 'text' }) 15 | expect(response.statusCode).toEqual(200) 16 | expect(response.headers['content-type']).toEqual('text/plain; version=0.0.4; charset=utf-8') 17 | }) 18 | 19 | it('should serve metrics with provided client', async () => { 20 | const client = { 21 | register: { 22 | contentType: 'text/plain; version=0.0.4; charset=utf-8', 23 | metrics: jest.fn().mockReturnValue('METRICS'), 24 | }, 25 | } 26 | server.register({ 27 | plugin: prometheusMetrics, 28 | options: { 29 | client, 30 | path: '/metrics', 31 | collectDefaultMetrics: false, 32 | }, 33 | }) 34 | const response = await makeRequest(server.listener, { endpoint: 'metrics', responseType: 'text' }) 35 | expect(response.statusCode).toEqual(200) 36 | expect(response.body).toEqual('METRICS') 37 | expect(client.register.metrics).toHaveBeenCalled() 38 | }) 39 | }) 40 | -------------------------------------------------------------------------------- /src/config/pino.ts: -------------------------------------------------------------------------------- 1 | import * as joi from 'joi' 2 | import { LoggerOptions } from 'pino' 3 | 4 | const schema = joi 5 | .object({ 6 | LOGGER_LEVEL: joi 7 | .string() 8 | .valid('fatal', 'error', 'warn', 'info', 'debug', 'trace') 9 | .when('NODE_ENV', { 10 | switch: [ 11 | { 12 | is: 'test', 13 | then: joi.string().default('fatal'), 14 | }, 15 | { 16 | is: 'development', 17 | then: joi.string().default('debug'), 18 | otherwise: joi.string().default('info'), 19 | }, 20 | ], 21 | }), 22 | LOGGER_REDACT_FIELDS: joi 23 | .string() 24 | .default('password, pass, authorization, auth, cookie, _object') 25 | .description('Comma separated list of field names to remove from objects'), 26 | NODE_ENV: joi.string().default('production'), 27 | }) 28 | .unknown() 29 | .required() 30 | 31 | export default function getConfig() { 32 | const { value: envVars, error } = schema.validate(process.env, { abortEarly: false }) 33 | if (error) { 34 | // don't expose environment variables in stack traces / logs 35 | delete error._original 36 | throw error 37 | } 38 | 39 | const redactFields = envVars 40 | .LOGGER_REDACT_FIELDS!.split(',') 41 | .map((field: string) => field.trim()) 42 | .filter((field: string) => field !== '') 43 | 44 | const config: LoggerOptions = { 45 | level: envVars.LOGGER_LEVEL, 46 | redact: redactFields, 47 | } 48 | 49 | return config 50 | } 51 | -------------------------------------------------------------------------------- /src/middleware/hapi/health-check.ts: -------------------------------------------------------------------------------- 1 | import * as Boom from '@hapi/boom' 2 | import * as Hapi from '@hapi/hapi' 3 | import { LogFn } from 'pino' 4 | import * as pgk from '../../../package.json' 5 | import defaultLogger from '../../logger' 6 | 7 | interface IOptions { 8 | path: string 9 | logger?: LogFn 10 | checks?: Array<() => Promise> 11 | } 12 | 13 | const healthCheck: Hapi.Plugin = { 14 | name: `${pgk.name}/health-check`, 15 | version: pgk.version, 16 | async register( 17 | server: Hapi.Server, 18 | { path, logger = defaultLogger.error.bind(defaultLogger), checks = [] }: IOptions 19 | ) { 20 | if (typeof path !== 'string') { 21 | throw new TypeError('path in options is required') 22 | } 23 | 24 | // respond with '503 Service Unavailable' once the termination signal is received 25 | let shuttingDown = false 26 | process.once('SIGTERM', () => { 27 | shuttingDown = true 28 | }) 29 | 30 | server.route({ 31 | method: 'GET', 32 | path, 33 | async handler(req, h) { 34 | if (shuttingDown) { 35 | return Boom.serverUnavailable('service is shutting down') 36 | } 37 | 38 | for (const check of checks) { 39 | try { 40 | await check() 41 | } catch (err) { 42 | logger(err, 'health check failed') 43 | return Boom.internal('health check failed') 44 | } 45 | } 46 | 47 | return { status: 'ok' } 48 | }, 49 | }) 50 | }, 51 | } 52 | 53 | export default healthCheck 54 | -------------------------------------------------------------------------------- /src/graceful-shutdown.ts: -------------------------------------------------------------------------------- 1 | import { LogFn } from 'pino' 2 | import defaultLogger from './logger' 3 | 4 | export default function registerGracefulShutdown( 5 | // https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters 6 | this: any, 7 | closeHandlers: Array<() => Promise> = [], 8 | { 9 | logger = { 10 | info: defaultLogger.info.bind(defaultLogger) as LogFn, 11 | error: defaultLogger.error.bind(defaultLogger) as LogFn, 12 | }, 13 | timeout = 30, 14 | } = {} 15 | ) { 16 | // gracefully shutdown on SIGTERM or SIGINT signal 17 | process.once('SIGTERM', gracefulShutDown.bind(this, 'SIGTERM')) 18 | process.once('SIGINT', gracefulShutDown.bind(this, 'SIGINT')) 19 | 20 | async function gracefulShutDown(signal = 'SIGTERM') { 21 | logger.info(`got kill signal (${signal}), starting graceful shut down`) 22 | 23 | // shut down anyway after `timeout` seconds 24 | if (timeout) { 25 | setTimeout(() => { 26 | logger.error('could not finish in time, forcefully exiting') 27 | process.exit(1) 28 | }, timeout * 1000).unref() 29 | } 30 | 31 | // release resources 32 | let isError = false 33 | for (const handler of closeHandlers) { 34 | try { 35 | await Promise.resolve(handler()) 36 | } catch (err) { 37 | logger.error(err, 'error happened during graceful shut down') 38 | isError = true 39 | } 40 | } 41 | 42 | if (isError) { 43 | process.exit(1) 44 | } 45 | 46 | logger.info('graceful shut down finished') 47 | process.kill(process.pid, signal) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | defaults: &defaults 2 | working_directory: ~/repo 3 | docker: 4 | - image: circleci/node:12 5 | 6 | version: 2 7 | jobs: 8 | test: 9 | <<: *defaults 10 | steps: 11 | - checkout 12 | - restore_cache: 13 | keys: 14 | - v1-dependencies-{{ checksum "package-lock.json" }} 15 | # fallback to using the latest cache if no exact match is found 16 | - v1-dependencies- 17 | - run: npm ci 18 | - save_cache: 19 | paths: 20 | - node_modules 21 | key: v1-dependencies-{{ checksum "package-lock.json" }} 22 | - run: npm test 23 | - persist_to_workspace: 24 | root: ~/repo 25 | paths: 26 | - . 27 | publish: 28 | <<: *defaults 29 | steps: 30 | - attach_workspace: 31 | at: ~/repo 32 | # NPM 33 | - run: 34 | name: Authenticate with registry 35 | command: | 36 | cat <> .npmrc 37 | //registry.npmjs.org/:_authToken=${NPM_TOKEN} 38 | //npm.pkg.github.com/:_authToken=${GITHUB_TOKEN} 39 | EOF 40 | - run: 41 | name: Publish package 42 | command: | 43 | npm publish 44 | npm publish --registry=https://npm.pkg.github.com 45 | 46 | workflows: 47 | version: 2 48 | test-publish: 49 | jobs: 50 | - test: 51 | filters: 52 | tags: 53 | only: /^v.*/ 54 | - publish: 55 | requires: 56 | - test 57 | filters: 58 | tags: 59 | only: /^v.*/ 60 | branches: 61 | ignore: /.*/ 62 | -------------------------------------------------------------------------------- /src/catch-errors.spec.ts: -------------------------------------------------------------------------------- 1 | import catchErrors from './catch-errors' 2 | import logger from './logger' 3 | 4 | describe('catch errors', () => { 5 | let reset: () => void 6 | let closeHandler: jest.Mock<{}> 7 | 8 | beforeEach(() => { 9 | closeHandler = jest.fn().mockResolvedValue(undefined) 10 | jest.spyOn(logger, 'fatal').mockReturnValue(undefined) 11 | jest.spyOn(process, 'exit').mockImplementation(() => { 12 | /* noop */ 13 | }) 14 | reset = catchErrors([closeHandler]) 15 | }) 16 | 17 | afterEach(() => { 18 | reset() 19 | jest.restoreAllMocks() 20 | }) 21 | 22 | it('should catch uncaught exceptions and exit the process', async () => { 23 | const err = new Error() 24 | process.emit('uncaughtException', err) 25 | // wait for promises 26 | await new Promise((resolve) => setImmediate(resolve)) 27 | expect(logger.fatal).toHaveBeenCalledWith(err, 'uncaught exception') 28 | expect(closeHandler).toHaveBeenCalled() 29 | expect(process.exit).toHaveBeenCalledWith(1) 30 | }) 31 | 32 | it('should catch unhandled promise rejections', async () => { 33 | jest.spyOn(logger, 'fatal').mockReturnValue(undefined) 34 | jest.spyOn(process, 'exit').mockImplementation(() => { 35 | /* noop */ 36 | }) 37 | const reason = new Error() 38 | const promise = new Promise(() => { 39 | /* don't care */ 40 | }) 41 | process.emit('unhandledRejection', reason, promise) 42 | // wait for promises 43 | await new Promise((resolve) => setImmediate(resolve)) 44 | expect(logger.fatal).toHaveBeenCalledWith(reason, 'unhandled promise rejection') 45 | expect(closeHandler).toHaveBeenCalled() 46 | expect(process.exit).toHaveBeenCalledWith(1) 47 | }) 48 | }) 49 | -------------------------------------------------------------------------------- /src/middleware/express/health-check.spec.ts: -------------------------------------------------------------------------------- 1 | import * as express from 'express' 2 | import * as http from 'http' 3 | import makeRequest from '../../helper/make-request' 4 | import { healthCheck } from './' 5 | 6 | describe('express health check middleware', () => { 7 | const logger: any = jest.fn((...args: any[]) => undefined) 8 | 9 | let app: express.Application 10 | beforeEach(() => { 11 | app = express() 12 | }) 13 | 14 | it('should respond with 200 status `ok` when all checks are passing', async () => { 15 | app.get('/', healthCheck([() => Promise.resolve()], { logger })) 16 | 17 | const server = http.createServer(app) 18 | const response = await makeRequest(server) 19 | expect(response.statusCode).toEqual(200) 20 | expect(response.body).toEqual({ status: 'ok' }) 21 | expect(logger).not.toHaveBeenCalled() 22 | }) 23 | 24 | it('should respond with 500 status `error` when some checks are failing', async () => { 25 | const err = new Error('dependency error') 26 | app.get('/', healthCheck([() => Promise.resolve(), () => Promise.reject(err)], { logger })) 27 | 28 | const server = http.createServer(app) 29 | const response = await makeRequest(server) 30 | expect(response.statusCode).toEqual(500) 31 | expect(response.body).toEqual({ status: 'error' }) 32 | expect(logger).toHaveBeenCalledWith(err, 'health check failed') 33 | }) 34 | 35 | it('should respond with 503 status `error` when shutdown signal is received', async () => { 36 | app.get('/', healthCheck([() => Promise.resolve()], { logger })) 37 | 38 | const server = http.createServer(app) 39 | let response = await makeRequest(server) 40 | expect(response.statusCode).toEqual(200) 41 | expect(response.body).toEqual({ status: 'ok' }) 42 | expect(logger).not.toHaveBeenCalled() 43 | 44 | process.emit('SIGTERM', 'SIGTERM') 45 | 46 | response = await makeRequest(server) 47 | expect(response.statusCode).toEqual(503) 48 | expect(response.body).toEqual({ status: 'error', details: { reason: 'service is shutting down' } }) 49 | expect(logger).not.toHaveBeenCalled() 50 | }) 51 | }) 52 | -------------------------------------------------------------------------------- /examples/express/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const http = require('http') 4 | const { promisify } = require('util') 5 | const { config, catchErrors, logger, middleware, gracefulShutdown } = require('@banzaicloud/service-tools') 6 | const stoppable = require('stoppable') 7 | const express = require('express') 8 | const cfg = require('./config') 9 | 10 | // catch all uncaught exceptions and unhandled promise rejections and exit application 11 | catchErrors([closeResources]) 12 | 13 | // intercept console calls and use built in (pino) logger instead 14 | logger.interceptConsole() 15 | 16 | const { nodeEnv } = config.environment 17 | console.log('starting application', { nodeEnv }) 18 | 19 | // create an express application 20 | const app = express() 21 | 22 | // create routes 23 | app.get('/', (req, res) => { 24 | res.status(200).end() 25 | }) 26 | app.get('/metrics', middleware.express.prometheusMetrics()) 27 | app.get( 28 | '/health', 29 | middleware.express.healthCheck([ 30 | async () => { 31 | // fake check 32 | return new Promise((resolve, reject) => { 33 | if (Math.random() < 0.2) { 34 | return reject(new Error('check failed')) 35 | } 36 | 37 | resolve() 38 | }) 39 | }, 40 | ]) 41 | ) 42 | 43 | // register error middleware 44 | app.use(middleware.express.errorHandler()) 45 | 46 | // use `stoppable` to stop accepting new connections and closes existing, 47 | // idle connections(including keep - alives) without killing requests that are in-flight 48 | // on .stop() call 49 | const server = stoppable(http.createServer(app)) 50 | // start server 51 | server.listen(cfg.server.port) 52 | 53 | server.once('listening', () => { 54 | const { port } = server.address() 55 | console.log(`server is listening on port ${port}`) 56 | }) 57 | 58 | server.once('error', (err) => { 59 | console.error('server error', err) 60 | process.exit(1) 61 | }) 62 | 63 | // close resources on error and stop signal 64 | var closeServer = promisify(server.stop).bind(server) 65 | async function closeResources() { 66 | // handle ongoing requests and close server 67 | if (closeServer) { 68 | await closeServer() 69 | } 70 | // ... close databases, message queues and other resources 71 | } 72 | 73 | // gracefully handle application stop (on SIGTERM & SIGINT) 74 | gracefulShutdown([closeResources]) 75 | -------------------------------------------------------------------------------- /src/catch-errors.ts: -------------------------------------------------------------------------------- 1 | import { LogFn } from 'pino' 2 | import defaultLogger from './logger' 3 | 4 | export default function catchErrors( 5 | closeHandlers: Array<() => Promise> = [], 6 | { 7 | exitOnUncaughtPromiseException = true, 8 | logger = defaultLogger.fatal.bind(defaultLogger) as LogFn, 9 | timeout = 30, 10 | }: { 11 | exitOnUncaughtPromiseException?: boolean 12 | logger?: LogFn 13 | timeout?: number 14 | } = {} 15 | ) { 16 | // it is not safe to resume normal operation after 'uncaughtException'. 17 | // read more: https://nodejs.org/api/process.html#process_event_uncaughtexception 18 | const uncaughtExceptionHandler = async (err: Error) => { 19 | logger(err, 'uncaught exception') 20 | 21 | // shut down anyway after `timeout` seconds 22 | if (timeout) { 23 | setTimeout(() => { 24 | logger('could not finish in time, forcefully exiting') 25 | process.exit(1) 26 | }, timeout * 1000).unref() 27 | } 28 | 29 | for (const handler of closeHandlers) { 30 | try { 31 | await Promise.resolve(handler()) 32 | } catch (err) { 33 | logger(err, 'failed to close resource') 34 | } 35 | } 36 | 37 | process.exit(1) 38 | } 39 | process.on('uncaughtException', uncaughtExceptionHandler) 40 | 41 | // a Promise is rejected and no error handler is attached. 42 | // read more: https://nodejs.org/api/process.html#process_event_unhandledrejection 43 | const unhandledRejectionHandler = async (reason: any = {}, promise: Promise) => { 44 | logger(reason, 'unhandled promise rejection') 45 | 46 | // shut down anyway after `timeout` seconds 47 | if (timeout) { 48 | setTimeout(() => { 49 | logger('could not finish in time, forcefully exiting') 50 | process.exit(1) 51 | }, timeout * 1000).unref() 52 | } 53 | 54 | for (const handler of closeHandlers) { 55 | try { 56 | await Promise.resolve(handler()) 57 | } catch (err) { 58 | logger(err, 'failed to close resource') 59 | } 60 | } 61 | 62 | if (exitOnUncaughtPromiseException) { 63 | process.exit(1) 64 | } 65 | } 66 | process.on('unhandledRejection', unhandledRejectionHandler) 67 | 68 | return () => { 69 | process.off('uncaughtException', uncaughtExceptionHandler) 70 | process.off('unhandledRejection', unhandledRejectionHandler) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /examples/hapi/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const { promisify } = require('util') 4 | const { config, catchErrors, logger, middleware, gracefulShutdown } = require('@banzaicloud/service-tools') 5 | const stoppable = require('stoppable') 6 | const Hapi = require('@hapi/hapi') 7 | const cfg = require('./config') 8 | 9 | // catch all uncaught exceptions and unhandled promise rejections and exit application 10 | catchErrors([closeResources]) 11 | 12 | // intercept console calls and use built in (pino) logger instead 13 | logger.interceptConsole() 14 | 15 | const { nodeEnv } = config.environment 16 | console.log('starting application', { nodeEnv }) 17 | 18 | // create Hapi server application and router 19 | const server = Hapi.server() 20 | 21 | // create routes 22 | server.route({ 23 | method: 'GET', 24 | path: '/', 25 | handler(req, h) { 26 | return { status: 'ok' } 27 | }, 28 | }) 29 | server.register({ 30 | plugin: middleware.hapi.prometheusMetrics, 31 | options: { 32 | path: '/metrics', 33 | }, 34 | }) 35 | server.register({ 36 | plugin: middleware.hapi.healthCheck, 37 | options: { 38 | path: '/health', 39 | checks: [ 40 | async () => { 41 | // fake check 42 | return new Promise((resolve, reject) => { 43 | if (Math.random() < 0.2) { 44 | return reject(new Error('check failed')) 45 | } 46 | 47 | resolve() 48 | }) 49 | }, 50 | ], 51 | }, 52 | }) 53 | 54 | // use `stoppable` to stop accepting new connections and closes existing, 55 | // idle connections(including keep - alives) without killing requests that are in-flight 56 | // on .stop() call 57 | const httpServer = stoppable(server.listener) 58 | // start server 59 | httpServer.listen(cfg.server.port) 60 | 61 | httpServer.once('listening', () => { 62 | const { port } = httpServer.address() 63 | console.log(`server is listening on port ${port}`) 64 | }) 65 | 66 | httpServer.once('error', (err) => { 67 | console.error('server error', err) 68 | process.exit(1) 69 | }) 70 | 71 | // close resources on error and stop signal 72 | var closeServer = promisify(httpServer.stop).bind(httpServer) 73 | async function closeResources() { 74 | // handle ongoing requests and close server 75 | if (closeServer) { 76 | await closeServer() 77 | } 78 | // ... close databases, message queues and other resources 79 | } 80 | 81 | // gracefully handle application stop (on SIGTERM & SIGINT) 82 | gracefulShutdown([closeResources]) 83 | -------------------------------------------------------------------------------- /src/middleware/hapi/health-check.spec.ts: -------------------------------------------------------------------------------- 1 | import * as Hapi from '@hapi/hapi' 2 | import * as http from 'http' 3 | import makeRequest from '../../helper/make-request' 4 | import { healthCheck } from './' 5 | 6 | describe('hapi health check plugin', () => { 7 | const logger: any = jest.fn((...args: any[]) => undefined) 8 | 9 | let server: Hapi.Server 10 | beforeEach(() => { 11 | server = Hapi.server() 12 | }) 13 | 14 | it('should respond with 200 status `ok` when all checks are passing', async () => { 15 | server.register({ 16 | plugin: healthCheck, 17 | options: { 18 | path: '/', 19 | logger, 20 | checks: [() => Promise.resolve()], 21 | }, 22 | }) 23 | 24 | const response = await makeRequest(server.listener) 25 | expect(response.statusCode).toEqual(200) 26 | expect(response.body).toEqual({ status: 'ok' }) 27 | expect(logger).not.toHaveBeenCalled() 28 | }) 29 | 30 | it('should respond with 500 status `error` when some checks are failing', async () => { 31 | server.register({ 32 | plugin: healthCheck, 33 | options: { 34 | path: '/', 35 | logger, 36 | checks: [() => Promise.resolve(), () => Promise.reject(err)], 37 | }, 38 | }) 39 | 40 | const err = new Error('dependency error') 41 | const response = await makeRequest(server.listener) 42 | expect(response.statusCode).toEqual(500) 43 | expect(response.body).toEqual({ 44 | error: 'Internal Server Error', 45 | message: 'An internal server error occurred', 46 | statusCode: 500, 47 | }) 48 | expect(logger).toHaveBeenCalledWith(err, 'health check failed') 49 | }) 50 | 51 | it('should respond with 503 status `error` when shutdown signal is received', async () => { 52 | server.register({ 53 | plugin: healthCheck, 54 | options: { 55 | path: '/', 56 | logger, 57 | }, 58 | }) 59 | 60 | let response = await makeRequest(server.listener) 61 | expect(response.statusCode).toEqual(200) 62 | expect(response.body).toEqual({ status: 'ok' }) 63 | expect(logger).not.toHaveBeenCalled() 64 | 65 | process.emit('SIGTERM', 'SIGTERM') 66 | 67 | response = await makeRequest(server.listener) 68 | expect(response.statusCode).toEqual(503) 69 | expect(response.body).toEqual({ 70 | error: 'Service Unavailable', 71 | message: 'service is shutting down', 72 | statusCode: 503, 73 | }) 74 | expect(logger).not.toHaveBeenCalled() 75 | }) 76 | }) 77 | -------------------------------------------------------------------------------- /examples/koa/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const http = require('http') 4 | const { promisify } = require('util') 5 | const { config, catchErrors, logger, middleware, gracefulShutdown } = require('@banzaicloud/service-tools') 6 | const stoppable = require('stoppable') 7 | const Koa = require('koa') 8 | const Router = require('koa-router') 9 | const cfg = require('./config') 10 | 11 | // catch all uncaught exceptions and unhandled promise rejections and exit application 12 | catchErrors([closeResources]) 13 | 14 | // intercept console calls and use built in (pino) logger instead 15 | logger.interceptConsole() 16 | 17 | const { nodeEnv } = config.environment 18 | console.log('starting application', { nodeEnv }) 19 | 20 | // create koa application and router 21 | const app = new Koa() 22 | const router = new Router() 23 | 24 | // create routes 25 | router.get('/', (ctx) => { 26 | ctx.status = 200 27 | }) 28 | router.get('/metrics', middleware.koa.prometheusMetrics()) 29 | router.get( 30 | '/health', 31 | middleware.koa.healthCheck([ 32 | async () => { 33 | // fake check 34 | return new Promise((resolve, reject) => { 35 | if (Math.random() < 0.2) { 36 | return reject(new Error('check failed')) 37 | } 38 | 39 | resolve() 40 | }) 41 | }, 42 | ]) 43 | ) 44 | 45 | // register middleware 46 | app.use(middleware.koa.errorHandler()) 47 | app.use(middleware.koa.requestLogger()) 48 | app.use(router.routes()) 49 | app.use(router.allowedMethods()) 50 | 51 | // use `stoppable` to stop accepting new connections and closes existing, 52 | // idle connections(including keep - alives) without killing requests that are in-flight 53 | // on .stop() call 54 | const server = stoppable(http.createServer(app.callback())) 55 | // start server 56 | server.listen(cfg.server.port) 57 | 58 | server.once('listening', () => { 59 | const { port } = server.address() 60 | console.log(`server is listening on port ${port}`) 61 | }) 62 | 63 | server.once('error', (err) => { 64 | console.error('server error', err) 65 | process.exit(1) 66 | }) 67 | 68 | // close resources on error and stop signal 69 | var closeServer = promisify(server.stop).bind(server) 70 | async function closeResources() { 71 | // handle ongoing requests and close server 72 | if (closeServer) { 73 | console.log('close server') 74 | await closeServer() 75 | } 76 | // ... close databases, message queues and other resources 77 | } 78 | 79 | // gracefully handle application stop (on SIGTERM & SIGINT) 80 | gracefulShutdown([closeResources]) 81 | -------------------------------------------------------------------------------- /src/middleware/koa/health-check.spec.ts: -------------------------------------------------------------------------------- 1 | import * as http from 'http' 2 | import * as Koa from 'koa' 3 | import makeRequest from '../../helper/make-request' 4 | import { healthCheck } from './' 5 | 6 | describe('koa health check middleware', () => { 7 | const logger: any = jest.fn((...args: any[]) => undefined) 8 | 9 | let app: Koa 10 | beforeEach(() => { 11 | app = new Koa() 12 | }) 13 | 14 | it('should respond with 200 status `ok` when all checks are passing', async () => { 15 | app.use(healthCheck([() => Promise.resolve()], { logger })) 16 | 17 | const server = http.createServer(app.callback()) 18 | const response = await makeRequest(server) 19 | expect(response.statusCode).toEqual(200) 20 | expect(response.body).toEqual({ status: 'ok' }) 21 | expect(logger).not.toHaveBeenCalled() 22 | }) 23 | 24 | it('should respond with 500 status `error` when some checks are failing', async () => { 25 | const err = new Error('dependency error') 26 | app.use(healthCheck([() => Promise.resolve(), () => Promise.reject(err)], { logger })) 27 | 28 | const server = http.createServer(app.callback()) 29 | const response = await makeRequest(server) 30 | expect(response.statusCode).toEqual(500) 31 | expect(response.body).toEqual({ status: 'error' }) 32 | expect(logger).toHaveBeenCalledWith(err, 'health check failed') 33 | }) 34 | 35 | it('should respond with 503 status `error` when shutdown signal is received', async () => { 36 | app.use(healthCheck([() => Promise.resolve()], { logger })) 37 | 38 | const server = http.createServer(app.callback()) 39 | let response = await makeRequest(server) 40 | expect(response.statusCode).toEqual(200) 41 | expect(response.body).toEqual({ status: 'ok' }) 42 | expect(logger).not.toHaveBeenCalled() 43 | 44 | process.emit('SIGTERM', 'SIGTERM') 45 | 46 | response = await makeRequest(server) 47 | expect(response.statusCode).toEqual(503) 48 | expect(response.body).toEqual({ status: 'error', details: { reason: 'service is shutting down' } }) 49 | expect(logger).not.toHaveBeenCalled() 50 | }) 51 | 52 | it('should not respond with 503 status `error` when shutdown signal is received (serviceUnavailableOnTermination=false)', async () => { 53 | app.use(healthCheck([() => Promise.resolve()], { logger, serviceUnavailableOnTermination: false })) 54 | 55 | const server = http.createServer(app.callback()) 56 | let response = await makeRequest(server) 57 | expect(response.statusCode).toEqual(200) 58 | expect(response.body).toEqual({ status: 'ok' }) 59 | expect(logger).not.toHaveBeenCalled() 60 | 61 | process.emit('SIGTERM', 'SIGTERM') 62 | 63 | response = await makeRequest(server) 64 | expect(response.statusCode).toEqual(200) 65 | expect(response.body).toEqual({ status: 'ok' }) 66 | expect(logger).not.toHaveBeenCalled() 67 | }) 68 | }) 69 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@banzaicloud/service-tools", 3 | "version": "4.0.6", 4 | "author": "Andras Toth", 5 | "license": "Apache-2.0", 6 | "description": "Node.js service tools for common use cases", 7 | "homepage": "https://github.com/banzaicloud/service-tools#readme", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/banzaicloud/service-tools" 11 | }, 12 | "keywords": [ 13 | "kubernetes", 14 | "microservice", 15 | "koa", 16 | "middleware", 17 | "health", 18 | "check", 19 | "graceful", 20 | "logger", 21 | "prometheus", 22 | "metrics" 23 | ], 24 | "main": "dist/src/index.js", 25 | "types": "dist/src/index.d.ts", 26 | "scripts": { 27 | "build": "tsc --build --clean && tsc --build tsconfig.json", 28 | "test": "npm run lint && npm run unit-test", 29 | "unit-test": "jest", 30 | "fmt": "prettier --find-config-path --write '{src,examples}/**/*.{js,ts,json}' && npm run lint -- --fix", 31 | "lint": "tslint --project tsconfig.json", 32 | "precommit": "pretty-quick --staged && npm test", 33 | "prepush": "npm run build && npm test", 34 | "prepublishOnly": "npm run build && npm run test" 35 | }, 36 | "dependencies": { 37 | "@hapi/boom": "9.1.3", 38 | "joi": "17.4.0", 39 | "got": "11.8.2", 40 | "http-errors": "1.8.0", 41 | "lodash": "4.17.21", 42 | "pino": "6.11.3", 43 | "prom-client": "12.0.0" 44 | }, 45 | "devDependencies": { 46 | "@hapi/hapi": "19.1.1", 47 | "@types/express": "4.17.12", 48 | "@types/hapi__hapi": "19.0.3", 49 | "@types/http-errors": "1.8.0", 50 | "@types/jest": "26.0.23", 51 | "@types/koa": "2.13.3", 52 | "@types/lodash": "4.14.170", 53 | "@types/node": "14.0.23", 54 | "@types/pino": "6.3.8", 55 | "@types/request-promise-native": "1.0.17", 56 | "express": "4.17.1", 57 | "husky": "4.2.5", 58 | "jest": "26.1.0", 59 | "jest-mock-console": "1.1.0", 60 | "koa": "2.13.1", 61 | "prettier": "2.3.2", 62 | "prettier-tslint": "0.4.2", 63 | "pretty-quick": "2.0.1", 64 | "request-promise-native": "1.0.9", 65 | "ts-jest": "26.1.2", 66 | "ts-node": "8.10.2", 67 | "tslint": "6.1.3", 68 | "tslint-config-prettier": "1.18.0", 69 | "typescript": "3.9.6" 70 | }, 71 | "peerDependencies": { 72 | "@hapi/hapi": ">=19.0.0 < 20.0.0", 73 | "express": ">=4.16.3 < 5.0.0", 74 | "koa": ">=2.5.2 < 3.0.0" 75 | }, 76 | "jest": { 77 | "testEnvironment": "node", 78 | "moduleFileExtensions": [ 79 | "ts", 80 | "js" 81 | ], 82 | "transform": { 83 | ".+\\.(ts)$": "ts-jest" 84 | }, 85 | "globals": { 86 | "ts-jest": { 87 | "tsConfig": "tsconfig.json", 88 | "diagnostics": false 89 | } 90 | }, 91 | "testMatch": [ 92 | "**/?(*.)+(spec|test).(ts|js)", 93 | "**/__tests__/*.+(ts|js)" 94 | ], 95 | "resetMocks": true 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2018 Banzai Cloud 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Node.js Service Tools 3 |

4 | 5 |

6 | Prepare your Node.js application for production! 7 |

8 | 9 | 17 | 18 | This library provides common functionalities, like graceful error handling & shutdown, structured JSON logging and several HTTP middleware to make your application truly ready for modern containerised environments, like [Kubernetes](http://kubernetes.io/). 19 | 20 | 21 | 22 | - [Installation](#installation) 23 | - [Usage](#usage) 24 | - [Main exports](#main-exports) 25 | - [`catchErrors(options)`](#catcherrorsoptions) 26 | - [`gracefulShutdown(handlers, options)`](#gracefulshutdownhandlers-options) 27 | - [`logger`](#logger) 28 | - [Use provided logger instead of `console`](#use-provided-logger-instead-of-console) 29 | - [Config](#config) 30 | - [`config.environment`](#configenvironment) 31 | - [`config.pino`](#configpino) 32 | - [Middleware (Koa)](#middleware-koa) 33 | - [`errorHandler(options)`](#errorhandleroptions) 34 | - [`healthCheck(checks, options)`](#healthcheckchecks-options) 35 | - [`prometheusMetrics(options)`](#prometheusmetricsoptions) 36 | - [`requestValidator(options)`](#requestvalidatoroptions) 37 | - [`requestLogger(options)`](#requestloggeroptions) 38 | - [Middleware (Express)](#middleware-express) 39 | - [`errorHandler(options)`](#errorhandleroptions-1) 40 | - [`healthCheck(checks, options)`](#healthcheckchecks-options-1) 41 | - [`prometheusMetrics(options)`](#prometheusmetricsoptions-1) 42 | - [`requestValidator(options)`](#requestvalidatoroptions-1) 43 | 44 | 45 | 46 | ## Installation 47 | 48 | ```sh 49 | npm i @banzaicloud/service-tools 50 | # or 51 | yarn add @banzaicloud/service-tools 52 | ``` 53 | 54 | ## Usage & Examples 55 | 56 | This library is written in TypeScript, refer to the published types or the source code for argument and return types. 57 | 58 | Examples are available for [Express](https://expressjs.com/) and [Koa](https://koajs.com/) frameworks. Check out the _[examples](/examples)_ folder! 59 | 60 | ### Main exports 61 | 62 | #### `catchErrors(options)` 63 | 64 | Catch uncaught exceptions and unhandled Promise rejections. It is not safe to resume normal operation after ['uncaughtException'](https://nodejs.org/api/process.html#process_event_uncaughtexception). 65 | 66 | ```js 67 | const { catchErrors } = require('@banzaicloud/service-tools') 68 | 69 | // ... 70 | 71 | // the handlers return a Promise 72 | // the handlers are called in order 73 | catchErrors([closeServer, closeDB]) 74 | 75 | // the error will be caught and the handlers will be called before exiting 76 | throw new Error() 77 | ``` 78 | 79 | #### `gracefulShutdown(handlers, options)` 80 | 81 | Graceful shutdown: release resources (databases, HTTP connections, ...) before exiting. When the application receives `SIGTERM` or `SIGINT` signals, the close handlers will be called. The handlers should return a `Promise`. 82 | 83 | ```js 84 | const { gracefulShutdown } = require('@banzaicloud/service-tools') 85 | 86 | // ... 87 | 88 | // the handlers return a Promise 89 | // the handlers are called in order 90 | gracefulShutdown([closeServer, closeDB]) 91 | ``` 92 | 93 | #### `logger` 94 | 95 | A [pino](https://github.com/pinojs/pino) structured JSON logger instance configured with [`config.pino`](#config). 96 | 97 | ```js 98 | const { logger } = require('@banzaicloud/service-tools') 99 | 100 | logger.info({ metadata: true }, 'log message') 101 | // > {"level":30,"time":,"msg":"log message","pid":0,"hostname":"local","metadata":true,"v":1} 102 | ``` 103 | 104 | ##### Use provided logger instead of `console` 105 | 106 | Globally overwrite the `console` and use the logger provided by the library to print out messages. 107 | 108 | ```js 109 | const { logger } = require('@banzaicloud/service-tools') 110 | 111 | console.log('log message') 112 | // > log message 113 | 114 | logger.interceptConsole() 115 | 116 | console.log('log message') 117 | // > {"level":30,"time":,"msg":"log message","pid":0,"hostname":"local","v":1} 118 | ``` 119 | 120 | ### Config 121 | 122 | Load configurations dynamically. 123 | 124 | #### `config.environment` 125 | 126 | Uses the `NODE_ENV` environment variable, with accepted values of: production, development, test. 127 | 128 | ```js 129 | const { config } = require('@banzaicloud/service-tools') 130 | // validates the NODE_ENV environment variable 131 | console.log(config.environment) 132 | // > { nodeEnv: 'production' } 133 | ``` 134 | 135 | #### `config.pino` 136 | 137 | Used by the provided [logger](#logger). Uses the `LOGGER_LEVEL` and `LOGGER_REDACT_FIELDS` environment variables. The `LOGGER_LEVEL` can be one of the following: fatal, error, warn, info, debug, trace. `LOGGER_REDACT_FIELDS` is a comma separated list of field names to mask out in the output (defaults to: `'password, pass, authorization, auth, cookie, _object'`). 138 | 139 | ```js 140 | const pino = require('pino') 141 | const { config } = require('@banzaicloud/service-tools') 142 | 143 | const logger = pino(config.pino) 144 | 145 | logger.info({ metadata: true, password: 'secret' }, 'log message') 146 | // > {"level":30,"time":,"msg":"log message","pid":0,"hostname":"local","metadata":true,"password":"[REDACTED]","v":1} 147 | ``` 148 | 149 | ### Middleware (Koa) 150 | 151 | Several middleware for the [Koa](https://koajs.com/) web framework. 152 | 153 | #### `errorHandler(options)` 154 | 155 | Koa error handler middleware. 156 | 157 | ```js 158 | const Koa = require('koa') 159 | const { koa: middleware } = require('@banzaicloud/service-tools').middleware 160 | 161 | const app = new Koa() 162 | 163 | // this should be the first middleware 164 | app.use(middleware.errorHandler()) 165 | ``` 166 | 167 | #### `healthCheck(checks, options)` 168 | 169 | Koa health check endpoint handler. 170 | 171 | ```js 172 | const Koa = require('koa') 173 | const Router = require('koa-router') 174 | const { koa: middleware } = require('@banzaicloud/service-tools').middleware 175 | 176 | // ... 177 | 178 | const app = new Koa() 179 | const router = new Router() 180 | 181 | // the checks return a Promise 182 | router.get('/health', middleware.healthCheck([checkDB])) 183 | 184 | app.use(router.routes()) 185 | app.use(router.allowedMethods()) 186 | ``` 187 | 188 | #### `prometheusMetrics(options)` 189 | 190 | Koa [Prometheus](https://prometheus.io/) metrics endpoint handler. By default it collects some [default metrics](https://github.com/siimon/prom-client#default-metrics). 191 | 192 | ```js 193 | const Koa = require('koa') 194 | const Router = require('koa-router') 195 | const { koa: middleware } = require('@banzaicloud/service-tools').middleware 196 | 197 | // ... 198 | 199 | const app = new Koa() 200 | const router = new Router() 201 | 202 | router.get('/metrics', middleware.prometheusMetrics()) 203 | 204 | app.use(router.routes()) 205 | app.use(router.allowedMethods()) 206 | ``` 207 | 208 | #### `requestValidator(options)` 209 | 210 | Koa request validator middleware. Accepts [Joi](https://github.com/hapijs/joi) schemas for `body` (body parser required), `params` and `query` (query parser required). Returns with `400` if the request is not valid. Assigns validated values to `ctx.state.validated`. 211 | 212 | ```js 213 | const joi = require('joi') 214 | const qs = require('qs') 215 | const Koa = require('koa') 216 | const Router = require('koa-router') 217 | const bodyParser = require('koa-bodyparser') 218 | const { koa: middleware } = require('@banzaicloud/service-tools').middleware 219 | 220 | // ... 221 | 222 | const app = new Koa() 223 | const router = new Router() 224 | 225 | const paramsSchema = joi 226 | .object({ 227 | id: joi 228 | .string() 229 | .hex() 230 | .length(64) 231 | .required(), 232 | }) 233 | .required() 234 | 235 | const bodySchema = joi.object({ name: joi.string().required() }).required() 236 | 237 | const querySchema = joi.object({ include: joi.array().default([]) }).required() 238 | 239 | router.get( 240 | '/', 241 | middleware.requestValidator({ params: paramsSchema, body: bodySchema, query: querySchema }), 242 | async function routeHandler(ctx) { 243 | const { params, body, query } = ctx.state.validated 244 | // ... 245 | } 246 | ) 247 | 248 | app.use(bodyParser()) 249 | // query parser 250 | app.use(async function parseQuery(ctx, next) { 251 | ctx.query = qs.parse(ctx.querystring, options) 252 | ctx.request.query = ctx.query 253 | await next() 254 | }) 255 | app.use(router.routes()) 256 | app.use(router.allowedMethods()) 257 | ``` 258 | 259 | #### `requestLogger(options)` 260 | 261 | Koa request logger middleware. Useful for local development and debugging. 262 | 263 | ```js 264 | const Koa = require('koa') 265 | const { koa: middleware } = require('@banzaicloud/service-tools').middleware 266 | 267 | // ... 268 | 269 | const app = new Koa() 270 | 271 | // this should be the second middleware after the error handler 272 | // ... 273 | app.use(middleware.requestLogger()) 274 | ``` 275 | 276 | ### Middleware (Express) 277 | 278 | Several middleware for the [Express](https://expressjs.com/) web framework. 279 | 280 | #### `errorHandler(options)` 281 | 282 | Express error handler middleware. 283 | 284 | ```js 285 | const express = require('express') 286 | const { express: middleware } = require('@banzaicloud/service-tools').middleware 287 | 288 | const app = express() 289 | 290 | // this should be the last middleware 291 | app.use(middleware.errorHandler()) 292 | ``` 293 | 294 | #### `healthCheck(checks, options)` 295 | 296 | Express health check endpoint handler. 297 | 298 | ```js 299 | const express = require('express') 300 | const { express: middleware } = require('@banzaicloud/service-tools').middleware 301 | 302 | // ... 303 | 304 | const app = express() 305 | 306 | // the checks return a Promise 307 | app.get('/health', middleware.healthCheck([checkDB])) 308 | ``` 309 | 310 | #### `prometheusMetrics(options)` 311 | 312 | Express [Prometheus](https://prometheus.io/) metrics endpoint handler. By default it collects some [default metrics](https://github.com/siimon/prom-client#default-metrics). 313 | 314 | ```js 315 | const express = require('express') 316 | const { express: middleware } = require('@banzaicloud/service-tools').middleware 317 | 318 | // ... 319 | 320 | const app = express() 321 | 322 | app.get('/metrics', middleware.prometheusMetrics()) 323 | ``` 324 | 325 | #### `requestValidator(options)` 326 | 327 | Express request validator middleware. Accepts [Joi](https://github.com/hapijs/joi) schemas for `body` (body parser required), `params` and `query`. Returns with `400` if the request is not valid. Assigns validated values to `req`. 328 | 329 | ```js 330 | const joi = require('joi') 331 | const express = require('express') 332 | const { express: middleware } = require('@banzaicloud/service-tools').middleware 333 | 334 | // ... 335 | 336 | const app = express() 337 | 338 | const paramsSchema = joi 339 | .object({ 340 | id: joi 341 | .string() 342 | .hex() 343 | .length(64) 344 | .required(), 345 | }) 346 | .required() 347 | 348 | const bodySchema = joi.object({ name: joi.string().required() }).required() 349 | 350 | const querySchema = joi.object({ include: joi.array().default([]) }).required() 351 | 352 | app.use(express.json()) 353 | app.get( 354 | '/', 355 | middleware.requestValidator({ params: paramsSchema, body: bodySchema, query: querySchema }), 356 | function routeHandler(req, res) { 357 | const { params, body, query } = req 358 | // ... 359 | } 360 | ) 361 | ``` 362 | --------------------------------------------------------------------------------