{"id":17300461,"url":"https://github.com/atomantic/hapi-and-healthy","last_synced_at":"2025-04-14T07:08:25.919Z","repository":{"id":20362704,"uuid":"23637893","full_name":"atomantic/hapi-and-healthy","owner":"atomantic","description":"🚦Fully Configurable Health Status API for Hapi Servers","archived":false,"fork":false,"pushed_at":"2023-02-27T19:27:32.000Z","size":1497,"stargazers_count":34,"open_issues_count":9,"forks_count":11,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-14T07:08:20.684Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/atomantic.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-09-03T21:18:19.000Z","updated_at":"2025-03-18T02:03:10.000Z","dependencies_parsed_at":"2024-06-18T18:51:30.239Z","dependency_job_id":null,"html_url":"https://github.com/atomantic/hapi-and-healthy","commit_stats":{"total_commits":132,"total_committers":13,"mean_commits":"10.153846153846153","dds":0.446969696969697,"last_synced_commit":"8c0295d2f20f75a6634d44d1410d8c949bf40cf3"},"previous_names":[],"tags_count":50,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atomantic%2Fhapi-and-healthy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atomantic%2Fhapi-and-healthy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atomantic%2Fhapi-and-healthy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atomantic%2Fhapi-and-healthy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/atomantic","download_url":"https://codeload.github.com/atomantic/hapi-and-healthy/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248837281,"owners_count":21169374,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-15T11:28:42.905Z","updated_at":"2025-04-14T07:08:25.893Z","avatar_url":"https://github.com/atomantic.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# \\\\[.\\_.]/ - Hapi and Healthly API\n\n[![](http://img.shields.io/npm/dm/hapi-and-healthy.svg?style=flat)](https://www.npmjs.org/package/hapi-and-healthy)\n[![](http://img.shields.io/npm/v/hapi-and-healthy.svg?style=flat)](https://www.npmjs.org/package/hapi-and-healthy)\n[![](http://img.shields.io/codeclimate/github/atomantic/hapi-and-healthy.svg?style=flat)](https://codeclimate.com/github/atomantic/hapi-and-healthy)\n[![](http://img.shields.io/travis/atomantic/hapi-and-healthy.svg?style=flat)](https://travis-ci.org/atomantic/hapi-and-healthy)\n[![](http://img.shields.io/david/atomantic/hapi-and-healthy.svg?style=flat)](https://www.npmjs.org/package/hapi-and-healthy)\n\n\n\u003e Version 6.x.x only supports hapi v17 and above!\n\nThis [Hapi.js](https://www.npmjs.org/package/hapi) plugin provides a configurable route for `/service-status` (`/health`) API reporting which returns a varied output depending on the consumer headers, request type and query flags.\n\n\nThe primary consumer is a Local Traffic Manager (LTM), which load balances and adds/removes nodes from rotation based on the API return status. You can add an arbitrary number of tests to the test.node array (in config), which will run in parallel and report basic health status for your node. Keep in mind that an LTM will hit this API every 1-10 seconds so the test functions should run really fast. Caching policy and what those tests actual are is entirely up to the application :)\n\n\n\u003e NOTE: failing dependecy services should never cause your node to be marked bad (lest you cascade failures down the chain--and remove your entire app stack from the node pool). Your tests should only validate that your node is configured and running correctly (otherwise, an LTM would remove a good node out of the pool only because another service went down).\n\nA secondary consumer is a DevOps maintainer who wants to see the status of the service and get more detailed information on what's going on with it.\n\nExamples:\n\n- what version/checksum/hash/`git rev-parse HEAD` is actually running (does it match the deployment manifest)?\n- what environment is the node configured to run (DEV, QA, STAGE, PROD, etc)?\n- what remote service environments is it setup to use (DEV, QA, STAGE, PROD, etc)?\n- what  what memcached servers are loaded in the pool?\n- why is it marked as good, bad or in a warning state (useful messages)?\n- how does the CPU/memory look on this node?\n- etc...\n\nQuery flags are available for verbose output (`?v`) to machines and humans. This API will report cpu and memory load for the system and for the hapi server process itself. The human friendly flag (`?v\u0026h`) converts values from bytes to KB/MB/GB and usage to percentage of the system rather than flat values\n\n\n## Installation:\n\n```\nnpm i -S hapi-and-healthy\n```\n\n## Demo:\n\nRun the demo to see it in action and view the demo.js file for the code\n```\ngit clone git@github.com:atomantic/hapi-and-healthy.git\ncd hapi-and-healthy;\nnpm i;\nnpm test;\n```\n\n## Tests:\n\nYou can run tests with `npm test`\n![](https://raw.githubusercontent.com/atomantic/hapi-and-healthy/master/docs/tests.png)\n\n## Configuration Options\n\n- `auth` - (`string`|false) The name of the auth strategy (default is false)\n- `custom` - (`object`) Additional custom data to return (e.g. custom:{memcached:memcached.servers})\n- `defaultContentType` - (`string`) Default content type for requests (defaults to `text/plain`)\n- `env` - (`string`) The running environment of your app (e.g. `DEV`, `QA`, `STAGE`, `PROD`). This will be returned in verbose output for consumers wishing to know what environment your service thinks it's running in.\n- `id` - (`string`) An ID of the state of this system, like a checksum (default: '[no id provided]')\n- `lang` - (`string`) Default 'en' a language override for the human output health data. This endpoint uses the [Humanize Duration package](https://www.npmjs.org/package/humanize-duration) so any valid language override for that library will be valid here (`fr`, `de`, `ko`, etc)\n- `name` - (`string`) The name of your service (reported in verbose mode), probably supplied by your package.json\n- `path` - (`string`) An override path for the default `'/service-status'` endpoint\n- `paths` - (`array`) A list of available versioned paths on this service (e.g. [\"v1\", \"v2\"]). This can be used for automated discovery of versioned endpoints deployed on this service (e.g. for detecting the location of a /v2/feature-status API endpoint)\n- `schema` - (`string`) Schema version number (defualts to 1.1.0 -- the schema version of this library)\n- `tags` - (`array`) Hapi Route tags for your status API (defaults to `['api', 'health', 'status']`)\n- `test.node` - (`array`) A set of Promises to run for testing your node health\n  - each Promise should resolve an error or success\n  - `message` is an optional mixed value (json or string) that will give more info about that status\n- `test.features` - (`array`) A set of Promises to run for testing optional features and dependencies. Ideally this would be a query on a file dump of a smoke test that gets run periodically to test each of the API endpoints or features of your service. It could also be a check to memcached for logs of known errors in the system (counter of unhandledException, cached by API path or flow, etc).\n  - `message` is an optional mixed value (json or string) that will give more info about that status\n- `usage` - (`boolean`) - show usage/health information (cpu, memory, etc). Default: true\n- `version` - (`string`) - the version of your service (probably from your package.json)\n\n### Example\n\n```javascript\n\nconst Hapi = require('hapi')\n// Hapi Server\nconst server = Hapi.createServer({\n    host: 'locahost',\n    port: 3192\n})\n\n// capture app ENV\nconst env = process.env.NODE_ENV||'DEV'\n\n// node os (for test example)\nconst os = require('os')\n\n// local memcached (for test example)\nconst Memcached = require('memcached')\nconst memcached = new Memcached('localhost:11211')\n\n// example app-specific module for feature testing\n// we have a content engine for keeping the site content up-to-date (see feature tests below)\nconst content = require('./lib/content')\n\nconst pjson = require('./package')\n\n// Register the plugin with custom config\nserver.register([{\n  plugin: require(\"hapi-and-healthy\"),\n  options: {\n    custom: {\n        // let's just say we want to keep an eye on the memcached pool\n        memcached: memcached.servers\n    },\n    env: env,\n    name: pjson.name,\n    test:{\n      // a series of tests that run in async parallel\n      // if any one of them fails, it returns immediately to the async callback\n      // which tells the API to reply with the failure.\n      node:[\n        // TEST 1: validate the version of this codebase matches release for this ENV\n        () =\u003e new Promise((resolve, reject) =\u003e {\n          // check the release version against current codebase.\n          // At deploy time, we update memcache with the release version for this env\n          // using a deploy script (stored under 'app_version_'+env)\n          memcached.get('app_version_'+env,function(err,data){\n            if(err) return cb(true, err)\n\n            if(data!==pjson.version){\n              // this codebase does not match our release manifest\n              // don't allow it in rotation\n              reject('version mismatch. Expected version is '+data+' but running '+pjson.version)\n            }\n            // ok, all good on this check\n            resolve('matches expected version ('+pjson.version+')')\n          })\n        })\n      ],\n      features:[\n        () =\u003e new Promise((resolve, reject) =\u003e {\n          // let's say we have a content directory that we use a tool like chef to\n          // dump onto the running node from a github repo\n          // this is a seperate dependency from the node\n          // whenever the app loads a new hash of the content\n          // (via fs.watch on the .git repo for the content directory)\n          // it updates memcached with the new hash for content.\n          // Our status page will check memcached from our running app's idea of the current\n          // content hash. If it's not a match then this node is out of date\n          // and we want to flag it in a WARN state (but not pull the node out of rotation).\n          memcached.get('content_hash',function(err, data){\n            // console.log('memcached found', err, data);\n            if(err){\n                reject('memcached error: '+err)\n            }\n            if(data!==content.hash){\n              // latest memcached version is different from this node's\n              // idea of what the content version is\n              // which means this node is behind other nodes\n              reject('content has fallen behind other nodes: '+content.hash+'(app) vs '+data+' (memcached)')\n            }\n            resolve('content matches other nodes')\n          })\n        })\n      ]\n    },\n    version: pjson.version\n  }\n}])\n.then(() =\u003e server.start())\n```\n\n## API\n\n- The API endpoint is configurable but defaults to `/service-status`\n- Additionally, the following query params are allowed:\n    - `v` - verbose mode\n    - `h` - human friendly mode\n- GET requests supplied with header `If-None-Match: {etag}` will return 304 not modified and empty body if the etag (base64 encode of status output minus published date) is a match\n\n## Spec\n\n\n### `/service-status`\nreturns simple health check for LTM (Local Traffic Manager) monitoring.\n\nThis route will enforce auth:false since the LTM needs to hit this so frequently and it does\nnot expose sensitive data\n\nIf the node fails any of the test functions supplied in `options.test.node`\n```\n⇒  curl -i -H \"Accept: text/plain\" http://127.0.0.1:3192/service-status\nHTTP/1.1 500 Internal Server Error\ncontent-type: text/plain; charset=utf-8\ncontent-length: 3\ncache-control: no-cache\nDate: Wed, 03 Sep 2014 23:16:54 GMT\nConnection: keep-alive\n\nBAD%\n```\n\nOR, if the node passes all the LTM tests supplied in `options.test.node`\n```\n⇒  curl -i -H \"Accept: text/plain\" http://127.0.0.1:3192/service-status\nHTTP/1.1 200 OK\ncontent-type: text/plain; charset=utf-8\ncontent-length: 4\ncache-control: no-cache\naccept-ranges: bytes\nDate: Wed, 03 Sep 2014 23:16:33 GMT\nConnection: keep-alive\n\nGOOD%\n```\n\nOR, if the node passes all the LTM tests supplied in `options.test.node`\nBUT, it did not pass all of the feature tests supplied in `options.test.features`\n(still returns 200 to keep node in rotation, but flags this node in WARN state)\n```\n⇒  curl -i -H \"Accept: text/plain\" http://127.0.0.1:3192/service-status\nHTTP/1.1 200 OK\ncontent-type: text/plain; charset=utf-8\ncontent-length: 4\ncache-control: no-cache\naccept-ranges: bytes\nDate: Wed, 03 Sep 2014 23:16:33 GMT\nConnection: keep-alive\n\nWARN%\n```\n\n### `/service-status?v`\nruns full, verbose suite of health checks and returns machine friendly output\n\n```json\n{\n  \"service\": {\n    \"env\": \"DEV\",\n    \"id\": \"98CF189C-36E0-416B-A2ED-90CE36F8D330\",\n    \"name\": \"my_service\",\n    \"version\": \"1.0.0\",\n    \"custom\": {\n      \"health\": {\n        \"cpu_load\": [\n          1.619140625,\n          1.732421875,\n          1.88818359375\n        ],\n        \"mem_free\": 354811904,\n        \"mem_free_percent\": 0.02065277099609375,\n        \"mem_total\": 17179869184,\n        \"os_uptime\": 606723\n      }\n    },\n    \"schema\": \"1.0.0\",\n    \"status\": {\n      \"state\": \"GOOD\",\n      \"message\": [\n        \"checksum matches manifest\",\n        \"content matches other nodes\"\n      ],\n      \"published\": \"2014-09-24T03:27:59.575Z\"\n    }\n  }\n}\n\n\n```\n\n\n### `/service-status?v\u0026h`\nruns full, verbose suite of health checks and returns human friendly output\n```json\n{\n  \"service\": {\n    \"env\": \"DEV\",\n    \"id\": \"98CF189C-36E0-416B-A2ED-90CE36F8D330\",\n    \"name\": \"my_service\",\n    \"version\": \"1.0.0\",\n    \"custom\": {\n      \"health\": {\n        \"cpu_load\": [\n          2.263671875,\n          2.107421875,\n          2.05810546875\n        ],\n        \"mem_free\": \"464.19 MB\",\n        \"mem_free_percent\": \"0.03%\",\n        \"mem_total\": \"17.18 GB\",\n        \"os_uptime\": \"10 minutes, 7.686 seconds\"\n      }\n    },\n    \"schema\": \"1.0.0\",\n    \"status\": {\n      \"state\": \"GOOD\",\n      \"message\": [\n        \"checksum matches manifest\",\n        \"content matches other nodes\"\n      ],\n      \"published\": \"2014-09-24T03:27:59.575Z\"\n    }\n  }\n}\n```\n\n## Support\nHey dude! Help me out for a couple of :beers:!\n\n[![Beerpay](https://beerpay.io/atomantic/hapi-and-healthy/badge.svg?style=beer-square)](https://beerpay.io/atomantic/hapi-and-healthy)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatomantic%2Fhapi-and-healthy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fatomantic%2Fhapi-and-healthy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatomantic%2Fhapi-and-healthy/lists"}