Skip to content

Commit

Permalink
Merge pull request #3 from aegenet/feat-custom-fetch
Browse files Browse the repository at this point in the history
Feat custom `fetch` options
  • Loading branch information
aegenet authored Jan 18, 2024
2 parents 9728174 + 642471e commit 9a78ba1
Show file tree
Hide file tree
Showing 14 changed files with 753 additions and 761 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const dts = require('rollup-plugin-dts');
const path = require('node:path');
import dts from 'rollup-plugin-dts';
import path from 'node:path';

module.exports = async function(options) {
export default async function(options) {
const folder = options.folder ? options.folder + '/' : '';

return {
Expand Down
File renamed without changes.
6 changes: 0 additions & 6 deletions .yarnrc.yml

This file was deleted.

44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ npm i @aegenet/ya-vigil-reporter@~1

## 📝 Usage

### Classic

```typescript
import { YaVigilReporter } from '@aegenet/ya-vigil-reporter';

Expand All @@ -52,6 +54,41 @@ await vigilReporter.stop();
await vigilReporter.stop({ flush: true });
```


### 📝 Custom fetch

```typescript
import { YaVigilReporter } from '@aegenet/ya-vigil-reporter';
import { bFetch, type bFetchOptions } from '@aegenet/belt-fetch';

// Async DNS & cache 1mn
const bFetchOpts: bFetchOptions = {
dnsCacheTTL: 60000,
};

const vigilReporter = new YaVigilReporter({
url: "https://status.example.com",
token: "...",
probe_id: "api",
node_id: "my-backend",
replica_id: "the-one",
interval: 30,
// logger: console,
fetch(input, init) {
return bFetch(input, init, bFetchOpts);
},
});

await vigilReporter.start();

/* ... */
// stop the reporter
await vigilReporter.stop();

// or specify the flush options to teardown the replica
await vigilReporter.stop({ flush: true });
```

## 🖹 API

```typescript
Expand Down Expand Up @@ -129,6 +166,13 @@ export interface YaVigilReporterOptions {

/** Format the fetch error message */
formatFetchError?: (resp: Response) => Promise<string> | string;

/**
* fetch function
*
* @default globalThis.fetch
*/
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}
```

Expand Down
37 changes: 18 additions & 19 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,33 +36,32 @@
"report-dir": "coverage"
},
"devDependencies": {
"@fastify/pre-commit": "^2.0.2",
"@types/mocha": "^10.0.2",
"@types/node": "^20.4.5",
"@typescript-eslint/eslint-plugin": "^6.2.0",
"@typescript-eslint/parser": "^6.2.0",
"eslint": "^8.45.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"fastify": "^4.20.0",
"@aegenet/belt-fetch": "^1.3.1",
"@fastify/pre-commit": "^2.1.0",
"@types/mocha": "^10.0.6",
"@types/node": "^18",
"@typescript-eslint/eslint-plugin": "^6.19.0",
"@typescript-eslint/parser": "^6.19.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"fastify": "^4.25.2",
"json": "^11.0.0",
"mocha": "^10.1.0",
"mocha": "^10.2.0",
"nyc": "^15.1.0",
"prettier": "^3.0.0",
"rimraf": "^5.0.1",
"prettier": "^3.2.2",
"rimraf": "^5.0.5",
"rollup-plugin-dts": "^6.1.0",
"ts-mocha": "^10.0.0",
"typescript": "^5.1.6",
"vite": "^4.4.7"
"typescript": "^5.3.3",
"vite": "^5.0.11"
},
"dependencies": {},
"pre-commit": [
"lint",
"test"
],
"publishConfig": {
"registry": "https://npm.pkg.github.com"
},
"publishConfig": {},
"scripts": {
"clean": "rimraf ./build ./coverage ./.nyc_output ./node_modules",
"test": "yarn tsc && nyc ts-mocha './src/**/*.spec.ts' --timeout 10000",
Expand All @@ -71,9 +70,9 @@
"cover:report": "node ./node_modules/nyc/bin/nyc -t ./coverage report --reporter html --reporter json --reporter text-summary",
"build:version": "node ./.build/build-flow.js build",
"publish:version": "node ./.build/build-flow.js publish",
"build": "yarn tsc && yarn run build:vite && yarn run build:dts --bundleConfigAsCjs",
"build": "yarn tsc && yarn run build:vite && yarn run build:dts",
"tsc": "rimraf build && node ./node_modules/typescript/bin/tsc",
"build:vite": "rimraf dist && node ./node_modules/vite/bin/vite build",
"build:dts": "rollup -c rollup.config.dts.js"
"build:dts": "rollup -c rollup.config.dts.mjs"
}
}
9 changes: 0 additions & 9 deletions rollup.config.dts.js

This file was deleted.

10 changes: 10 additions & 0 deletions rollup.config.dts.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import config from './.build/rollup.dts.configurator.mjs';

export default config({
cwd: dirname(fileURLToPath(import.meta.url)),
libName: '@aegenet/ya-vigil-reporter',
entryPoint: 'index.ts',
nodeExternal: true,
});
7 changes: 7 additions & 0 deletions src/models/ya-vigil-reporter-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ export interface YaVigilReporterOptions {

/** Format the fetch error message */
formatFetchError?: (resp: Response) => Promise<string> | string;

/**
* fetch function
*
* @default globalThis.fetch
*/
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}

export interface YaVigilReportResult {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
export type YaFetchWTimeoutOptions = {
timeout: number;
formatErrorMessage?: (resp: Response) => Promise<string> | string;
};

/** Fetch with Timeout */
export async function yaFetchWTimeout(input: RequestInfo | URL, init: RequestInit, options: YaFetchWTimeoutOptions): Promise<Response> {
const resp = await fetch(input, {
...init,
signal: AbortSignal.timeout(options.timeout),
});
/** Ensure & format response */
export async function ensureFetchResponse(
resp: Response,
options: {
formatErrorMessage?: (resp: Response) => Promise<string> | string;
}
): Promise<void> {
if (resp && !resp.ok) {
throw new Error(options.formatErrorMessage ? await options.formatErrorMessage(resp) : await _defaultFormatErrorMessage(resp));
}
return resp;
}

async function _defaultFormatErrorMessage(resp: Response): Promise<string> {
Expand Down
30 changes: 30 additions & 0 deletions src/ya-vigil-reporter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { type YaVigilReportResult, YaVigilReporter, type IYaVigilReporter } from
import { type FastifyInstance } from 'fastify';
import { createFakeVigilServer } from './tests/create-fake-vigil-server.spec';
import { delay } from './utils/ya-workload.spec';
import { bFetch, type bFetchOptions } from '@aegenet/belt-fetch';

describe('ya-vigil-reporter', () => {
let server: FastifyInstance;
Expand Down Expand Up @@ -660,4 +661,33 @@ describe('ya-vigil-reporter', () => {
}
});
});

describe('Custom fetch', () => {
it('With bFetch', async () => {
const bFetchOpts: bFetchOptions = {
dnsCacheTTL: 1000,
};
const vigilReporter = new YaVigilReporter({
url,
token: '...',
probe_id: 'api',
node_id: 'my-backend',
replica_id: 'the-one',
interval: 30,
fetch(input, init) {
return bFetch(input, init, bFetchOpts);
},
});
const result = await vigilReporter.report();
assert.ok(!result.error);
assert.ok(result.bodySent);
assert.strictEqual(result.bodySent.replica, 'the-one');
assert.strictEqual(result.bodySent.interval, 30);
assert.ok(result.bodySent.load);
assert.ok(result.bodySent.load.cpu != null);
assert.ok(result.bodySent.load.ram != null);
assert.ok(typeof result.bodySent.load.cpu === 'number');
assert.ok(typeof result.bodySent.load.ram === 'number');
});
});
});
33 changes: 17 additions & 16 deletions src/ya-vigil-reporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { assertVigilReporterOptions, YaVigilReportResult, type YaVigilReporterOp
import { YaWorkload, type YaWorkloadResult } from './utils/ya-workload';
import type { YaVigilReportBody } from './models/ya-vigil-report-body';
import type { IYaVigilReporter } from './i-ya-vigil-reporter';
import { type YaFetchWTimeoutOptions, yaFetchWTimeout } from './utils/ya-fetch-w-timeout';
import { ensureFetchResponse } from './utils/ensure-fetch-response';

/**
* Yet Another Vigil Reporter
Expand All @@ -16,7 +16,6 @@ export class YaVigilReporter implements IYaVigilReporter {
private readonly _baseURL: string;
private readonly _reporterAuthz: string;
private readonly _reporterHeader: { Authorization: string; 'Content-Type': string };
private readonly _reportFetchWAbortOpts: YaFetchWTimeoutOptions;
private readonly _intervalMs: number;
private readonly _timeoutMs: number;
private _currentCpuUsage?: YaWorkloadResult;
Expand Down Expand Up @@ -48,10 +47,6 @@ export class YaVigilReporter implements IYaVigilReporter {
Authorization: this._reporterAuthz,
'Content-Type': 'application/json; charset=utf-8',
};
this._reportFetchWAbortOpts = {
timeout: this._timeoutMs,
formatErrorMessage: this._options.formatFetchError,
};
}

/** @inheritdoc */
Expand Down Expand Up @@ -135,14 +130,16 @@ export class YaVigilReporter implements IYaVigilReporter {
load: this._currentCpuUsage || this._workload.getCurrentUsage(),
};

await yaFetchWTimeout(
this._baseURL,
{
await ensureFetchResponse(
await this._fetch(this._baseURL, {
method: 'POST',
headers: this._reporterHeader,
body: JSON.stringify(reportBody),
},
this._reportFetchWAbortOpts
signal: AbortSignal.timeout(this._timeoutMs),
}),
{
formatErrorMessage: this._options.formatFetchError,
}
);

return {
Expand Down Expand Up @@ -173,16 +170,15 @@ export class YaVigilReporter implements IYaVigilReporter {
try {
this._options.logger?.info?.('ya-vigil-reporter.flush');

await yaFetchWTimeout(
this._baseURL + encodeURIComponent(this._options.replica_id) + '/',
{
await ensureFetchResponse(
await this._fetch(this._baseURL + encodeURIComponent(this._options.replica_id) + '/', {
method: 'DELETE',
headers: {
Authorization: this._reporterAuthz,
},
},
signal: AbortSignal.timeout(args.timeout || YaVigilReporter._DEFAULT_TIMEOUT_MS),
}),
{
timeout: args.timeout || YaVigilReporter._DEFAULT_TIMEOUT_MS,
formatErrorMessage: this._options.formatFetchError,
}
);
Expand All @@ -201,4 +197,9 @@ export class YaVigilReporter implements IYaVigilReporter {
}
}
}

/** fetch */
private get _fetch(): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {
return this._options.fetch ?? globalThis.fetch;
}
}
9 changes: 0 additions & 9 deletions vite.config.js

This file was deleted.

10 changes: 10 additions & 0 deletions vite.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { config } from './.build/vite.configurator.mjs';

export default config({
cwd: dirname(fileURLToPath(import.meta.url)),
libName: '@aegenet/ya-vigil-reporter',
entryPoint: 'index',
nodeExternal: true,
});
Loading

0 comments on commit 9a78ba1

Please sign in to comment.