Compare commits
352 commits
Author | SHA1 | Date | |
---|---|---|---|
|
1a35138ed2 | ||
|
898adfbdc9 | ||
|
c1cbbc07ab | ||
|
709f74baf8 | ||
|
c09be24f0f | ||
|
50fd37ef54 | ||
|
3b582ea7b8 | ||
|
3fed2ecf7d | ||
|
58e71351ab | ||
|
a0a8f7301f | ||
|
9e789fc347 | ||
|
5925fedb53 | ||
|
f382e4e9a8 | ||
|
11f69ceb55 | ||
|
2849cd732c | ||
|
92f92e81fd | ||
|
99e03d73d0 | ||
|
ef35642f10 | ||
|
c37fad86f6 | ||
|
1349b4da25 | ||
|
c5c1434c77 | ||
|
26188855bb | ||
|
4f80e744b2 | ||
|
dac42d5ead | ||
|
3589832ad6 | ||
|
54cf7f5f24 | ||
|
b73f025548 | ||
|
fce96663db | ||
|
064d09ff70 | ||
|
af0296b7b3 | ||
|
3079103d03 | ||
|
3f15bae6a8 | ||
|
f72862b955 | ||
|
3bd5d1da4d | ||
|
9f94d50f1e | ||
|
cedf9b7af7 | ||
|
2b093b0fa2 | ||
|
ac5eb866d8 | ||
|
c0654ce76f | ||
|
52857f987c | ||
|
37246fa512 | ||
|
06222b4846 | ||
|
73d4b44522 | ||
|
9df9d347ad | ||
|
9379ec63fa | ||
|
0e29b88c32 | ||
|
2363bf25c4 | ||
|
d5b3fbdbb1 | ||
|
c36a5af463 | ||
|
2b859d8322 | ||
|
06c48fb317 | ||
|
a72d5948ab | ||
|
440b8455d3 | ||
|
fcb3767093 | ||
|
40c0a61ba6 | ||
|
9d9fbfb6b7 | ||
|
96084208bf | ||
|
60373593bf | ||
|
84b75d8c24 | ||
|
f7a753a86d | ||
|
cc162d9a56 | ||
|
704a353667 | ||
|
fc838ad93e | ||
|
303f397c83 | ||
|
72e7d6310d | ||
|
8425ab99db | ||
|
455844a4ed | ||
|
e5d9b7bfb9 | ||
|
fdbcfc27cf | ||
|
2641d455c1 | ||
|
d15fcfe557 | ||
|
2466225145 | ||
|
91592d5e21 | ||
|
77169d3f06 | ||
|
366e31ce17 | ||
|
543c130543 | ||
|
b7e0eae52f | ||
|
3d78d1cbc3 | ||
|
bba1ceb04a | ||
|
27d9c954ba | ||
|
3d31ca39ea | ||
|
995cec0974 | ||
|
9fae4246d0 | ||
|
7db8afc51c | ||
|
e0f3d4ca87 | ||
|
3a6fe1390d | ||
|
eca3bff6c3 | ||
|
7b110d609b | ||
|
486587fc86 | ||
|
c54cd9b871 | ||
|
b4210ec85d | ||
|
252fab726a | ||
|
e7343bd194 | ||
|
c4626d0186 | ||
|
03843eacf2 | ||
|
7b0be18923 | ||
|
9ce1163bc0 | ||
|
717b27c4e2 | ||
|
945568d91c | ||
|
ae9dc17e0f | ||
|
c18d79e662 | ||
|
17bcf3d4cf | ||
|
c8b70eeb27 | ||
|
a8c4a19808 | ||
|
05ad26f999 | ||
|
d1cf71869e | ||
|
d2cfdef13a | ||
|
539c202a83 | ||
|
d63f3fb465 | ||
|
6d217c3e95 | ||
|
d3f77a7180 | ||
|
be61660ab7 | ||
|
9126d38fea | ||
|
5515aaf590 | ||
|
2d5ba1d8f1 | ||
|
92155ae9b2 | ||
|
e216174dce | ||
|
dd983f9926 | ||
|
dc4c8d8d39 | ||
|
ec2025b768 | ||
|
c3f519ae4a | ||
|
acfb6e689e | ||
|
ccb89a9889 | ||
|
cb77478841 | ||
|
20b362a90c | ||
|
c392a82084 | ||
|
cbc6d971ac | ||
|
409c477d63 | ||
|
ea238c97f6 | ||
|
5ed6ee7d1e | ||
|
1c57adc4a0 | ||
|
890d1ef780 | ||
|
92f88d1fe9 | ||
|
bad4fa08b5 | ||
|
8646f816fc | ||
|
47eb77c6fd | ||
|
796eec97c2 | ||
|
b4512f25cc | ||
|
c2997d04d5 | ||
|
9c4964c1ae | ||
|
1ead5e54ef | ||
|
c73299f7b1 | ||
|
5d8dee811a | ||
|
d176ad2c9d | ||
|
d1a39d9838 | ||
|
a85bf04d0e | ||
|
0ccc4a8579 | ||
|
719ff9edd1 | ||
|
106daf044b | ||
|
f97a52b0a7 | ||
|
c07b8fdff8 | ||
|
84b23d6b14 | ||
|
9446ff2a16 | ||
|
92594538fa | ||
|
37a8545c5e | ||
|
47a097cc4d | ||
|
b5f8df30d8 | ||
|
df991fe5e5 | ||
|
eba5c42871 | ||
|
87721ec82a | ||
|
d76faf9197 | ||
|
dc71ce5ca4 | ||
|
579e973c66 | ||
|
9ea9576aa2 | ||
|
b88630e1ea | ||
|
82983a2827 | ||
|
0a58df5386 | ||
|
789f0ffea8 | ||
|
3063ea575c | ||
|
ddac01aea3 | ||
|
d4d0f412e4 | ||
|
5e0472c1f6 | ||
|
b254a33d47 | ||
|
b3eea21ecb | ||
|
454e3d1e89 | ||
|
2a578c5d1b | ||
|
0131f8a3f7 | ||
|
9bce041750 | ||
|
6f20f49855 | ||
|
fe6804d1e9 | ||
|
4008da12a8 | ||
|
49291172ac | ||
|
daf064caee | ||
|
ad5fe8b853 | ||
|
970b7129c0 | ||
|
520725ecd9 | ||
|
bcd798a057 | ||
|
9faea4df2c | ||
|
d6ca56b6e5 | ||
|
ab9c4fb17d | ||
|
00ccd46018 | ||
|
705c7f4f4f | ||
|
29801d3f81 | ||
|
8e71014357 | ||
|
e086844f3f | ||
|
80c64cf0e3 | ||
|
3b15f7f37a | ||
|
ac8caabcda | ||
|
cb415fa855 | ||
|
001aaf069a | ||
|
1ff3300a85 | ||
|
55b67bc1dd | ||
|
736cc88149 | ||
|
2f6f6c816c | ||
|
c85023b9d6 | ||
|
0322126616 | ||
|
6fe53182aa | ||
|
a7a39a4a1c | ||
|
9ab7f7f442 | ||
|
9e34c098cc | ||
|
5f25da655a | ||
|
710f2b07e7 | ||
|
93cf430c19 | ||
|
41ae48102c | ||
|
e08596d098 | ||
|
5166af0d25 | ||
|
e9c4c8fb29 | ||
|
540fad5757 | ||
|
891ae81a2c | ||
|
4af4035ce9 | ||
|
9213eb707b | ||
|
a794d7bf39 | ||
|
0df74d8ff0 | ||
|
e480235537 | ||
|
484280f497 | ||
|
5707c03cd4 | ||
|
4b7d9ee94e | ||
|
eddc283983 | ||
|
438ec423c4 | ||
|
a8cc8290e2 | ||
|
d70eb9064a | ||
|
06d74c57ce | ||
|
e99c4c57a2 | ||
|
744cd7ed4c | ||
|
cb8d04a2b2 | ||
|
317b8b598b | ||
|
c9c9ba45eb | ||
|
fe524c1f0a | ||
|
bbc21f4c6e | ||
|
bd17d79c0d | ||
|
de6ff2decd | ||
|
76a3ad9c7f | ||
|
33a7c9d0cf | ||
|
8935a2402c | ||
|
c5f289946c | ||
|
be7210d375 | ||
|
70468821ea | ||
|
cc19c0fe40 | ||
|
b4a263e4e4 | ||
|
f1746e47b3 | ||
|
3c9ecc1f65 | ||
|
67824f6a37 | ||
|
626ff1951b | ||
|
3f405e1a70 | ||
|
0b98217d3b | ||
|
8d16187a0a | ||
|
a850d1cbdf | ||
|
13d3867522 | ||
|
23a891be36 | ||
|
2acb8da732 | ||
|
92070192d8 | ||
|
3e9803c106 | ||
|
e780b319c7 | ||
|
f971f044b6 | ||
|
abba84e44b | ||
|
ed69818d61 | ||
|
64b180c059 | ||
|
482aa769a1 | ||
|
f8d4e43aef | ||
|
82506f8b45 | ||
|
b31833ad61 | ||
|
62f3bea6cb | ||
|
92ed6b139f | ||
|
0c96be8fbe | ||
|
df95319003 | ||
|
c4ce1531cc | ||
|
78d45e770e | ||
|
774a36e38b | ||
|
936301322d | ||
|
57cfe61290 | ||
|
5907f57339 | ||
|
5243d8c68c | ||
|
3657968ce3 | ||
|
b04326d378 | ||
|
5a8f056ef7 | ||
|
a1aa1d775b | ||
|
5e5a9acf9f | ||
|
7429e433cd | ||
|
a8cc0f24c2 | ||
|
b796e657de | ||
|
41afec3769 | ||
|
790e9774a2 | ||
|
a50c464a0f | ||
|
df552b6f3f | ||
|
9dd0b270ec | ||
|
ec77f03f5e | ||
|
4d79aaee71 | ||
|
6bc63894e6 | ||
|
0d1dd28b8b | ||
|
13493b1eb2 | ||
|
70e0d06c95 | ||
|
a556c3aca1 | ||
|
9b41a89059 | ||
|
4fd8e9bdb1 | ||
|
861572d9c2 | ||
|
66a465d351 | ||
|
19131ee9c3 | ||
|
64d6dfe960 | ||
|
a3ac5edee8 | ||
|
c7967e2200 | ||
|
5c59fa3816 | ||
|
7e52448bfe | ||
|
f36112ff9c | ||
|
8a0061428d | ||
|
f30dfe0cee | ||
|
e5b3a90fae | ||
|
d25207923c | ||
|
f45df5d422 | ||
|
65304798de | ||
|
565f423dd9 | ||
|
ccca32d7b2 | ||
|
fa687f635f | ||
|
3282a084a4 | ||
|
df81a1206a | ||
|
1d3452cdb0 | ||
|
7c7673f1c2 | ||
|
97de2f0905 | ||
|
ddc85f5359 | ||
|
600a5bae61 | ||
|
b7364927df | ||
|
cd08a3ecf6 | ||
|
8f2d80a7fb | ||
|
f70de293a5 | ||
|
e791b690aa | ||
|
cc81f5868e | ||
|
3e5006dd5d | ||
|
c24a9731c1 | ||
|
fc1bf8b334 | ||
|
6f7686ba34 | ||
|
261fa74ac9 | ||
|
04706f69d5 | ||
|
2e8f2d0579 | ||
|
9127408d23 | ||
|
b8a4c2c9e6 | ||
|
ce8876793d | ||
|
f8007b55ca | ||
|
edf4e605e5 | ||
|
57e8a4d831 | ||
|
479fbe5727 | ||
|
4fad222b82 | ||
|
34be5bbca2 | ||
|
8102144b85 |
37 changed files with 6978 additions and 4493 deletions
1
.envrc
Normal file
1
.envrc
Normal file
|
@ -0,0 +1 @@
|
|||
use flake
|
|
@ -19,6 +19,8 @@ module.exports = {
|
|||
'import/no-default-export': 'error',
|
||||
'import/no-namespace': 'error',
|
||||
'import/no-useless-path-segments': 'error',
|
||||
'import/no-named-as-default': 0,
|
||||
'no-duplicate-imports': 'error',
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
|
@ -33,6 +35,7 @@ module.exports = {
|
|||
},
|
||||
rules: {
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'error',
|
||||
'@typescript-eslint/consistent-type-imports': ['error', { prefer: 'type-imports' }],
|
||||
},
|
||||
settings: {
|
||||
'import/resolver': {
|
||||
|
|
1
.github/FUNDING.yml
vendored
1
.github/FUNDING.yml
vendored
|
@ -1 +1,2 @@
|
|||
github: lstrojny
|
||||
custom: ["https://paypal.me/larsstrojny"]
|
||||
|
|
9
.github/dependabot.yml
vendored
9
.github/dependabot.yml
vendored
|
@ -3,4 +3,11 @@ updates:
|
|||
- package-ecosystem: npm
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
interval: daily
|
||||
open-pull-requests-limit: 30
|
||||
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 30
|
||||
|
|
71
.github/workflows/build.yml
vendored
71
.github/workflows/build.yml
vendored
|
@ -4,40 +4,83 @@ on: [push, pull_request]
|
|||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-20.04
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# the Node.js versions to build on
|
||||
node-version: [14.x, 16.x, 17.x, 18.x]
|
||||
allow-lint-failure: [false]
|
||||
allow-test-failure: [false]
|
||||
include:
|
||||
- { node-version: 10.x, allow-lint-failure: true, allow-test-failure: true }
|
||||
- { node-version: 11.x, allow-lint-failure: true, allow-test-failure: true }
|
||||
- { node-version: 12.x, allow-lint-failure: true, allow-test-failure: true }
|
||||
- { node-version: 13.x, allow-lint-failure: true, allow-test-failure: true }
|
||||
- { node-version: 15.x, allow-lint-failure: true, allow-test-failure: false }
|
||||
- { node-version: 14.x, lint: true, tests: true }
|
||||
- { node-version: 15.x, lint: false, tests: true }
|
||||
- { node-version: 16.x, lint: true, tests: true }
|
||||
- { node-version: 17.x, lint: true, tests: true }
|
||||
- { node-version: 18.x, lint: true, tests: true }
|
||||
- { node-version: 19.x, lint: true, tests: true }
|
||||
|
||||
name: nodejs ${{ matrix.node-version }} (${{ matrix.lint && 'lint → ' || '' }}${{ matrix.tests && 'test → ' || '' }}build)
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4.1.0
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v3.8.1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Cache node modules
|
||||
id: cache-npm
|
||||
uses: actions/cache@v3.3.2
|
||||
env:
|
||||
cache-name: cache-node-modules
|
||||
with:
|
||||
path: node_modules
|
||||
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json', '**/package.json') }}
|
||||
|
||||
- name: Cache eslint
|
||||
id: cache-eslint
|
||||
uses: actions/cache@v3.3.2
|
||||
env:
|
||||
cache-name: cache-eslint
|
||||
with:
|
||||
path: .eslintcache
|
||||
key: ${{ env.cache-name }}-${{ hashFiles('**/package-lock.json', '**/package.json') }}
|
||||
|
||||
- name: Cache TypeScript
|
||||
id: cache-typescript
|
||||
uses: actions/cache@v3.3.2
|
||||
env:
|
||||
cache-name: cache-typescript
|
||||
with:
|
||||
path: .tsbuildinfo
|
||||
key: ${{ env.cache-name }}-${{ hashFiles('**/package-lock.json', '**/package.json') }}
|
||||
|
||||
- name: Cache prettier
|
||||
id: cache-prettier
|
||||
uses: actions/cache@v3.3.2
|
||||
env:
|
||||
cache-name: cache-prettier
|
||||
with:
|
||||
path: node_modules/.cache/prettier/.prettier-cache
|
||||
key: ${{ env.cache-name }}-${{ hashFiles('**/package-lock.json', '**/package.json') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
if: ${{ steps.cache-npm.outputs.cache-hit != 'true' }}
|
||||
|
||||
- name: Lint the project
|
||||
run: npm run lint
|
||||
continue-on-error: ${{ matrix.allow-lint-failure }}
|
||||
if: ${{ matrix.lint }}
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
continue-on-error: ${{ matrix.allow-test-failure }}
|
||||
if: ${{ matrix.tests }}
|
||||
|
||||
- name: Upload code coverage
|
||||
uses: actions/upload-artifact@v3.1.3
|
||||
with:
|
||||
name: code-coverage
|
||||
path: coverage/lcov.info
|
||||
if: ${{ matrix.node-version == '18.x' }}
|
||||
|
||||
- name: Build the project
|
||||
run: npm run build
|
||||
|
|
28
.github/workflows/dependabot-automerge.yml
vendored
Normal file
28
.github/workflows/dependabot-automerge.yml
vendored
Normal file
|
@ -0,0 +1,28 @@
|
|||
name: Dependabot auto merge
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types:
|
||||
- completed
|
||||
|
||||
jobs:
|
||||
automerge:
|
||||
name: Auto merge "${{ github.event.workflow_run.head_branch }}"
|
||||
runs-on: ubuntu-22.04
|
||||
if: >
|
||||
github.event.workflow_run.event == 'pull_request'
|
||||
&& github.event.workflow_run.conclusion == 'success'
|
||||
&& github.actor == 'dependabot[bot]'
|
||||
&& startsWith(github.event.workflow_run.head_branch, 'dependabot/')
|
||||
steps:
|
||||
- name: Checkout source
|
||||
uses: actions/checkout@v4.1.0
|
||||
with:
|
||||
ref: ${{ github.event.workflow_run.head_commit.id }}
|
||||
|
||||
- name: Instruct @dependabot to merge
|
||||
run: "gh issue comment $ISSUE_ID --body \"(This is an automated comment from workflow $WORKFLOW_URL)\n\n@dependabot squash and merge\""
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.DEPENDABOT_COMMENT_TOKEN }}
|
||||
ISSUE_ID: ${{ github.event.workflow_run.pull_requests[0].number }}
|
||||
WORKFLOW_URL: ${{ github.event.repository.html_url }}/actions/runs/${{ github.run_id }}
|
55
.github/workflows/sonar.yml
vendored
Normal file
55
.github/workflows/sonar.yml
vendored
Normal file
|
@ -0,0 +1,55 @@
|
|||
name: Sonar scan
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
sonar:
|
||||
name: Sonar scan on "${{ github.event.workflow_run.head_branch }}"
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.workflow_run.conclusion == 'success'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
with:
|
||||
repository: ${{ github.event.workflow_run.head_repository.full_name }}
|
||||
ref: ${{ github.event.workflow_run.head_branch }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 'Download code coverage'
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
script: |
|
||||
let allArtifacts = await github.rest.actions.listWorkflowRunArtifacts({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
run_id: context.payload.workflow_run.id,
|
||||
});
|
||||
let matchArtifact = allArtifacts.data.artifacts.filter((artifact) => {
|
||||
return artifact.name == "code-coverage"
|
||||
})[0];
|
||||
let download = await github.rest.actions.downloadArtifact({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
artifact_id: matchArtifact.id,
|
||||
archive_format: 'zip',
|
||||
});
|
||||
let fs = require('fs');
|
||||
fs.writeFileSync(`${process.env.GITHUB_WORKSPACE}/code-coverage.zip`, Buffer.from(download.data));
|
||||
|
||||
- name: 'Unzip code coverage'
|
||||
run: unzip code-coverage.zip -d coverage
|
||||
|
||||
- name: SonarCloud scan
|
||||
uses: sonarsource/sonarcloud-github-action@master
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
with:
|
||||
args: >
|
||||
-Dsonar.scm.revision=${{ github.event.workflow_run.head_sha }}
|
||||
-Dsonar.pullrequest.key=${{ github.event.workflow_run.pull_requests[0].number }}
|
||||
-Dsonar.pullrequest.branch=${{ github.event.workflow_run.pull_requests[0].head.ref }}
|
||||
-Dsonar.pullrequest.base=${{ github.event.workflow_run.pull_requests[0].base.ref }}
|
|
@ -143,3 +143,4 @@ prettier.config.js
|
|||
jest.config.js
|
||||
nodemon.json
|
||||
/code-generation/
|
||||
/release.sh
|
||||
|
|
102
README.md
102
README.md
|
@ -11,7 +11,8 @@
|
|||
width="10%"/>
|
||||
</div>
|
||||
|
||||
# Homebridge Prometheus Exporter [](https://github.com/lstrojny/homebridge-prometheus-exporter/actions/workflows/build.yml)
|
||||
# Homebridge Prometheus Exporter
|
||||
[](https://github.com/lstrojny/homebridge-prometheus-exporter/actions/workflows/build.yml) [](https://sonarcloud.io/summary/new_code?id=lstrojny_homebridge-prometheus-exporter) [](https://badge.fury.io/js/homebridge-prometheus-exporter)  
|
||||
|
||||
> What if we could store homebridge metrics in Prometheus
|
||||
|
||||
|
@ -63,7 +64,7 @@ Create `/etc/systemd/system/homebridge.service.d` folder:
|
|||
```shell
|
||||
mkdir /etc/systemd/system/homebridge.service.d
|
||||
```
|
||||
Write this drop-in configuration file to /etc/systemd/system/homebridge.service.d/insecure.conf:
|
||||
Write this drop-in configuration file to `/etc/systemd/system/homebridge.service.d/insecure.conf`:
|
||||
```ini
|
||||
[Service]
|
||||
ExecStart=
|
||||
|
@ -116,34 +117,95 @@ Once *Prometheus* is restarted, metrics with the `homebridge_` prefix should sta
|
|||
|
||||
*homebridge-prometheus-exporter* offers a few advanced settings to customize its behavior.
|
||||
|
||||
```json lines
|
||||
<!-- AUTOGENERATED CONFIG DOCS BEGIN -->
|
||||
```json5
|
||||
{
|
||||
// …
|
||||
// ...
|
||||
"platforms": [
|
||||
{
|
||||
"platform": "PrometheusExporter",
|
||||
// Homebridge PIN for service authentication. String of digits, format XXX-XX-XXX. Required
|
||||
"pin": string,
|
||||
|
||||
// Toggle debug mode. Run homebridge with -D if you want to see the debug output. Default: false
|
||||
"debug": boolean,
|
||||
|
||||
// Prefix for all metrics. Default: "homebridge"
|
||||
"prefix": string,
|
||||
// Pin
|
||||
//
|
||||
// Homebridge PIN for service authentication
|
||||
"pin": "<string>",
|
||||
|
||||
// TCP port where the Prometheus metrics server listens. Default: 36123
|
||||
"port": number,
|
||||
|
||||
// How frequently the services should be rediscovered (in seconds). Default: 60
|
||||
"refresh_interval": number,
|
||||
// Debug
|
||||
//
|
||||
// Default: false
|
||||
"debug": "<boolean>",
|
||||
|
||||
// Timeout for the HTTP request that retrieves the homekit devices (in seconds). Default: 10
|
||||
"request_timeout": number,
|
||||
|
||||
// Timeout for the service discovery (in seconds). Default: 20
|
||||
"discovery_timeout": number,
|
||||
},
|
||||
// …
|
||||
// Metrics prefix
|
||||
//
|
||||
// Default: "homebridge"
|
||||
"prefix": "<string>",
|
||||
|
||||
|
||||
// Metrics server port
|
||||
//
|
||||
// TCP port where the Prometheus metrics server listens
|
||||
//
|
||||
// Default: 36123
|
||||
"port": "<integer>",
|
||||
|
||||
|
||||
// Metrics server interface
|
||||
//
|
||||
// Interface where the Prometheus metrics server listens. Can be an IP, a
|
||||
// hostname, "0.0.0.0" for all IPv4 interfaces, "::1" for all IPv6 interfaces.
|
||||
// Default is "::" which means "any interface"
|
||||
//
|
||||
// Default: "::"
|
||||
"interface": "<string>",
|
||||
|
||||
|
||||
// Service refresh interval
|
||||
//
|
||||
// Discover new services every <interval> seconds
|
||||
//
|
||||
// Default: 60
|
||||
"refresh_interval": "<integer>",
|
||||
|
||||
|
||||
// Request timeout
|
||||
//
|
||||
// Request timeout when interacting with homebridge instances
|
||||
//
|
||||
// Default: 10
|
||||
"request_timeout": "<integer>",
|
||||
|
||||
|
||||
// Service discovery timeout
|
||||
//
|
||||
// Discovery timeout after which the current discovery is considered failed
|
||||
//
|
||||
// Default: 20
|
||||
"discovery_timeout": "<integer>",
|
||||
|
||||
|
||||
// TLS cert file
|
||||
//
|
||||
// Path to TLS certificate file (in PEM format)
|
||||
"tls_cert_file": "<string>",
|
||||
|
||||
|
||||
// TLS key file
|
||||
//
|
||||
// Path to TLS key file
|
||||
"tls_key_file": "<string>",
|
||||
|
||||
|
||||
// Basic auth username/password pairs
|
||||
//
|
||||
// Usernames and passwords for basic auth. Object key is the username, object
|
||||
// value is the password. Password must be encoded with bcrypt. Example:
|
||||
// {"joanna": "$2a$12$5/mmmRB28wg9yzaXhee5Iupq3UrFr/qMgAe9LvAxGoY5jLcfVGTUq"}
|
||||
"basic_auth": "<object>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
<!-- AUTOGENERATED CONFIG DOCS END -->
|
|
@ -1,17 +1,17 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
const { parseSchema } = require('json-schema-to-zod-with-defaults')
|
||||
const { parseSchema } = require('json-schema-to-zod')
|
||||
const { schema } = require('../config.schema.json')
|
||||
const { format } = require('prettier')
|
||||
const { join, basename } = require('path')
|
||||
const prettierConfig = require('../prettier.config')
|
||||
const { writeFileSync } = require('fs')
|
||||
const { writeFileSync, readFileSync } = require('fs')
|
||||
|
||||
const file = join(__dirname, '../src/generated/config_boundary.ts')
|
||||
|
||||
console.log(`Starting code generation for ${file}`)
|
||||
|
||||
const zodSchema = parseSchema(schema, true)
|
||||
const zodSchema = parseSchema(schema, false)
|
||||
|
||||
const code = format(
|
||||
`
|
||||
|
@ -26,4 +26,77 @@ export const ConfigBoundary = ${zodSchema}
|
|||
|
||||
writeFileSync(file, code)
|
||||
|
||||
const note = 'AUTOGENERATED CONFIG DOCS'
|
||||
const comment = (...strings) => `<!-- ${strings.join(' ')} -->`
|
||||
const readmePath = join(__dirname, '../README.md')
|
||||
const readme = readFileSync(readmePath).toString()
|
||||
const regex = new RegExp(`${comment(note, 'BEGIN')}.*${comment(note, 'END')}`, 'mgs')
|
||||
if (!readme.match(regex)) {
|
||||
console.log('Could not update README.md')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
writeFileSync(
|
||||
readmePath,
|
||||
readme.replace(
|
||||
regex,
|
||||
`${comment(note, 'BEGIN')}\n\`\`\`json5\n${generateDocs(schema)}\n\`\`\`\n${comment(note, 'END')}`,
|
||||
),
|
||||
)
|
||||
|
||||
function generateDocs(schema) {
|
||||
const doc = indent(
|
||||
Object.entries(schema.properties)
|
||||
.map(([property, definition]) => {
|
||||
const lines = []
|
||||
|
||||
if (definition.title) {
|
||||
lines.push(`// ${definition.title}`)
|
||||
}
|
||||
if (definition.description) {
|
||||
lines.push(`//\n// ${wordwrap(definition.description, 80, '\n// ')}`)
|
||||
}
|
||||
if (definition.default !== undefined) {
|
||||
lines.push(`//\n// Default: ${JSON.stringify(definition.default)}`)
|
||||
}
|
||||
|
||||
lines.push(`${JSON.stringify(property)}: ${JSON.stringify('<' + definition.type + '>')}`)
|
||||
|
||||
return lines.join('\n')
|
||||
})
|
||||
.join(',\n\n\n'),
|
||||
6,
|
||||
)
|
||||
|
||||
return `{
|
||||
// ...
|
||||
"platforms": [
|
||||
{
|
||||
"platform": "PrometheusExporter",
|
||||
|
||||
|
||||
${doc}
|
||||
}
|
||||
]
|
||||
}`
|
||||
}
|
||||
|
||||
function wordwrap(word, length, wrap = '\n') {
|
||||
const wrapped = []
|
||||
while (word.length > length) {
|
||||
const cut = word.substring(0, length)
|
||||
const pos = cut.lastIndexOf(' ')
|
||||
wrapped.push(cut.substring(0, pos))
|
||||
word = word.substring(pos + 1)
|
||||
}
|
||||
|
||||
wrapped.push(word)
|
||||
|
||||
return wrapped.join(wrap)
|
||||
}
|
||||
|
||||
function indent(string, indent) {
|
||||
return string.replace(/^(.+)$/gm, `${' '.repeat(indent)}$1`)
|
||||
}
|
||||
|
||||
console.log(`Finished code generation for ${file}`)
|
||||
|
|
|
@ -24,9 +24,9 @@ for (const [name, service] of Object.entries(hap.Service)) {
|
|||
const code = format(
|
||||
`
|
||||
// Auto-generated by "${join(basename(__dirname), basename(__filename))}", don’t manually edit
|
||||
export const Uuids: Record<string,string> = ${JSON.stringify(uuidToServiceMap)} as const
|
||||
export const Uuids = ${JSON.stringify(uuidToServiceMap)} as const
|
||||
|
||||
export const Services: Record<string,string> = ${JSON.stringify(serviceToUuidMap)} as const
|
||||
export const Services = ${JSON.stringify(serviceToUuidMap)} as const
|
||||
`,
|
||||
{ filepath: 'codegen.ts', ...prettierConfig },
|
||||
)
|
||||
|
|
|
@ -26,12 +26,18 @@
|
|||
"default": "homebridge"
|
||||
},
|
||||
"port": {
|
||||
"title": "Probe server port",
|
||||
"description": "TCP port for the prometheus probe server to listen to",
|
||||
"title": "Metrics server port",
|
||||
"description": "TCP port where the Prometheus metrics server listens",
|
||||
"type": "integer",
|
||||
"required": false,
|
||||
"default": 36123
|
||||
},
|
||||
"interface": {
|
||||
"title": "Metrics server interface",
|
||||
"description": "Interface where the Prometheus metrics server listens. Can be an IP, a hostname, \"0.0.0.0\" for all IPv4 interfaces, \"::1\" for all IPv6 interfaces. Default is \"::\" which means \"any interface\"",
|
||||
"type": "string",
|
||||
"default": "::"
|
||||
},
|
||||
"refresh_interval": {
|
||||
"title": "Service refresh interval",
|
||||
"description": "Discover new services every <interval> seconds",
|
||||
|
@ -52,6 +58,25 @@
|
|||
"type": "integer",
|
||||
"required": false,
|
||||
"default": 20
|
||||
},
|
||||
"tls_cert_file": {
|
||||
"title": "TLS cert file",
|
||||
"description": "Path to TLS certificate file (in PEM format)",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
"tls_key_file": {
|
||||
"title": "TLS key file",
|
||||
"description": "Path to TLS key file",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
"basic_auth": {
|
||||
"title": "Basic auth username/password pairs",
|
||||
"description": "Usernames and passwords for basic auth. Object key is the username, object value is the password. Password must be encoded with bcrypt. Example: {\"joanna\": \"$2a$12$5/mmmRB28wg9yzaXhee5Iupq3UrFr/qMgAe9LvAxGoY5jLcfVGTUq\"}",
|
||||
"type": "object",
|
||||
"additionalProperties": { "type": "string" },
|
||||
"required": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
description = "Ansible environment";
|
||||
description = "homebridge-prometheus-exporter";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
|
@ -16,6 +16,6 @@
|
|||
|
||||
in with pkgs; rec {
|
||||
|
||||
devShell = pkgs.mkShell rec { buildInputs = with pkgs; [ nodejs jq ]; };
|
||||
devShell = pkgs.mkShell rec { buildInputs = with pkgs; [ nodejs ]; };
|
||||
});
|
||||
}
|
||||
|
|
|
@ -3,4 +3,5 @@ module.exports = {
|
|||
preset: 'ts-jest',
|
||||
testEnvironment: 'node',
|
||||
verbose: true,
|
||||
testPathIgnorePatterns: ['dist'],
|
||||
}
|
||||
|
|
10290
package-lock.json
generated
10290
package-lock.json
generated
File diff suppressed because it is too large
Load diff
34
package.json
34
package.json
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "homebridge-prometheus-exporter",
|
||||
"version": "0.0.10",
|
||||
"version": "1.0.5",
|
||||
"description": "Prometheus exporter for homebridge accessories.",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
|
@ -16,11 +16,12 @@
|
|||
},
|
||||
"main": "dist/src/index.js",
|
||||
"scripts": {
|
||||
"lint": "ifNotCi() { test \"$CI\" && echo \"$2\" || echo \"$1\"; }; `npm bin`/tsc --noEmit && `npm bin`/prettier --ignore-path=.gitignore `ifNotCi --write --check` '**/**.{ts,js,json}' && `npm bin`/eslint `ifNotCi --fix` --ignore-path=.gitignore '**/**.{ts,js,json}'",
|
||||
"_portable_exec": "npmPortableExec() { `npm root`/.bin/$@; }; npmPortableExec",
|
||||
"lint": "ifNotCi() { test \"$CI\" && echo \"$2\" || echo \"$1\"; }; npm run _portable_exec -- tsc --noEmit && npm run _portable_exec -- prettier --ignore-path=.gitignore `ifNotCi --write \"--check --cache --cache-strategy content\"` '**/**.{ts,js,json}' && npm run _portable_exec -- eslint `ifNotCi --fix \"--cache --cache-strategy content\"` --ignore-path=.gitignore '**/**.{ts,js,json}'",
|
||||
"start": "npm run build && npm run link && nodemon",
|
||||
"test": "ifNotCi() { test \"$CI\" && echo \"$2\" || echo \"$1\"; }; npm run code-generation && `npm bin`/jest `ifNotCi --watchAll`",
|
||||
"test": "ifNotCi() { test \"$CI\" && echo \"$2\" || echo \"$1\"; }; npm run code-generation && npm run _portable_exec -- jest `ifNotCi --watchAll --collect-coverage`",
|
||||
"link": "npm install --no-save file:///$PWD/",
|
||||
"build": "rimraf ./dist && npm run code-generation && tsc",
|
||||
"build": "rimraf ./dist .tsbuildinfo && npm run code-generation && tsc",
|
||||
"code-generation": "./code-generation/hap-gen.js && ./code-generation/config-scheme-gen.js",
|
||||
"prepublishOnly": "npm run code-generation && npm run lint && npm run build",
|
||||
"release": "release-it --only-version"
|
||||
|
@ -33,34 +34,37 @@
|
|||
],
|
||||
"devDependencies": {
|
||||
"@jest/globals": "^29.3.0",
|
||||
"@types/node": "^18.11.9",
|
||||
"@types/bcrypt": "^5.0.0",
|
||||
"@types/node": "^20.2.3",
|
||||
"@types/supertest": "^2.0.12",
|
||||
"@typescript-eslint/eslint-plugin": "^5.42.0",
|
||||
"@typescript-eslint/parser": "^5.42.0",
|
||||
"array.prototype.flatmap": "^1.3.1",
|
||||
"eslint": "^8.0.1",
|
||||
"eslint-import-resolver-typescript": "^3.5.2",
|
||||
"eslint-plugin-import": "^2.26.0",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"hap-nodejs": "^0.10.4",
|
||||
"hap-nodejs": "^0.11.0",
|
||||
"homebridge": "^1.3.5",
|
||||
"homebridge-cmdswitch2": "^0.2.10",
|
||||
"jest": "^29.3.0",
|
||||
"json-schema-to-zod-with-defaults": "^0.2.1",
|
||||
"nodemon": "^2.0.13",
|
||||
"json-schema-to-zod": "^0.6.0",
|
||||
"nodemon": "^3.0.1",
|
||||
"prettier": "^2.7.1",
|
||||
"release-it": "^15.5.0",
|
||||
"rimraf": "^3.0.2",
|
||||
"release-it": "^16.0.0",
|
||||
"rimraf": "^5.0.0",
|
||||
"supertest": "^6.3.1",
|
||||
"ts-jest": "^29.0.3",
|
||||
"ts-node": "^10.3.0",
|
||||
"typescript": "^4.4.4"
|
||||
"typescript": "^5.0.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/auth": "^4.1.0",
|
||||
"@fastify/basic-auth": "^5.0.0",
|
||||
"array.prototype.group": "^1.1.2",
|
||||
"bcrypt": "^5.1.0",
|
||||
"fastify": "^4.9.2",
|
||||
"hap-node-client": "^0.1.25",
|
||||
"hap-node-client": "^0.2.1",
|
||||
"zod": "^3.19.1"
|
||||
},
|
||||
"overrides": {
|
||||
"jest-mock": "29.2"
|
||||
}
|
||||
}
|
||||
|
|
7
sonar-project.properties
Normal file
7
sonar-project.properties
Normal file
|
@ -0,0 +1,7 @@
|
|||
sonar.projectKey=lstrojny_homebridge-prometheus-exporter
|
||||
sonar.organization=lstrojny
|
||||
sonar.sources=.
|
||||
sonar.exclusions=tests/**
|
||||
sonar.tests=tests
|
||||
sonar.javascript.lcov.reportPaths=./coverage/lcov.info
|
||||
sonar.coverage.exclusions=code-generation/**,*.config.js,src/generated/**
|
|
@ -1,14 +1,9 @@
|
|||
import type { Device } from '../../boundaries/hap'
|
||||
import type { Config, Device } from '../../boundaries'
|
||||
import type { Logger } from 'homebridge'
|
||||
|
||||
type Pin = string
|
||||
|
||||
export interface HapConfig {
|
||||
pin: Pin
|
||||
refreshInterval: number
|
||||
discoveryTimeout: number
|
||||
requestTimeout: number
|
||||
logger: Logger
|
||||
debug: boolean
|
||||
export interface HapDiscoveryConfig {
|
||||
config: Pick<Config, 'debug' | 'pin' | 'refresh_interval' | 'discovery_timeout' | 'request_timeout'>
|
||||
log?: Logger
|
||||
}
|
||||
export type HapDiscover = (config: HapConfig) => Promise<Device[]>
|
||||
|
||||
export type HapDiscover = (config: HapDiscoveryConfig) => Promise<Device[]>
|
||||
|
|
|
@ -1,64 +1,66 @@
|
|||
import type { HapDiscover } from './api'
|
||||
import { HAPNodeJSClient } from 'hap-node-client'
|
||||
import { Device, DeviceBoundary, checkBoundary } from '../../boundaries'
|
||||
import { HAPNodeJSClient, type HAPNodeJSClientConfig } from 'hap-node-client'
|
||||
import { type Device, DeviceBoundary, checkBoundary } from '../../boundaries'
|
||||
import type { Logger } from 'homebridge'
|
||||
import z from 'zod'
|
||||
|
||||
const MaybeDevices = z.array(z.unknown())
|
||||
|
||||
interface HapConfig {
|
||||
debug: boolean
|
||||
refresh: number
|
||||
timeout: number
|
||||
reqTimeout: number
|
||||
pin: string
|
||||
}
|
||||
type ResolveFunc = (devices: Device[]) => void
|
||||
type RejectFunc = (error: unknown) => void
|
||||
|
||||
const clientMap: Record<string, HAPNodeJSClient> = {}
|
||||
const promiseMap: Record<string, [ResolveFunc, RejectFunc]> = {}
|
||||
|
||||
function startDiscovery(logger: Logger, config: HapConfig, resolve: ResolveFunc, reject: RejectFunc) {
|
||||
function startDiscovery(
|
||||
logger: Logger | undefined,
|
||||
config: HAPNodeJSClientConfig,
|
||||
resolve: ResolveFunc,
|
||||
reject: RejectFunc,
|
||||
) {
|
||||
const key = JSON.stringify(config)
|
||||
|
||||
if (!clientMap[key]) {
|
||||
logger.debug('Creating new HAP client')
|
||||
const client = new HAPNodeJSClient(config)
|
||||
client.on('Ready', (deviceData: unknown) => {
|
||||
try {
|
||||
const devices: Device[] = []
|
||||
|
||||
for (const device of checkBoundary(MaybeDevices, deviceData)) {
|
||||
try {
|
||||
devices.push(checkBoundary(DeviceBoundary, device))
|
||||
} catch (e) {
|
||||
logger.error('Boundary check for device data failed %o %s', e, JSON.stringify(device, null, 4))
|
||||
}
|
||||
}
|
||||
|
||||
if (promiseMap[key]) promiseMap[key][0](devices)
|
||||
} catch (e) {
|
||||
if (promiseMap[key]) promiseMap[key][1](e)
|
||||
}
|
||||
})
|
||||
clientMap[key] = client
|
||||
} else {
|
||||
logger.debug('Reusing existing HAP client')
|
||||
}
|
||||
promiseMap[key] = [resolve, reject]
|
||||
|
||||
if (!clientMap[key]) {
|
||||
logger?.debug('Creating new HAP client')
|
||||
clientMap[key] = new HAPNodeJSClient(config)
|
||||
clientMap[key].on('Ready', createDiscoveryHandler(logger, key))
|
||||
} else {
|
||||
logger?.debug('Reusing existing HAP client')
|
||||
}
|
||||
}
|
||||
|
||||
export const discover: HapDiscover = ({ pin, refreshInterval, discoveryTimeout, requestTimeout, logger, debug }) => {
|
||||
function createDiscoveryHandler(logger: Logger | undefined, key: string): (deviceData: unknown) => void {
|
||||
return (deviceData: unknown) => {
|
||||
try {
|
||||
const devices: Device[] = []
|
||||
|
||||
for (const device of checkBoundary(MaybeDevices, deviceData)) {
|
||||
try {
|
||||
devices.push(checkBoundary(DeviceBoundary, device))
|
||||
} catch (e) {
|
||||
logger?.error('Boundary check for device data failed %o %s', e, JSON.stringify(device, null, 4))
|
||||
}
|
||||
}
|
||||
|
||||
if (promiseMap[key]) promiseMap[key][0](devices)
|
||||
} catch (e) {
|
||||
if (promiseMap[key]) promiseMap[key][1](e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const hapNodeJsClientDiscover: HapDiscover = ({ config, log }) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
startDiscovery(
|
||||
logger,
|
||||
log,
|
||||
{
|
||||
debug: debug,
|
||||
refresh: refreshInterval,
|
||||
timeout: discoveryTimeout,
|
||||
reqTimeout: requestTimeout,
|
||||
pin,
|
||||
debug: config.debug,
|
||||
refresh: config.refresh_interval,
|
||||
timeout: config.discovery_timeout,
|
||||
reqTimeout: config.request_timeout,
|
||||
pin: config.pin,
|
||||
},
|
||||
resolve,
|
||||
reject,
|
||||
|
|
2
src/adapters/discovery/index.ts
Normal file
2
src/adapters/discovery/index.ts
Normal file
|
@ -0,0 +1,2 @@
|
|||
export * from './api'
|
||||
export * from './hap_node_js_client'
|
|
@ -1,4 +1,7 @@
|
|||
import type { HttpServer } from '../../http'
|
||||
import type { Logger } from 'homebridge'
|
||||
import type { RequestListener, Server } from 'http'
|
||||
import type { Config } from '../../boundaries'
|
||||
import type { Metric } from '../../metrics'
|
||||
|
||||
export interface HttpResponse {
|
||||
statusCode?: number
|
||||
|
@ -11,3 +14,19 @@ export interface HttpServerController {
|
|||
}
|
||||
|
||||
export type HttpAdapter = (config: HttpServer) => Promise<HttpServerController>
|
||||
|
||||
export type HttpConfig = Pick<
|
||||
Config,
|
||||
'debug' | 'port' | 'interface' | 'prefix' | 'basic_auth' | 'tls_cert_file' | 'tls_key_file'
|
||||
>
|
||||
|
||||
export interface HttpServer {
|
||||
log: Logger | null
|
||||
config: HttpConfig
|
||||
serverFactory?: (requestListener: RequestListener) => Server
|
||||
onRequest(): HttpResponse | null
|
||||
onMetrics(): HttpResponse
|
||||
onNotFound(): HttpResponse
|
||||
onError(error: Error): HttpResponse
|
||||
onMetricsDiscovery(metrics: Metric[]): void
|
||||
}
|
||||
|
|
|
@ -1,6 +1,10 @@
|
|||
import Fastify, { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from 'fastify'
|
||||
import type { HttpAdapter, HttpResponse } from './api'
|
||||
import type { HttpServer } from '../../http'
|
||||
import Fastify, { type FastifyReply, type FastifyRequest, type HookHandlerDoneFunction } from 'fastify'
|
||||
import { readFileSync } from 'fs'
|
||||
import { constants as HttpConstants } from 'http2'
|
||||
import { isAuthenticated } from '../../security'
|
||||
import type { HttpAdapter, HttpResponse, HttpServer } from './api'
|
||||
import fastifyAuth from '@fastify/auth'
|
||||
import fastifyBasicAuth from '@fastify/basic-auth'
|
||||
|
||||
function adaptResponseToReply(response: HttpResponse, reply: FastifyReply): void {
|
||||
if (response.statusCode) {
|
||||
|
@ -16,11 +20,61 @@ function adaptResponseToReply(response: HttpResponse, reply: FastifyReply): void
|
|||
}
|
||||
}
|
||||
|
||||
export const serve: HttpAdapter = async (server: HttpServer) => {
|
||||
const fastify = Fastify({
|
||||
logger: server.debug,
|
||||
function formatCombinedLog(request: FastifyRequest, reply: FastifyReply): string {
|
||||
const remoteAddress = [request.socket.remoteAddress, request.socket.remotePort].filter((v) => v != null).join(':')
|
||||
const userAgent = request.headers['user-agent'] || ''
|
||||
const contentType = request.headers['content-type'] || ''
|
||||
return `${remoteAddress} - "${request.method} ${request.url} HTTP/${request.raw.httpVersion}" ${reply.statusCode} "${request.protocol}://${request.hostname}" "${userAgent}" "${contentType}"`
|
||||
}
|
||||
|
||||
type FastifyServer = ReturnType<typeof Fastify>
|
||||
function createFastify(server: HttpServer): FastifyServer {
|
||||
const config = { logger: false }
|
||||
|
||||
if (server.config.tls_cert_file && server.config.tls_key_file) {
|
||||
server.log?.debug('Running with TLS enabled')
|
||||
return Fastify({
|
||||
...config,
|
||||
https: {
|
||||
key: readFileSync(server.config.tls_key_file),
|
||||
cert: readFileSync(server.config.tls_cert_file),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return Fastify({
|
||||
...config,
|
||||
serverFactory: server.serverFactory,
|
||||
})
|
||||
}
|
||||
|
||||
export const fastifyServe: HttpAdapter = async (server: HttpServer) => {
|
||||
const fastify = createFastify(server)
|
||||
|
||||
if (server.config.basic_auth && Object.keys(server.config.basic_auth).length > 0) {
|
||||
const users = server.config.basic_auth
|
||||
|
||||
const validate = async (username: string, password: string) => {
|
||||
if (!(await isAuthenticated(username, password, users))) {
|
||||
throw new Error('Unauthorized')
|
||||
}
|
||||
}
|
||||
|
||||
await fastify.register(fastifyAuth)
|
||||
await fastify.register(fastifyBasicAuth, { validate, authenticate: true })
|
||||
|
||||
fastify.after(() => {
|
||||
fastify.addHook('preHandler', fastify.auth([fastify.basicAuth]))
|
||||
})
|
||||
}
|
||||
|
||||
fastify.addHook('onResponse', (request: FastifyRequest, reply: FastifyReply) => {
|
||||
if (reply.statusCode >= HttpConstants.HTTP_STATUS_BAD_REQUEST) {
|
||||
server.log?.error(formatCombinedLog(request, reply))
|
||||
} else if (server.config.debug) {
|
||||
server.log?.debug(formatCombinedLog(request, reply))
|
||||
}
|
||||
})
|
||||
|
||||
fastify.addHook('onRequest', (request: FastifyRequest, reply: FastifyReply, next: HookHandlerDoneFunction) => {
|
||||
const response = server.onRequest()
|
||||
|
@ -44,7 +98,7 @@ export const serve: HttpAdapter = async (server: HttpServer) => {
|
|||
adaptResponseToReply(server.onMetrics(), reply)
|
||||
})
|
||||
|
||||
await fastify.listen({ port: server.port, host: '::' })
|
||||
await listen(fastify, server.config.port, server.config.interface)
|
||||
|
||||
return {
|
||||
shutdown() {
|
||||
|
@ -52,3 +106,13 @@ export const serve: HttpAdapter = async (server: HttpServer) => {
|
|||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function listen(fastify: FastifyServer, port: number, host: string): Promise<void> {
|
||||
try {
|
||||
await fastify.listen({ port, host })
|
||||
} catch (e: unknown) {
|
||||
if (host === '::' && e instanceof Error && (e as Error & { code: string }).code === 'EAFNOSUPPORT') {
|
||||
await listen(fastify, port, '0.0.0.0')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
2
src/adapters/http/index.ts
Normal file
2
src/adapters/http/index.ts
Normal file
|
@ -0,0 +1,2 @@
|
|||
export * from './api'
|
||||
export * from './fastify'
|
9
src/ambient.d.ts
vendored
9
src/ambient.d.ts
vendored
|
@ -13,3 +13,12 @@ declare module 'hap-node-client' {
|
|||
on(event: 'Ready', callback: (v: unknown) => void): void
|
||||
}
|
||||
}
|
||||
|
||||
declare module 'array.prototype.group' {
|
||||
function shim(): void
|
||||
}
|
||||
|
||||
interface Array<T> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
group<U>(fn: (value: T, index: number, array: T[]) => U, thisArg?: any): { U: T[] }
|
||||
}
|
||||
|
|
|
@ -6,7 +6,13 @@ export const ConfigBoundary = z.object({
|
|||
pin: z.string().regex(new RegExp('^\\d{3}-\\d{2}-\\d{3}$')).describe('Homebridge PIN for service authentication'),
|
||||
debug: z.boolean().default(false),
|
||||
prefix: z.string().default('homebridge'),
|
||||
port: z.number().int().describe('TCP port for the prometheus probe server to listen to').default(36123),
|
||||
port: z.number().int().describe('TCP port where the Prometheus metrics server listens').default(36123),
|
||||
interface: z
|
||||
.string()
|
||||
.describe(
|
||||
'Interface where the Prometheus metrics server listens. Can be an IP, a hostname, "0.0.0.0" for all IPv4 interfaces, "::1" for all IPv6 interfaces. Default is "::" which means "any interface"',
|
||||
)
|
||||
.default('::'),
|
||||
refresh_interval: z.number().int().describe('Discover new services every <interval> seconds').default(60),
|
||||
request_timeout: z
|
||||
.number()
|
||||
|
@ -18,4 +24,12 @@ export const ConfigBoundary = z.object({
|
|||
.int()
|
||||
.describe('Discovery timeout after which the current discovery is considered failed')
|
||||
.default(20),
|
||||
tls_cert_file: z.string().describe('Path to TLS certificate file (in PEM format)').optional(),
|
||||
tls_key_file: z.string().describe('Path to TLS key file').optional(),
|
||||
basic_auth: z
|
||||
.record(z.string())
|
||||
.describe(
|
||||
'Usernames and passwords for basic auth. Object key is the username, object value is the password. Password must be encoded with bcrypt. Example: {"joanna": "$2a$12$5/mmmRB28wg9yzaXhee5Iupq3UrFr/qMgAe9LvAxGoY5jLcfVGTUq"}',
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
// Auto-generated by "code-generation/hap-gen.js", don’t manually edit
|
||||
export const Uuids: Record<string, string> = {
|
||||
export const Uuids = {
|
||||
'00000260-0000-1000-8000-0026BB765291': 'AccessCode',
|
||||
'000000DA-0000-1000-8000-0026BB765291': 'AccessControl',
|
||||
'0000003E-0000-1000-8000-0026BB765291': 'AccessoryInformation',
|
||||
|
@ -29,6 +29,7 @@ export const Uuids: Record<string, string> = {
|
|||
'000000B7-0000-1000-8000-0026BB765291': 'Fanv2',
|
||||
'000000D7-0000-1000-8000-0026BB765291': 'Faucet',
|
||||
'000000BA-0000-1000-8000-0026BB765291': 'FilterMaintenance',
|
||||
'00000236-0000-1000-8000-0026BB765291': 'FirmwareUpdate',
|
||||
'00000041-0000-1000-8000-0026BB765291': 'GarageDoorOpener',
|
||||
'000000BC-0000-1000-8000-0026BB765291': 'HeaterCooler',
|
||||
'000000BD-0000-1000-8000-0026BB765291': 'HumidifierDehumidifier',
|
||||
|
@ -59,6 +60,7 @@ export const Uuids: Record<string, string> = {
|
|||
'00000088-0000-1000-8000-0026BB765291': 'StatefulProgrammableSwitch',
|
||||
'00000089-0000-1000-8000-0026BB765291': 'StatelessProgrammableSwitch',
|
||||
'00000049-0000-1000-8000-0026BB765291': 'Switch',
|
||||
'0000022E-0000-1000-8000-0026BB765291': 'TapManagement',
|
||||
'00000125-0000-1000-8000-0026BB765291': 'TargetControl',
|
||||
'00000122-0000-1000-8000-0026BB765291': 'TargetControlManagement',
|
||||
'000000D8-0000-1000-8000-0026BB765291': 'Television',
|
||||
|
@ -76,7 +78,7 @@ export const Uuids: Record<string, string> = {
|
|||
'0000008C-0000-1000-8000-0026BB765291': 'WindowCovering',
|
||||
} as const
|
||||
|
||||
export const Services: Record<string, string> = {
|
||||
export const Services = {
|
||||
AccessCode: '00000260-0000-1000-8000-0026BB765291',
|
||||
AccessControl: '000000DA-0000-1000-8000-0026BB765291',
|
||||
AccessoryInformation: '0000003E-0000-1000-8000-0026BB765291',
|
||||
|
@ -109,6 +111,7 @@ export const Services: Record<string, string> = {
|
|||
Fanv2: '000000B7-0000-1000-8000-0026BB765291',
|
||||
Faucet: '000000D7-0000-1000-8000-0026BB765291',
|
||||
FilterMaintenance: '000000BA-0000-1000-8000-0026BB765291',
|
||||
FirmwareUpdate: '00000236-0000-1000-8000-0026BB765291',
|
||||
GarageDoorOpener: '00000041-0000-1000-8000-0026BB765291',
|
||||
HeaterCooler: '000000BC-0000-1000-8000-0026BB765291',
|
||||
HumidifierDehumidifier: '000000BD-0000-1000-8000-0026BB765291',
|
||||
|
@ -140,6 +143,7 @@ export const Services: Record<string, string> = {
|
|||
StatefulProgrammableSwitch: '00000088-0000-1000-8000-0026BB765291',
|
||||
StatelessProgrammableSwitch: '00000089-0000-1000-8000-0026BB765291',
|
||||
Switch: '00000049-0000-1000-8000-0026BB765291',
|
||||
TapManagement: '0000022E-0000-1000-8000-0026BB765291',
|
||||
TargetControl: '00000125-0000-1000-8000-0026BB765291',
|
||||
TargetControlManagement: '00000122-0000-1000-8000-0026BB765291',
|
||||
Television: '000000D8-0000-1000-8000-0026BB765291',
|
||||
|
|
16
src/http.ts
16
src/http.ts
|
@ -1,16 +0,0 @@
|
|||
import type { HttpResponse } from './adapters/http/api'
|
||||
import type { Metric } from './metrics'
|
||||
import type { Logger } from 'homebridge'
|
||||
import type { RequestListener, Server } from 'http'
|
||||
|
||||
export interface HttpServer {
|
||||
port: number
|
||||
debug: boolean
|
||||
log?: Logger
|
||||
serverFactory?: (requestListener: RequestListener) => Server
|
||||
onRequest(): HttpResponse | undefined
|
||||
onMetrics(): HttpResponse
|
||||
onNotFound(): HttpResponse
|
||||
onError(error: unknown): HttpResponse
|
||||
updateMetrics(metrics: Metric[]): void
|
||||
}
|
119
src/metrics.ts
119
src/metrics.ts
|
@ -1,13 +1,15 @@
|
|||
import type { Accessory, Device, Service } from './boundaries/hap'
|
||||
import { Uuids } from './generated/services'
|
||||
import { assertTypeExhausted, isType } from './std'
|
||||
import type { Accessory, Device, Service } from './boundaries'
|
||||
import { Services, Uuids } from './generated/services'
|
||||
import { assertTypeExhausted, isKeyOfConstObject, isType, strCamelCaseToSnakeCase } from './std'
|
||||
|
||||
type Labels = Record<string, string>
|
||||
|
||||
export class Metric {
|
||||
constructor(
|
||||
public readonly name: string,
|
||||
public readonly value: number,
|
||||
public readonly timestamp: Date | null = null,
|
||||
public readonly labels: Record<string, string> = {},
|
||||
public readonly labels: Labels = {},
|
||||
) {}
|
||||
}
|
||||
|
||||
|
@ -17,7 +19,7 @@ export class Metric {
|
|||
const METRICS_FILTER = ['Identifier']
|
||||
|
||||
export function aggregate(devices: Device[], timestamp: Date): Metric[] {
|
||||
const metrics: Metric[] = []
|
||||
const metrics: Metric[][] = []
|
||||
|
||||
for (const device of devices) {
|
||||
for (const accessory of device.accessories.accessories) {
|
||||
|
@ -27,84 +29,87 @@ export function aggregate(devices: Device[], timestamp: Date): Metric[] {
|
|||
...getAccessoryLabels(accessory),
|
||||
...getServiceLabels(service),
|
||||
}
|
||||
for (const characteristic of service.characteristics) {
|
||||
const format = characteristic.format
|
||||
switch (format) {
|
||||
case 'string':
|
||||
case 'tlv8':
|
||||
case 'data':
|
||||
break
|
||||
|
||||
case 'bool':
|
||||
case 'float':
|
||||
case 'int':
|
||||
case 'uint8':
|
||||
case 'uint16':
|
||||
case 'uint32':
|
||||
case 'uint64':
|
||||
if (characteristic.value != null) {
|
||||
if (METRICS_FILTER.includes(characteristic.description)) {
|
||||
break
|
||||
}
|
||||
const name = formatName(
|
||||
Uuids[service.type] || 'custom',
|
||||
characteristic.description,
|
||||
characteristic.unit,
|
||||
)
|
||||
metrics.push(new Metric(name, characteristic.value, timestamp, labels))
|
||||
}
|
||||
break
|
||||
|
||||
default:
|
||||
assertTypeExhausted(format)
|
||||
}
|
||||
}
|
||||
metrics.push(extractMetrics(service, timestamp, labels))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return metrics.flat()
|
||||
}
|
||||
|
||||
function extractMetrics(service: Service, timestamp: Date, labels: Labels): Metric[] {
|
||||
const metrics: Metric[] = []
|
||||
|
||||
for (const characteristic of service.characteristics) {
|
||||
if (METRICS_FILTER.includes(characteristic.description)) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (characteristic.value == null) {
|
||||
continue
|
||||
}
|
||||
|
||||
const format = characteristic.format
|
||||
switch (format) {
|
||||
case 'string':
|
||||
case 'tlv8':
|
||||
case 'data':
|
||||
break
|
||||
|
||||
case 'bool':
|
||||
case 'float':
|
||||
case 'int':
|
||||
case 'uint8':
|
||||
case 'uint16':
|
||||
case 'uint32':
|
||||
case 'uint64':
|
||||
{
|
||||
const name = formatName(
|
||||
isKeyOfConstObject(service.type, Uuids) ? Uuids[service.type] : 'custom',
|
||||
characteristic.description,
|
||||
characteristic.unit,
|
||||
)
|
||||
metrics.push(new Metric(name, characteristic.value, timestamp, labels))
|
||||
}
|
||||
break
|
||||
|
||||
default:
|
||||
assertTypeExhausted(format)
|
||||
}
|
||||
}
|
||||
|
||||
return metrics
|
||||
}
|
||||
|
||||
export function formatName(serviceName: string, description: string, unit: string | undefined = undefined): string {
|
||||
export function formatName(serviceName: string, description: string, unit: string | null = null): string {
|
||||
return (
|
||||
[serviceName, description, typeof unit === 'string' ? unit.toLowerCase() : undefined]
|
||||
.filter(isType('string'))
|
||||
.map((v) => camelCaseToSnakeCase(v))
|
||||
.map((val) => strCamelCaseToSnakeCase(val))
|
||||
// Remove duplicate prefix
|
||||
.reduce((carry, value) => (value.startsWith(carry) ? value : carry + '_' + value))
|
||||
.reduce((carry, val) => (val.startsWith(carry) ? val : `${carry}_${val}`))
|
||||
)
|
||||
}
|
||||
|
||||
function camelCaseToSnakeCase(str: string): string {
|
||||
return str
|
||||
.replace(/\B([A-Z][a-z])/g, ' $1')
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/\s+/g, '_')
|
||||
}
|
||||
|
||||
function getDeviceLabels(device: Device): Record<string, string> {
|
||||
function getDeviceLabels(device: Device): Labels {
|
||||
return {
|
||||
bridge: device.instance.name,
|
||||
device_id: device.instance.deviceID,
|
||||
}
|
||||
}
|
||||
|
||||
function getAccessoryLabels(accessory: Accessory): Record<string, string> {
|
||||
const labels: Record<string, string> = {}
|
||||
|
||||
function getAccessoryLabels(accessory: Accessory): Labels {
|
||||
for (const service of accessory.services) {
|
||||
if (service.type === '0000003E-0000-1000-8000-0026BB765291') {
|
||||
if (service.type === Services.AccessoryInformation) {
|
||||
return getServiceLabels(service)
|
||||
}
|
||||
}
|
||||
|
||||
return labels
|
||||
return {}
|
||||
}
|
||||
|
||||
function getServiceLabels(service: Service): Record<string, string> {
|
||||
const labels: Record<string, string> = {}
|
||||
function getServiceLabels(service: Service): Labels {
|
||||
const labels: Labels = {}
|
||||
|
||||
for (const characteristic of service.characteristics) {
|
||||
if (
|
||||
|
@ -121,7 +126,7 @@ function getServiceLabels(service: Service): Record<string, string> {
|
|||
'Hardware Revision',
|
||||
].includes(characteristic.description)
|
||||
) {
|
||||
labels[camelCaseToSnakeCase(characteristic.description)] = characteristic.value
|
||||
labels[strCamelCaseToSnakeCase(characteristic.description)] = characteristic.value
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,15 +1,14 @@
|
|||
import type { API, IndependentPlatformPlugin, Logger, PlatformConfig } from 'homebridge'
|
||||
|
||||
import { aggregate } from './metrics'
|
||||
import { discover } from './adapters/discovery/hap_node_js_client'
|
||||
import { serve } from './adapters/http/fastify'
|
||||
import type { HttpServerController } from './adapters/http/api'
|
||||
import { hapNodeJsClientDiscover as discover } from './adapters/discovery'
|
||||
import { type HttpServerController, fastifyServe as serve } from './adapters/http'
|
||||
import { PrometheusServer } from './prometheus'
|
||||
import { Config, ConfigBoundary, checkBoundary } from './boundaries'
|
||||
import { type Config, ConfigBoundary, checkBoundary } from './boundaries'
|
||||
|
||||
export class PrometheusExporterPlatform implements IndependentPlatformPlugin {
|
||||
private readonly httpServer: PrometheusServer
|
||||
private httpServerController: HttpServerController | undefined = undefined
|
||||
private httpServerController: HttpServerController | null = null
|
||||
private readonly config: Config
|
||||
|
||||
constructor(public readonly log: Logger, config: PlatformConfig, public readonly api: API) {
|
||||
|
@ -28,7 +27,7 @@ export class PrometheusExporterPlatform implements IndependentPlatformPlugin {
|
|||
|
||||
this.log.debug('Starting Prometheus HTTP server on port %d', this.config.port)
|
||||
|
||||
this.httpServer = new PrometheusServer(this.config.port, this.log, this.config.debug, this.config.prefix)
|
||||
this.httpServer = new PrometheusServer(this.config, this.log)
|
||||
serve(this.httpServer)
|
||||
.then((httpServerController) => {
|
||||
this.log.debug('HTTP server started on port %d', this.config.port)
|
||||
|
@ -46,17 +45,10 @@ export class PrometheusExporterPlatform implements IndependentPlatformPlugin {
|
|||
|
||||
private startHapDiscovery(): void {
|
||||
this.log.debug('Starting HAP discovery')
|
||||
discover({
|
||||
logger: this.log,
|
||||
refreshInterval: this.config.refresh_interval,
|
||||
discoveryTimeout: this.config.discovery_timeout,
|
||||
requestTimeout: this.config.request_timeout,
|
||||
pin: this.config.pin,
|
||||
debug: this.config.debug,
|
||||
})
|
||||
discover({ log: this.log, config: this.config })
|
||||
.then((devices) => {
|
||||
const metrics = aggregate(devices, new Date())
|
||||
this.httpServer.updateMetrics(metrics)
|
||||
this.httpServer.onMetricsDiscovery(metrics)
|
||||
this.log.debug('HAP discovery completed, %d metrics discovered', metrics.length)
|
||||
this.startHapDiscovery()
|
||||
})
|
||||
|
|
|
@ -1,24 +1,39 @@
|
|||
import type { Metric } from './metrics'
|
||||
import type { Logger } from 'homebridge'
|
||||
import type { HttpResponse } from './adapters/http/api'
|
||||
import type { HttpServer } from './http'
|
||||
import type { HttpConfig, HttpResponse, HttpServer } from './adapters/http'
|
||||
import type { Metric } from './metrics'
|
||||
import { strTrimRight } from './std'
|
||||
import { shim } from 'array.prototype.group'
|
||||
shim()
|
||||
|
||||
export class MetricsRenderer {
|
||||
constructor(private readonly prefix: string) {}
|
||||
private readonly prefix: string
|
||||
|
||||
render(metric: Metric): string {
|
||||
const name = this.metricName(metric.name)
|
||||
return [
|
||||
`# TYPE ${name} ${name.endsWith('_total') ? 'counter' : 'gauge'}`,
|
||||
`${name}${this.renderLabels(metric.labels)} ${metric.value}${
|
||||
metric.timestamp !== null ? ' ' + String(metric.timestamp.getTime()) : ''
|
||||
}`,
|
||||
].join('\n')
|
||||
constructor(prefix: string) {
|
||||
this.prefix = strTrimRight(prefix, '_')
|
||||
}
|
||||
|
||||
private renderLabels(labels: Metric['labels']): string {
|
||||
render(metrics: Metric[]): string {
|
||||
return (
|
||||
Object.entries(metrics.sort().group((metric) => this.metricName(metric.name)))
|
||||
.map(([name, metrics]) => {
|
||||
return [
|
||||
`# TYPE ${name} ${name.endsWith('_total') ? 'counter' : 'gauge'}`,
|
||||
metrics.map((metric) => this.formatMetric(metric)).join('\n'),
|
||||
].join('\n')
|
||||
})
|
||||
.join('\n\n') + '\n'
|
||||
)
|
||||
}
|
||||
|
||||
private formatMetric(metric: Metric): string {
|
||||
return `${this.metricName(metric.name)}${MetricsRenderer.renderLabels(metric.labels)} ${metric.value}${
|
||||
metric.timestamp !== null ? ' ' + String(metric.timestamp.getTime()) : ''
|
||||
}`
|
||||
}
|
||||
|
||||
private static renderLabels(labels: Metric['labels']): string {
|
||||
const rendered = Object.entries(labels)
|
||||
.map(([key, value]) => `${sanitizePrometheusMetricName(key)}="${escapeAttributeValue(value)}"`)
|
||||
.map(([label, val]) => `${sanitizePrometheusMetricName(label)}="${escapeAttributeValue(val)}"`)
|
||||
.join(',')
|
||||
|
||||
return rendered !== '' ? '{' + rendered + '}' : ''
|
||||
|
@ -27,7 +42,7 @@ export class MetricsRenderer {
|
|||
private metricName(name: string): string {
|
||||
name = name.replace(/^(.*_)?(total)_(.*)$/, '$1$3_$2')
|
||||
|
||||
return sanitizePrometheusMetricName(this.prefix.replace(/_+$/, '') + '_' + name)
|
||||
return sanitizePrometheusMetricName(`${this.prefix}_${name}`)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -36,62 +51,59 @@ const textContentType = 'text/plain; charset=utf-8'
|
|||
const prometheusSpecVersion = '0.0.4'
|
||||
const metricsContentType = `${textContentType}; version=${prometheusSpecVersion}`
|
||||
|
||||
function headers(contentType: string, headers: Record<string, string> = {}): Record<string, string> {
|
||||
function withHeaders(contentType: string, headers: Record<string, string> = {}): Record<string, string> {
|
||||
return { ...headers, 'Content-Type': contentType }
|
||||
}
|
||||
|
||||
export class PrometheusServer implements HttpServer {
|
||||
private metricsInitialized = false
|
||||
private metrics: Metric[] = []
|
||||
private metricsDiscovered = false
|
||||
private metricsResponse = ''
|
||||
|
||||
constructor(
|
||||
public readonly port: number,
|
||||
public readonly log: Logger | undefined,
|
||||
public readonly debug: boolean,
|
||||
private readonly prefix: string,
|
||||
public readonly config: HttpConfig,
|
||||
public readonly log: Logger | null = null,
|
||||
private readonly renderer: MetricsRenderer = new MetricsRenderer(config.prefix),
|
||||
) {}
|
||||
|
||||
onRequest(): HttpResponse | undefined {
|
||||
if (!this.metricsInitialized) {
|
||||
return {
|
||||
statusCode: 503,
|
||||
headers: headers(textContentType, { 'Retry-After': String(retryAfterWhileDiscovery) }),
|
||||
body: 'Metrics discovery pending',
|
||||
}
|
||||
onRequest(): HttpResponse | null {
|
||||
if (this.metricsDiscovered) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
statusCode: 503,
|
||||
headers: withHeaders(textContentType, { 'Retry-After': String(retryAfterWhileDiscovery) }),
|
||||
body: 'Metrics discovery pending',
|
||||
}
|
||||
}
|
||||
|
||||
onMetrics(): HttpResponse {
|
||||
const renderer = new MetricsRenderer(this.prefix)
|
||||
const metrics = this.metrics.map((metric) => renderer.render(metric)).join('\n')
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
headers: headers(metricsContentType),
|
||||
body: metrics,
|
||||
headers: withHeaders(metricsContentType),
|
||||
body: this.metricsResponse,
|
||||
}
|
||||
}
|
||||
|
||||
onNotFound(): HttpResponse {
|
||||
return {
|
||||
statusCode: 404,
|
||||
headers: headers(textContentType),
|
||||
headers: withHeaders(textContentType),
|
||||
body: 'Not found. Try /metrics',
|
||||
}
|
||||
}
|
||||
|
||||
onError(error: unknown): HttpResponse {
|
||||
onError(error: Error): HttpResponse {
|
||||
this.log?.error('HTTP request error: %o', error)
|
||||
return {
|
||||
statusCode: 500,
|
||||
headers: headers(textContentType),
|
||||
body: 'Server error',
|
||||
headers: withHeaders(textContentType),
|
||||
body: error.message,
|
||||
}
|
||||
}
|
||||
|
||||
updateMetrics(metrics: Metric[]): void {
|
||||
this.metrics = metrics
|
||||
this.metricsInitialized = true
|
||||
onMetricsDiscovery(metrics: Metric[]): void {
|
||||
this.metricsResponse = this.renderer.render(metrics)
|
||||
this.metricsDiscovered = true
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -107,7 +119,7 @@ function escapeString(str: string) {
|
|||
*
|
||||
* `undefined` is converted to an empty string.
|
||||
*/
|
||||
function escapeAttributeValue(str: string) {
|
||||
function escapeAttributeValue(str: Metric['labels'][keyof Metric['labels']]) {
|
||||
if (typeof str !== 'string') {
|
||||
str = JSON.stringify(str)
|
||||
}
|
||||
|
|
9
src/security.ts
Normal file
9
src/security.ts
Normal file
|
@ -0,0 +1,9 @@
|
|||
import { compare } from 'bcrypt'
|
||||
|
||||
export function isAuthenticated(
|
||||
username: string,
|
||||
plainPassword: string,
|
||||
map: Record<string, string>,
|
||||
): Promise<boolean> {
|
||||
return compare(plainPassword, map[username] || '')
|
||||
}
|
30
src/std.ts
30
src/std.ts
|
@ -1,15 +1,41 @@
|
|||
type Types = 'string' | 'number' | 'boolean' | 'object'
|
||||
interface TypeMap {
|
||||
string: string
|
||||
number: number
|
||||
bigint: bigint
|
||||
boolean: boolean
|
||||
object: object
|
||||
symbol: symbol
|
||||
undefined: undefined
|
||||
}
|
||||
|
||||
export function isType<T extends Types>(type: T): (v: unknown) => v is TypeMap[T] {
|
||||
// Type predicate higher order function for use with e.g. filter or map
|
||||
export function isType<T extends keyof TypeMap>(type: T): (v: unknown) => v is TypeMap[T] {
|
||||
return (v: unknown): v is TypeMap[T] => typeof v === type
|
||||
}
|
||||
|
||||
// Type predicate for object keys
|
||||
// Only safe for const objects, as other objects might carry additional, undeclared properties
|
||||
export function isKeyOfConstObject<T extends object>(key: string | number | symbol, obj: T): key is keyof T {
|
||||
return key in obj
|
||||
}
|
||||
|
||||
// Use for exhaustiveness checks in switch/case
|
||||
export function assertTypeExhausted(v: never): never {
|
||||
throw new Error(`Type should be exhausted but is not. Value "${JSON.stringify(v)}`)
|
||||
}
|
||||
|
||||
export function strCamelCaseToSnakeCase(str: string): string {
|
||||
return str
|
||||
.replace(/\B([A-Z][a-z])/g, ' $1')
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/\s+/g, '_')
|
||||
}
|
||||
|
||||
export function strReverse(str: string): string {
|
||||
return str.split('').reverse().join('')
|
||||
}
|
||||
|
||||
export function strTrimRight(str: string, char: string): string {
|
||||
return strReverse(strReverse(str).replace(new RegExp(`^[${char}]+`), ''))
|
||||
}
|
||||
|
|
74
tests/adapters/discovery/hap_node_js_client.test.ts
Normal file
74
tests/adapters/discovery/hap_node_js_client.test.ts
Normal file
|
@ -0,0 +1,74 @@
|
|||
import { afterAll, describe, expect, jest, test } from '@jest/globals'
|
||||
import { hapNodeJsClientDiscover as discover } from '../../../src/adapters/discovery/hap_node_js_client'
|
||||
|
||||
const intervals: NodeJS.Timer[] = []
|
||||
|
||||
let deviceData: unknown = null
|
||||
|
||||
jest.mock('hap-node-client', () => ({
|
||||
HAPNodeJSClient: class {
|
||||
on(event: string, fn: (data: unknown) => void) {
|
||||
intervals.push(setInterval(() => fn(deviceData), 100))
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
const properDeviceData = {
|
||||
instance: {
|
||||
deviceID: 'bff926c2-ddbe-4141-b17f-f011e03e669c',
|
||||
name: 'name',
|
||||
url: 'http://bridge.local',
|
||||
},
|
||||
accessories: {
|
||||
accessories: [
|
||||
{
|
||||
services: [
|
||||
{
|
||||
type: 'SERVICE TYPE',
|
||||
characteristics: [
|
||||
{
|
||||
format: 'bool',
|
||||
value: 1,
|
||||
description: 'description',
|
||||
type: 'CHARACTERISTIC TYPE',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
const invalidDeviceData = {}
|
||||
|
||||
const config = {
|
||||
debug: false,
|
||||
pin: '123-12-123',
|
||||
refresh_interval: 10,
|
||||
discovery_timeout: 10,
|
||||
request_timeout: 10,
|
||||
}
|
||||
|
||||
describe('HAP NodeJS Client', () => {
|
||||
afterAll(() => {
|
||||
intervals.map((timer) => clearInterval(timer))
|
||||
})
|
||||
|
||||
test('Simple discovery', async () => {
|
||||
deviceData = [properDeviceData]
|
||||
expect(await discover({ config })).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('Connection pooling works', async () => {
|
||||
deviceData = [properDeviceData]
|
||||
expect(await discover({ config })).toHaveLength(1)
|
||||
|
||||
expect(await discover({ config })).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('Invalid device data is ignored', async () => {
|
||||
deviceData = [invalidDeviceData, properDeviceData]
|
||||
expect(await discover({ config })).toHaveLength(1)
|
||||
})
|
||||
})
|
|
@ -1,9 +1,8 @@
|
|||
import { describe, test } from '@jest/globals'
|
||||
import request from 'supertest'
|
||||
import { PrometheusServer } from '../../../src/prometheus'
|
||||
import { serve } from '../../../src/adapters/http/fastify'
|
||||
import { Server, createServer } from 'http'
|
||||
import type { HttpServer } from '../../../src/http'
|
||||
import { type HttpServer, fastifyServe } from '../../../src/adapters/http'
|
||||
import { type Server, createServer } from 'http'
|
||||
import { Metric } from '../../../src/metrics'
|
||||
|
||||
class TestablePrometheusServer extends PrometheusServer {
|
||||
|
@ -11,10 +10,20 @@ class TestablePrometheusServer extends PrometheusServer {
|
|||
}
|
||||
|
||||
function createTestServer(): { http: Server; prometheus: HttpServer } {
|
||||
return createTestServerWithBasicAuth({})
|
||||
}
|
||||
|
||||
function createTestServerWithBasicAuth(basicAuth: Record<string, string>): { http: Server; prometheus: HttpServer } {
|
||||
const http = createServer()
|
||||
const prometheus = new TestablePrometheusServer(0, undefined, false, 'homebridge')
|
||||
const prometheus = new TestablePrometheusServer({
|
||||
port: 0,
|
||||
interface: 'localhost',
|
||||
debug: false,
|
||||
prefix: 'homebridge',
|
||||
basic_auth: basicAuth,
|
||||
})
|
||||
prometheus.serverFactory = (handler) => http.on('request', handler)
|
||||
serve(prometheus).catch((err: Error) => {
|
||||
fastifyServe(prometheus).catch((err: Error) => {
|
||||
if (!('code' in err) || (err as unknown as { code: unknown }).code !== 'ERR_SERVER_ALREADY_LISTEN') {
|
||||
console.debug(err)
|
||||
}
|
||||
|
@ -23,6 +32,8 @@ function createTestServer(): { http: Server; prometheus: HttpServer } {
|
|||
return { http, prometheus }
|
||||
}
|
||||
|
||||
const secretAsBcrypt = '$2b$12$B8C9hsi2idheYOdSM9au0.6DbD6z44iI5dZo.72AYLsAEiNdnqNPG'
|
||||
|
||||
describe('Fastify HTTP adapter', () => {
|
||||
test('Serves 503 everywhere while metrics are not available', () => {
|
||||
return request(createTestServer().http)
|
||||
|
@ -35,7 +46,7 @@ describe('Fastify HTTP adapter', () => {
|
|||
|
||||
test('Serves 404 on / when metrics are available', () => {
|
||||
const testServer = createTestServer()
|
||||
testServer.prometheus.updateMetrics([])
|
||||
testServer.prometheus.onMetricsDiscovery([])
|
||||
|
||||
return request(testServer.http)
|
||||
.get('/')
|
||||
|
@ -47,7 +58,7 @@ describe('Fastify HTTP adapter', () => {
|
|||
test('Serves metrics', () => {
|
||||
const testServer = createTestServer()
|
||||
const timestamp = new Date('2020-01-01 00:00:00 UTC')
|
||||
testServer.prometheus.updateMetrics([
|
||||
testServer.prometheus.onMetricsDiscovery([
|
||||
new Metric('metric', 0.1, timestamp, { name: 'metric' }),
|
||||
new Metric('total_something', 100, timestamp, { name: 'counter' }),
|
||||
])
|
||||
|
@ -60,8 +71,58 @@ describe('Fastify HTTP adapter', () => {
|
|||
[
|
||||
'# TYPE homebridge_metric gauge',
|
||||
'homebridge_metric{name="metric"} 0.1 1577836800000',
|
||||
'',
|
||||
'# TYPE homebridge_something_total counter',
|
||||
'homebridge_something_total{name="counter"} 100 1577836800000',
|
||||
'',
|
||||
].join('\n'),
|
||||
)
|
||||
})
|
||||
|
||||
test('Basic auth denied without user', () => {
|
||||
const testServer = createTestServerWithBasicAuth({ joanna: secretAsBcrypt })
|
||||
testServer.prometheus.onMetricsDiscovery([])
|
||||
|
||||
return request(testServer.http)
|
||||
.get('/metrics')
|
||||
.expect(401)
|
||||
.expect('Content-Type', 'text/plain; charset=utf-8')
|
||||
.expect('Missing or bad formatted authorization header')
|
||||
})
|
||||
|
||||
test('Basic auth denied with incorrect user', () => {
|
||||
const testServer = createTestServerWithBasicAuth({ joanna: secretAsBcrypt })
|
||||
testServer.prometheus.onMetricsDiscovery([])
|
||||
|
||||
return request(testServer.http)
|
||||
.get('/metrics')
|
||||
.auth('john', 'secret')
|
||||
.expect(401)
|
||||
.expect('Content-Type', 'text/plain; charset=utf-8')
|
||||
.expect('Unauthorized')
|
||||
})
|
||||
|
||||
test('Basic auth grants access', () => {
|
||||
const testServer = createTestServerWithBasicAuth({ joanna: secretAsBcrypt })
|
||||
const timestamp = new Date('2020-01-01 00:00:00 UTC')
|
||||
testServer.prometheus.onMetricsDiscovery([
|
||||
new Metric('metric', 0.1, timestamp, { name: 'metric' }),
|
||||
new Metric('total_something', 100, timestamp, { name: 'counter' }),
|
||||
])
|
||||
|
||||
return request(testServer.http)
|
||||
.get('/metrics')
|
||||
.auth('joanna', 'secret')
|
||||
.expect(200)
|
||||
.expect('Content-Type', 'text/plain; charset=utf-8; version=0.0.4')
|
||||
.expect(
|
||||
[
|
||||
'# TYPE homebridge_metric gauge',
|
||||
'homebridge_metric{name="metric"} 0.1 1577836800000',
|
||||
'',
|
||||
'# TYPE homebridge_something_total counter',
|
||||
'homebridge_something_total{name="counter"} 100 1577836800000',
|
||||
'',
|
||||
].join('\n'),
|
||||
)
|
||||
})
|
||||
|
|
4
tests/ambient.d.ts
vendored
4
tests/ambient.d.ts
vendored
|
@ -1,5 +1,5 @@
|
|||
import { SuperTest, Test } from 'supertest'
|
||||
import { Server } from 'http'
|
||||
import type { SuperTest, Test } from 'supertest'
|
||||
import type { Server } from 'http'
|
||||
|
||||
declare module 'supertest' {
|
||||
function supertest(app: Server): SuperTest<Test>
|
||||
|
|
|
@ -6,68 +6,94 @@ describe('Render prometheus metrics', () => {
|
|||
const renderer = new MetricsRenderer('prefix')
|
||||
|
||||
test('Renders simple metric', () => {
|
||||
expect(renderer.render(new Metric('metric', 0.000001))).toEqual(
|
||||
expect(renderer.render([new Metric('metric', 0.000001)])).toEqual(
|
||||
`# TYPE prefix_metric gauge
|
||||
prefix_metric 0.000001`,
|
||||
prefix_metric 0.000001
|
||||
`,
|
||||
)
|
||||
})
|
||||
|
||||
test('Renders simple metric with timestamp', () => {
|
||||
expect(renderer.render(new Metric('metric', 0.000001, new Date('2000-01-01 00:00:00 UTC')))).toEqual(
|
||||
expect(renderer.render([new Metric('metric', 0.000001, new Date('2000-01-01 00:00:00 UTC'))])).toEqual(
|
||||
`# TYPE prefix_metric gauge
|
||||
prefix_metric 0.000001 946684800000`,
|
||||
prefix_metric 0.000001 946684800000
|
||||
`,
|
||||
)
|
||||
})
|
||||
|
||||
test('Renders simple metric with labels', () => {
|
||||
expect(
|
||||
renderer.render(
|
||||
renderer.render([
|
||||
new Metric('metric', 0.000001, new Date('2000-01-01 00:00:00 UTC'), { label: 'Some Label' }),
|
||||
),
|
||||
]),
|
||||
).toEqual(
|
||||
`# TYPE prefix_metric gauge
|
||||
prefix_metric{label="Some Label"} 0.000001 946684800000`,
|
||||
prefix_metric{label="Some Label"} 0.000001 946684800000
|
||||
`,
|
||||
)
|
||||
})
|
||||
|
||||
test('Renders total as counter', () => {
|
||||
for (const metricName of ['some_total_metric', 'some_metric_total', 'total_some_metric']) {
|
||||
expect(
|
||||
renderer.render(
|
||||
renderer.render([
|
||||
new Metric(metricName, 42, new Date('2000-01-01 00:00:00 UTC'), { label: 'Some Label' }),
|
||||
),
|
||||
]),
|
||||
).toEqual(
|
||||
`# TYPE prefix_some_metric_total counter
|
||||
prefix_some_metric_total{label="Some Label"} 42 946684800000`,
|
||||
prefix_some_metric_total{label="Some Label"} 42 946684800000
|
||||
`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('Renders multiple metrics correctly', () => {
|
||||
expect(
|
||||
renderer.render([
|
||||
new Metric('some_gauge', 10, new Date('2000-01-01 00:00:00 UTC')),
|
||||
new Metric('another_gauge', 30, new Date('2000-01-01 00:00:00 UTC')),
|
||||
new Metric('some_gauge', 20, new Date('2000-01-01 00:00:00 UTC')),
|
||||
]),
|
||||
).toEqual(
|
||||
`# TYPE prefix_some_gauge gauge
|
||||
prefix_some_gauge 10 946684800000
|
||||
prefix_some_gauge 20 946684800000
|
||||
|
||||
# TYPE prefix_another_gauge gauge
|
||||
prefix_another_gauge 30 946684800000
|
||||
`,
|
||||
)
|
||||
})
|
||||
|
||||
test('Sanitizes metric names', () => {
|
||||
expect(renderer.render(new Metric('mätric name', 0))).toEqual(
|
||||
expect(renderer.render([new Metric('mätric name', 0)])).toEqual(
|
||||
`# TYPE prefix_m_tric_name gauge
|
||||
prefix_m_tric_name 0`,
|
||||
prefix_m_tric_name 0
|
||||
`,
|
||||
)
|
||||
})
|
||||
|
||||
test('Sanitizes label names', () => {
|
||||
expect(renderer.render(new Metric('metric', 0, null, { 'yet another label': 'foo' }))).toEqual(
|
||||
expect(renderer.render([new Metric('metric', 0, null, { 'yet another label': 'foo' })])).toEqual(
|
||||
`# TYPE prefix_metric gauge
|
||||
prefix_metric{yet_another_label="foo"} 0`,
|
||||
prefix_metric{yet_another_label="foo"} 0
|
||||
`,
|
||||
)
|
||||
})
|
||||
|
||||
test('Escapes newlines in attribute value', () => {
|
||||
expect(renderer.render(new Metric('metric', 0, null, { label: 'foo\nbar' }))).toEqual(
|
||||
expect(renderer.render([new Metric('metric', 0, null, { label: 'foo\nbar' })])).toEqual(
|
||||
`# TYPE prefix_metric gauge
|
||||
prefix_metric{label="foo\\nbar"} 0`,
|
||||
prefix_metric{label="foo\\nbar"} 0
|
||||
`,
|
||||
)
|
||||
})
|
||||
|
||||
test('Escapes quotes in attribute value', () => {
|
||||
expect(renderer.render(new Metric('metric', 0, null, { label: 'foo"bar' }))).toEqual(
|
||||
expect(renderer.render([new Metric('metric', 0, null, { label: 'foo"bar' })])).toEqual(
|
||||
`# TYPE prefix_metric gauge
|
||||
prefix_metric{label="foo\\"bar"} 0`,
|
||||
prefix_metric{label="foo\\"bar"} 0
|
||||
`,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
|
@ -10,9 +10,11 @@
|
|||
"rootDir": "./",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"importsNotUsedAsValues": "error",
|
||||
"verbatimModuleSyntax": false,
|
||||
"noImplicitAny": true,
|
||||
"resolveJsonModule": true
|
||||
"resolveJsonModule": true,
|
||||
"tsBuildInfoFile": ".tsbuildinfo",
|
||||
"incremental": true
|
||||
},
|
||||
"include": ["src/", "tests/"],
|
||||
"exclude": []
|
||||
|
|
Loading…
Add table
Reference in a new issue