Skip to content

Commit

Permalink
feat: init
Browse files Browse the repository at this point in the history
  • Loading branch information
dnlup committed Jan 12, 2021
1 parent ef08bec commit 048ec7b
Show file tree
Hide file tree
Showing 11 changed files with 8,449 additions and 1 deletion.
18 changes: 18 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
- package-ecosystem: "npm" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "daily"
open-pull-requests-limit: 10

- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
open-pull-requests-limit: 10
41 changes: 41 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: Tests

on:
push:
branches:
- next
pull_request:
branches:
- '*'

env:
CI: true

jobs:
test:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
node-version: [10.x, 12.x, 14.x]

runs-on: ${{ matrix.os }}

steps:
- uses: actions/checkout@v2

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/[email protected]
with:
node-version: ${{ matrix.node-version }}

- name: Install
run: npm ci

- name: Lint
run: npm run lint

- name: Run tests
run: npm run test:ci

- name: Coverage report
uses: codecov/codecov-action@v1
42 changes: 42 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Logs
logs
*.log
npm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Dependency directories
node_modules/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

*.swp

.clinic
15 changes: 15 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
ISC License

Copyright (c) 2021, Daniele Belardi

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
124 changes: 123 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,124 @@
# fastify-doc
A Fastify plugin for sampling process metrics.

[![npm version](https://badge.fury.io/js/%40dnlup%2Ffastify-doc.svg)](https://badge.fury.io/js/%40dnlup%2Ffastify-doc)
![Tests](https://github.com/dnlup/fastify-traps/workflows/Tests/badge.svg)
[![codecov](https://codecov.io/gh/dnlup/fastify-doc/branch/next/graph/badge.svg?token=EX89KNVVSY)](https://codecov.io/gh/dnlup/fastify-doc)

> A Fastify plugin for sampling process metrics.
It uses the module [`@dnlup/doc`](https://github.com/dnlup/doc) behind the scenes.

It decorates the `Fastify` instance with a [`Sampler`](https://github.com/dnlup/doc#class-docsampler)
instance that you can use to get process metrics.

A new sample of the metrics is available when the `Sampler` emits a `sample` event.

See [`@dnlup/doc`](https://github.com/dnlup/doc#class-docsampler)
documentation for more details.

<!-- toc -->

- [Install](#install)
- [Usage](#usage)
* [Register in the same context](#register-in-the-same-context)
* [Register in an encapsulated context](#register-in-an-encapsulated-context)
* [Plugin options](#plugin-options)
- [Decorators](#decorators)
* [`metrics`](#metrics)
- [Hooks](#hooks)
* [`onClose`](#onclose)
- [License](#license)

<!-- tocstop -->

## Install

```bash
npm i @dnlup/fastify-doc
```

## Usage

### Register in the same context

> Uses [fastify-plugin](https://github.com/fastify/fastify-plugin) and it's the most common registration method.
```js
const fastify = require('fastify')()
const plugin = require('@dnlup/fastify-doc')

fastify.register(plugin.register)

fastify.metrics.on('sample', () => {
// sendCpuUsage(fastify.metrics.cpu.usage)
// ...send other metrics as well
})

fastify.get('/', (request, reply) => {
reply.send({ ok: true })
})

fastify.listen(3000)
```

### Register in an encapsulated context

> If you don't want to expose this plugin to the outer context.
```js
const fastify = require('fastify')()
const { plugin } = require('@dnlup/fastify-doc')

fastify.register(function myCustomPlugin (instance, opts, done) {
const myOpts = {}
instance.register(plugin, myOpts)
// ...my custom logic
instance.metrics.on('sample', () => {
// sendCpuUsage(fastify.metrics.cpu.usage)
// ...send other metrics as well
})
done()
})

fastify.get('/', (request, reply) => {
reply.send({ ok: true })
})

fastify.listen(3000)
```

### Plugin options

The options are the same of [`@dnlup/doc`](https://github.com/dnlup/doc#docoptions) (reported here for convenience):

* `options` `<Object>`
* `sampleInterval` `<number>`: sample interval (ms) to get a sample. On each `sampleInterval` ms a [`sample`](#event-sample) event is emitted. **Default:** `500` on Node < 11.10.0, `1000` otherwise. Under the hood the package uses [`monitorEventLoopDelay`](https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html#perf_hooks_perf_hooks_monitoreventloopdelay_options) when available to track the event loop delay and this allows to increase the default `sampleInterval`.
* `autoStart` `<boolean>`: start automatically to collect metrics. **Default:** `true`.
* `unref` `<boolean>`: [unref](https://nodejs.org/dist/latest-v12.x/docs/api/timers.html#timers_timeout_unref) the timer used to schedule the sampling interval. **Default:** `true`.
* `eventLoopOptions` `<Object>`: Options to setup [`monitorEventLoopDelay`](https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html#perf_hooks_perf_hooks_monitoreventloopdelay_options). **Default:** `{ resolution: 10 }`
* `collect` `<Object>`: enable/disable the collection of specific metrics.
* `cpu` `<boolean>`: enable cpu metric. **Default:** `true`.
* `resourceUsage` `<boolean>`: enable [resourceUsage](https://nodejs.org/docs/latest-v12.x/api/process.html#process_process_resourceusage) metric. **Default:** `false`.
* `eventLoopDelay` `<boolean>`: enable eventLoopDelay metric. **Default:** `true`.
* `eventLoopUtilization` `<boolean>`: enable [eventLoopUtilization](https://nodejs.org/docs/latest-v14.x/api/perf_hooks.html#perf_hooks_performance_eventlooputilization_utilization1_utilization2) metric. **Default:** `true` on Node versions that support it.
* `memory` `<boolean>`: enable memory metric. **Default:** `true`.
* `gc` `<boolean>`: enable garbage collection metric. **Default:** `false`.
* `activeHandles` `<boolean>`: enable active handles collection metric. **Default:** `false`.

## Decorators

### `metrics`

* [`<Sampler>`](https://github.com/dnlup/doc#class-docsampler)

A `Sampler` instance.

## Hooks

### `onClose`

Stops the `Sampler` instance when closing the server.

## License

[ISC](./LICENSE)
7 changes: 7 additions & 0 deletions husky.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const tasks = list => list.join(' && ')

module.exports = {
hooks: {
'pre-commit': tasks(['lint-staged', 'npm test'])
}
}
24 changes: 24 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict'

const fp = require('fastify-plugin')
const doc = require('@dnlup/doc')

function plugin (fastify, opts, done) {
try {
const sampler = doc(opts)
fastify.decorate('metrics', sampler)
fastify.addHook('onClose', (instance, done) => {
sampler.stop()
done()
})
done()
} catch (error) {
done(error)
}
}

exports.plugin = plugin
exports.register = fp(plugin, {
fastify: '^3.0.0',
name: '@dnlup/fastify-doc'
})
7 changes: 7 additions & 0 deletions lint-staged.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
'*.md': filenames => {
const list = filenames.map(filename => `'markdown-toc -i ${filename}`)
return list
},
'*.js': ['standard --fix']
}
Loading

0 comments on commit 048ec7b

Please sign in to comment.