Skip to content

Commit

Permalink
[v1.0.0] update docs (#2)
Browse files Browse the repository at this point in the history
* fix docs

* docs: update description of `status`

* docs: update informations in README.md

* chore: update deps and add changelog

* docs: update docs to use this package

* docs: update readme instructions

* 📖 fix typos
  • Loading branch information
gritzkoo authored Feb 22, 2023
1 parent d38bb54 commit 4b234fc
Show file tree
Hide file tree
Showing 7 changed files with 2,023 additions and 1,358 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 16.x]
node-version: [14.x, 16.x, 18.x]
steps:
- name: Git checkout
uses: actions/checkout@v2
Expand Down Expand Up @@ -113,7 +113,7 @@ jobs:
- build
- validate
runs-on: ubuntu-latest
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
Expand Down
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Nodejs Healthchecker lightweight

___

## `[v1.0.0] 2023-02-21`

### Added

- first release

### Removed

- N/A

### Notes

- N/A

___
240 changes: 169 additions & 71 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,75 +14,24 @@
[![Languages Status](https://img.shields.io/github/languages/count/gritzkoo/nodejs-health-checker-lw)](https://img.shields.io/github/languages/count/gritzkoo/nodejs-health-checker-lw)
[![Repo Size Status](https://img.shields.io/github/repo-size/gritzkoo/nodejs-health-checker-lw)](https://img.shields.io/github/repo-size/gritzkoo/nodejs-health-checker-lw)
</div>
____

A successor package for [nodejs-health-checker](https://github.com/gritzkoo/nodejs-health-checker) to simplify health checks.

The main purpose of this package is to standardize the liveness and readiness actions for Nodejs applications, for Kubernetes deployments.

## How to install

```sh
npm i --save nodejs-health-checker-lw
```

OR
## contributors

```sh
yarn add nodejs-health-checker-lw
```

## Creating your own checkers

It's important to keep in mind that you need to create the tests you API needs as the example below:
![contributors](https://contrib.rocks/image?repo=gritzkoo/nodejs-health-checker-lw)
>Made with [contributors-img](https://contrib.rocks).
____

```ts
// file /app/src/github.ts
import { Check } from 'nodejs-health-checker-lw'
import 'fetch' from 'node-fetch'

export const MyIntegrationTest = async(): Promise<Check> => {
const check = new Check({url: 'https://github.com/status'})
fetch(check.url,{
timeout: 10
}).then( response => {
check.status = response.status === 200;
check.error = response.status !== 200 ? { http_status: response.status } : undefined,
resolve(check)
}).catch( error => {
check.error = error
resolve(check)
})
}
```
A successor package for [nodejs-health-checker](https://github.com/gritzkoo/nodejs-health-checker) to simplify health checks.

## How to init
The main purpose of this package is to substitute `nodejs-health-checker` package and standardize the liveness and readiness actions for Nodejs applications running in Kubernetes deployments, without adding complexity and extra package installs.

```ts
import { HealthChecker, Check } from 'nodejs-health-checker-lw'
import { MyIntegrationTest } from 'src/github'
export const check = new HealthChecker({
name: 'myapp',
version: 'v1.0.0',
// integrations are the list of outside integrations of your API you need to test
// to guarantee that your service is healthy to work
integrations: [
{
// name is just a string that will help you fast identify the integration you need to check-on
name: 'github integration',
//
handle: MyIntegrationTest
}
}
]
})
```
Read more about migrating from `nodejs-health-checker` or creating your tests in [MIGRATIONS GUIDELINES](docs/MIGRATIONS.md)

___

## Liveness method

Will return an `JSON` as below:
Will return a `JSON` as below:

```json
{
Expand All @@ -93,14 +42,13 @@ Will return an `JSON` as below:

## Readiness method

Will return an `JSON` as below:
Will return a `JSON` as below:
>The `status` prop will return true once all your integrations works. If one of then fails, this `status` prop will reflect that something went wrong and you need to check the `status` inside `integrations` prop
```jsonc
```json
{
"name": "myapp",
"version": "v1.0.0",
// the main status of all integrations
// will return true when none of integrations fails
"status": true,
"date": "2022-07-10T00:46:19.186Z",
"duration": 0.068,
Expand All @@ -117,21 +65,92 @@ Will return an `JSON` as below:

___

## How to install

```sh
npm i --save nodejs-health-checker-lw
```

OR

```sh
yarn add nodejs-health-checker-lw
```

## How to init

First, you `need` to write your test like below:
>this example is using http check for API integrations. Remember that you can write using your own methods and patterns. You need only to return an instance of `nodejs-health-checker Check`.
```ts
// file src/integrations/github.ts
import { Check } from 'nodejs-health-checker-lw'
import { fetch } from 'node-fetch'
export async function TestGithubIntegration() Promise<Check> {
return new Promise((resolve, _) => {
let result = new Check({ url: 'https://github.com/status' })
// call a url to test connectivity and HTTP status
fetch(result.url, { timeout: 10000 })
.then(response => {
if (response.status !== 200) {
result.error = {
status: response.status,
body: response.body
}
}
})
.catch(error => result.error = error)
.finally(() => resolve(result))
})
}

```

Then in your main declarations, you `MUST` create a `const` with `HealthChecker` from `nodejs-health-checker-lw` and fill a few props to create a re-usable pointer to be called after as below.
> Read more about the `version` [in this topic](README.md#version-in-your-healthchecker)
```ts
// file src/healthchecker.ts
import { HealthChecker} from 'nodejs-health-checker-lw'
import { TestGithubIntegration } from 'src/integrations/github' // as the example above. This list can grow as mush as you need
export const check = new HealthChecker({
name: 'myapp', // set your application name
version: 'v1.0.0', // set the version of your application
// integrations are the list of tests that needs to be executed.
integrations: [
{
// set the name of the integration that will be tested
name: 'github integration',
// pass the functions that tests this integration
handle: MyIntegrationTest
}
]
})
```

## How to use it

Once you create a constant with an instance of HealthChecker, you can now call the methods, liveness, and readiness, in your application, in CLI or API mode

### CLI interface

```js
import check from 'src/to/your/check/const'
import check from 'src/healthchecker' // as the example above
const cliArgs = process.argv.slice(2)
switch (cliArgs[0]) {
case 'liveness':
console.log(check.liveness())
break
case 'readiness':
check.readiness().then(response => console.log(response))
check.readiness().then(response => {
if (!response.status) {
// do something like trigger an alarm or log to other obervability stacks
console.warning(JSON.stringify({message: "health check fails", results: response}))
} else {
// or just log OK to track
console.info(JSON.stringify(response));
}
})
break
default:
console.error(`invalid option: ${cliArgs[0]}... accepty only liveness or readiness`)
Expand Down Expand Up @@ -168,31 +187,41 @@ spec:
command:
- "/bin/node"
- "your-script.js"
args:
- "liveness"
readinessProbe:
exec:
command:
- "/bin/node"
- "your-script.js"
args:
- "readiness"
```
____
___
## HTTP interface
In `javascript`
In `Javascript`

```js
```ts
import express from 'express'
import check from 'src/to/your/check/const'
import check from 'src/healthchecker' // as the example above
const PORT = process.env.PORT||80;
const server = express()
server.get('/health-check/liveness', (_, res) => {
res.json(check.liveness())
})
server.get('/health-check/readiness', async (_, res) => {
res.json(await check.readiness())
const result = await check.readiness()
if (!response.status) {
// do something like trigger an alarm or log to other obervability stacks
console.warning(JSON.stringify({message: "health check fails", results: response}))
} else {
// or just log OK to track
console.info(JSON.stringify(response));
}
res.json(result)
})
server.listen(PORT, () => {
console.log(`[SERVER] Running at http://localhost:${PORT}`);
Expand Down Expand Up @@ -234,4 +263,73 @@ spec:
port: http
```
____
It's important to share that you `MUST` return always an `OK` status in Kubernetes liveness and readiness because if one of your integration fails, this can teardown all of your pods and make your application unavailable. Use other observability stacks like `Zabbix` or `Grafana alarms` to track your application logs and then take actions based on observability! `(I learned it by the hard way =/ )`

___

## More pieces of information

___

### Version in your `HealthChecker`

I highly recommend you fill this prop using a dynamic file content loading like:

- reading the `package.json` file and using the `version` value to fill the `HealthChecker.version` placeholder like below:

```ts
import fs from 'fs'
import path from 'path'
import { HealthChecker } from 'nodejs-health-checker-lw'
import { TestGithubIntegration } from 'src/integrations/github'
const versionFilePath = path('package.json')
const file = {
content: null
error: undefined
}
try {
let tmpRawData = await fs.readFileSync(versionFilePath, {encoding: 'utf8'})
file.content = JSON.parse(tmpRawData)
} catch (error) {
file.error = error
}
export const check = new HealthChecker({
name: 'myapp',
version: file.error || file.content.version
integrations: [/*and the list of your integrations here*/]
})
```

- creating a file like `version.txt` using a command like the below in the pipeline before a `docker build/push` steps:

```sh
git show -s --format="%ai %H %s %aN" HEAD > version.txt
```

then use it in your code like:

```ts
import fs from 'fs'
import path from 'path'
import { HealthChecker } from 'nodejs-health-checker-lw'
import { TestGithubIntegration } from 'src/integrations/github'
const versionFilePath = path('version.txt')
const file = {
content: null
error: undefined
}
try {
file.content = await fs.readFileSync(versionFilePath, {encoding: 'utf8'})
} catch (error) {
file.error = error
}
export const check = new HealthChecker({
name: 'myapp',
version: file.error || file.content
integrations: [/*and the list of your integrations here*/]
})
```
Loading

0 comments on commit 4b234fc

Please sign in to comment.