@application-kit/observability 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # @application-kit/observability
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2f8c709: Первый выпуск: вход `/metrics` — `MetricsRegistry` (реестр Prometheus с метриками процесса Node), RED-гистограммы
8
+ `HttpMetrics` (ярлык маршрута — шаблон пути, `resolveRouteLabel`) и `GraphqlMetrics` (ярлык operation — корневые поля
9
+ документа, адаптер хуков `asMercuriusHook`), `startMetricsServer` — HTTP-сервер `/metrics` для процессов без веб-слоя.
10
+ Peer `graphql` — optional: из него берутся только типы, нужен лишь GraphQL-гистограмме.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 application-kit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # @application-kit/observability
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Наблюдаемость NestJS-процесса. Первый вход — `/metrics`: реестр Prometheus с метриками процесса Node, RED-гистограммы
4
+ HTTP и GraphQL и HTTP-сервер экспозиции для процессов без своего веб-слоя. Пакет не знает ни маршрутов, ни схемы,
5
+ ни портов приложения: ярлыки и порт приходят параметрами, а хуки веб-сервера и контроллер скрейпа остаются у потребителя.
6
+
7
+ ## Установка
8
+
9
+ ```sh
10
+ yarn add @application-kit/observability
11
+ ```
12
+
13
+ Peer-зависимости: `@nestjs/common`, `@prometheus-io/client`; `graphql` — optional, нужен только GraphQL-гистограмме
14
+ (из него берутся типы документа, сам вход грузится и без него).
15
+
16
+ ## Входы
17
+
18
+ | Вход | Для чего | Тянет |
19
+ |------|----------|-------|
20
+ | `@application-kit/observability/metrics` | реестр, гистограммы HTTP и GraphQL, сервер `/metrics` | `@nestjs/common`, `@prometheus-io/client` |
21
+
22
+ Корневого входа нет: каждый вход несёт свои peer-зависимости, и лишнего потребитель не ставит.
23
+
24
+ ## Метрики
25
+
26
+ - `MetricsRegistry` — провайдер с собственным `Registry` (не глобальным: экземпляры независимы) и метриками процесса
27
+ из коробки клиента; `render()` отдаёт экспозицию, `contentType` — её заголовок.
28
+ - `HttpMetrics` — гистограмма `http_request_duration_seconds{method,route,status}`. Ярлык `route` — ШАБЛОН маршрута
29
+ (`/users/:id`), не URL: `resolveRouteLabel(routeUrl)` подставляет `UNMATCHED_ROUTE` для запросов мимо маршрутов.
30
+ - `GraphqlMetrics` — гистограмма `graphql_operation_duration_seconds{operation,outcome,type}`. Ярлык `operation` —
31
+ отсортированные корневые поля документа (`describeOperation`), не `operationName` клиента. Жизненный цикл —
32
+ `start(key)` → `describe(key, document)` → `finish(key, hasErrors)`, где `key` — объект контекста запроса;
33
+ `asMercuriusHook` оборачивает синхронный обработчик в async-хук Mercurius.
34
+ - `DURATION_BUCKETS_SECONDS` — общие границы гистограмм, от 5 мс до 10 с.
35
+
36
+ ```ts
37
+ app.register(async (instance) => {
38
+ instance.addHook('onResponse', (request, reply, done) => {
39
+ httpMetrics.observe({
40
+ durationSeconds: reply.elapsedTime / 1000,
41
+ method: request.method,
42
+ route: resolveRouteLabel(request.routeOptions.url),
43
+ status: reply.statusCode,
44
+ })
45
+ done()
46
+ })
47
+ })
48
+ ```
49
+
50
+ ## Сервер `/metrics` без веб-слоя
51
+
52
+ Процессу без HTTP (консьюмер очереди как Nest-микросервис) негде отдать экспозицию — `startMetricsServer` поднимает
53
+ минимальный `node:http`-сервер на отдельном порту: `/metrics` отдаёт реестр, остальное — 404, ошибка рендера — 500
54
+ и вызов `onError` вместо падения процесса.
55
+
56
+ ```ts
57
+ const server = startMetricsServer({ onError: (error) => logger.error(error), port: 9464, registry })
58
+ ```
@@ -0,0 +1,20 @@
1
+ import type { DocumentNode } from 'graphql';
2
+ import { MetricsRegistry } from './metrics.registry.js';
3
+ declare const UNKNOWN_OPERATION = "unknown";
4
+ interface OperationDescriptionInterface {
5
+ operation: string;
6
+ type: string;
7
+ }
8
+ declare const describeOperation: (document: DocumentNode) => OperationDescriptionInterface;
9
+ type MercuriusHook<TArguments extends unknown[]> = (...arguments_: TArguments) => Promise<void>;
10
+ declare class GraphqlMetrics {
11
+ private readonly metricsRegistry;
12
+ private readonly operationDuration;
13
+ private readonly pending;
14
+ constructor(metricsRegistry: MetricsRegistry);
15
+ describe(key: object, document: DocumentNode): void;
16
+ finish(key: object, hasErrors: boolean): void;
17
+ start(key: object): void;
18
+ }
19
+ declare const asMercuriusHook: <TArguments extends unknown[]>(handler: (...arguments_: TArguments) => void) => MercuriusHook<TArguments>;
20
+ export { asMercuriusHook, describeOperation, GraphqlMetrics, UNKNOWN_OPERATION };
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.UNKNOWN_OPERATION = exports.GraphqlMetrics = exports.describeOperation = exports.asMercuriusHook = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const client_1 = require("@prometheus-io/client");
15
+ const node_perf_hooks_1 = require("node:perf_hooks");
16
+ const http_metrics_js_1 = require("./http-metrics.js");
17
+ const metrics_registry_js_1 = require("./metrics.registry.js");
18
+ const UNKNOWN_OPERATION = 'unknown';
19
+ exports.UNKNOWN_OPERATION = UNKNOWN_OPERATION;
20
+ const OPERATION_LABEL_MAX_LENGTH = 60;
21
+ const OPERATION_DEFINITION_KIND = 'OperationDefinition';
22
+ const FIELD_KIND = 'Field';
23
+ const kindOf = (node) => node.kind;
24
+ const isOperationDefinition = (node) => kindOf(node) === OPERATION_DEFINITION_KIND;
25
+ const isField = (selection) => kindOf(selection) === FIELD_KIND;
26
+ const describeOperation = (document) => {
27
+ const definition = document.definitions.find(isOperationDefinition);
28
+ if (definition === undefined) {
29
+ return { operation: UNKNOWN_OPERATION, type: UNKNOWN_OPERATION };
30
+ }
31
+ const fields = definition.selectionSet.selections
32
+ .filter(isField)
33
+ .map((selection) => selection.name.value)
34
+ .toSorted((first, second) => first.localeCompare(second));
35
+ const operation = fields.length === 0
36
+ ? UNKNOWN_OPERATION
37
+ : fields.join('+').slice(0, OPERATION_LABEL_MAX_LENGTH);
38
+ return { operation, type: definition.operation };
39
+ };
40
+ exports.describeOperation = describeOperation;
41
+ let GraphqlMetrics = class GraphqlMetrics {
42
+ metricsRegistry;
43
+ operationDuration;
44
+ pending = new WeakMap();
45
+ constructor(metricsRegistry) {
46
+ this.metricsRegistry = metricsRegistry;
47
+ this.operationDuration = new client_1.Histogram({
48
+ buckets: http_metrics_js_1.DURATION_BUCKETS_SECONDS,
49
+ help: 'Длительность GraphQL-операции, секунды',
50
+ labelNames: ['operation', 'outcome', 'type'],
51
+ name: 'graphql_operation_duration_seconds',
52
+ registers: [this.metricsRegistry.registry],
53
+ });
54
+ }
55
+ describe(key, document) {
56
+ const started = this.pending.get(key);
57
+ this.pending.set(key, {
58
+ ...describeOperation(document),
59
+ startedAt: started?.startedAt ?? node_perf_hooks_1.performance.now(),
60
+ });
61
+ }
62
+ finish(key, hasErrors) {
63
+ const started = this.pending.get(key);
64
+ if (started === undefined) {
65
+ return;
66
+ }
67
+ this.pending.delete(key);
68
+ this.operationDuration.observe({
69
+ operation: started.operation,
70
+ outcome: hasErrors ? 'error' : 'ok',
71
+ type: started.type,
72
+ }, (node_perf_hooks_1.performance.now() - started.startedAt) / 1000);
73
+ }
74
+ start(key) {
75
+ this.pending.set(key, { operation: UNKNOWN_OPERATION, startedAt: node_perf_hooks_1.performance.now(), type: UNKNOWN_OPERATION });
76
+ }
77
+ };
78
+ exports.GraphqlMetrics = GraphqlMetrics;
79
+ exports.GraphqlMetrics = GraphqlMetrics = __decorate([
80
+ (0, common_1.Injectable)(),
81
+ __metadata("design:paramtypes", [metrics_registry_js_1.MetricsRegistry])
82
+ ], GraphqlMetrics);
83
+ const asMercuriusHook = (handler) => {
84
+ const hook = async (...arguments_) => {
85
+ handler(...arguments_);
86
+ };
87
+ return hook;
88
+ };
89
+ exports.asMercuriusHook = asMercuriusHook;
@@ -0,0 +1,17 @@
1
+ import { MetricsRegistry } from './metrics.registry.js';
2
+ declare const UNMATCHED_ROUTE = "unmatched";
3
+ declare const DURATION_BUCKETS_SECONDS: number[];
4
+ interface HttpSampleInterface {
5
+ durationSeconds: number;
6
+ method: string;
7
+ route: string;
8
+ status: number;
9
+ }
10
+ declare const resolveRouteLabel: (routeUrl?: string) => string;
11
+ declare class HttpMetrics {
12
+ private readonly metricsRegistry;
13
+ private readonly requestDuration;
14
+ constructor(metricsRegistry: MetricsRegistry);
15
+ observe({ durationSeconds, method, route, status }: HttpSampleInterface): void;
16
+ }
17
+ export { DURATION_BUCKETS_SECONDS, HttpMetrics, resolveRouteLabel, UNMATCHED_ROUTE };
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.UNMATCHED_ROUTE = exports.resolveRouteLabel = exports.HttpMetrics = exports.DURATION_BUCKETS_SECONDS = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const client_1 = require("@prometheus-io/client");
15
+ const metrics_registry_js_1 = require("./metrics.registry.js");
16
+ const UNMATCHED_ROUTE = 'unmatched';
17
+ exports.UNMATCHED_ROUTE = UNMATCHED_ROUTE;
18
+ const DURATION_BUCKETS_SECONDS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
19
+ exports.DURATION_BUCKETS_SECONDS = DURATION_BUCKETS_SECONDS;
20
+ const resolveRouteLabel = (routeUrl) => (routeUrl === undefined || routeUrl === '' ? UNMATCHED_ROUTE : routeUrl);
21
+ exports.resolveRouteLabel = resolveRouteLabel;
22
+ let HttpMetrics = class HttpMetrics {
23
+ metricsRegistry;
24
+ requestDuration;
25
+ constructor(metricsRegistry) {
26
+ this.metricsRegistry = metricsRegistry;
27
+ this.requestDuration = new client_1.Histogram({
28
+ buckets: DURATION_BUCKETS_SECONDS,
29
+ help: 'Длительность обработки HTTP-запроса, секунды',
30
+ labelNames: ['method', 'route', 'status'],
31
+ name: 'http_request_duration_seconds',
32
+ registers: [this.metricsRegistry.registry],
33
+ });
34
+ }
35
+ observe({ durationSeconds, method, route, status }) {
36
+ this.requestDuration.observe({ method, route, status }, durationSeconds);
37
+ }
38
+ };
39
+ exports.HttpMetrics = HttpMetrics;
40
+ exports.HttpMetrics = HttpMetrics = __decorate([
41
+ (0, common_1.Injectable)(),
42
+ __metadata("design:paramtypes", [metrics_registry_js_1.MetricsRegistry])
43
+ ], HttpMetrics);
@@ -0,0 +1,4 @@
1
+ export * from './graphql-metrics.js';
2
+ export * from './http-metrics.js';
3
+ export * from './metrics-http-server.js';
4
+ export * from './metrics.registry.js';
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./graphql-metrics.js"), exports);
18
+ __exportStar(require("./http-metrics.js"), exports);
19
+ __exportStar(require("./metrics-http-server.js"), exports);
20
+ __exportStar(require("./metrics.registry.js"), exports);
@@ -0,0 +1,10 @@
1
+ import type { Server } from 'node:http';
2
+ import type { MetricsRegistry } from './metrics.registry.js';
3
+ type MetricsServerErrorHandler = (error: unknown) => void;
4
+ interface MetricsServerOptionsInterface {
5
+ onError?: MetricsServerErrorHandler | undefined;
6
+ port: number;
7
+ registry: MetricsRegistry;
8
+ }
9
+ declare const startMetricsServer: ({ onError, port, registry }: MetricsServerOptionsInterface) => Server;
10
+ export { startMetricsServer };
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startMetricsServer = void 0;
4
+ const node_http_1 = require("node:http");
5
+ const METRICS_PATH = '/metrics';
6
+ const NOT_FOUND = 404;
7
+ const OK = 200;
8
+ const SERVER_ERROR = 500;
9
+ const renderMetrics = async (registry, response, onError) => {
10
+ try {
11
+ const exposition = await registry.render();
12
+ response.writeHead(OK, { 'Content-Type': registry.contentType });
13
+ response.end(exposition);
14
+ }
15
+ catch (error) {
16
+ response.writeHead(SERVER_ERROR);
17
+ response.end();
18
+ onError?.(error);
19
+ }
20
+ };
21
+ const respond = async (registry, request, response, onError) => {
22
+ if (request.url !== METRICS_PATH) {
23
+ response.writeHead(NOT_FOUND);
24
+ response.end();
25
+ return;
26
+ }
27
+ await renderMetrics(registry, response, onError);
28
+ };
29
+ const startMetricsServer = ({ onError, port, registry }) => {
30
+ const server = (0, node_http_1.createServer)((request, response) => {
31
+ void respond(registry, request, response, onError);
32
+ });
33
+ server.listen(port, '0.0.0.0');
34
+ return server;
35
+ };
36
+ exports.startMetricsServer = startMetricsServer;
@@ -0,0 +1,8 @@
1
+ import { Registry } from '@prometheus-io/client';
2
+ declare class MetricsRegistry {
3
+ readonly registry: Registry<import("@prometheus-io/client").RegistryContentType>;
4
+ get contentType(): string;
5
+ constructor();
6
+ render(): Promise<string>;
7
+ }
8
+ export { MetricsRegistry };
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MetricsRegistry = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const client_1 = require("@prometheus-io/client");
15
+ let MetricsRegistry = class MetricsRegistry {
16
+ registry = new client_1.Registry();
17
+ get contentType() {
18
+ return this.registry.contentType;
19
+ }
20
+ constructor() {
21
+ (0, client_1.collectDefaultMetrics)({ register: this.registry });
22
+ }
23
+ async render() {
24
+ return this.registry.metrics();
25
+ }
26
+ };
27
+ exports.MetricsRegistry = MetricsRegistry;
28
+ exports.MetricsRegistry = MetricsRegistry = __decorate([
29
+ (0, common_1.Injectable)(),
30
+ __metadata("design:paramtypes", [])
31
+ ], MetricsRegistry);
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,20 @@
1
+ import type { DocumentNode } from 'graphql';
2
+ import { MetricsRegistry } from './metrics.registry.js';
3
+ declare const UNKNOWN_OPERATION = "unknown";
4
+ interface OperationDescriptionInterface {
5
+ operation: string;
6
+ type: string;
7
+ }
8
+ declare const describeOperation: (document: DocumentNode) => OperationDescriptionInterface;
9
+ type MercuriusHook<TArguments extends unknown[]> = (...arguments_: TArguments) => Promise<void>;
10
+ declare class GraphqlMetrics {
11
+ private readonly metricsRegistry;
12
+ private readonly operationDuration;
13
+ private readonly pending;
14
+ constructor(metricsRegistry: MetricsRegistry);
15
+ describe(key: object, document: DocumentNode): void;
16
+ finish(key: object, hasErrors: boolean): void;
17
+ start(key: object): void;
18
+ }
19
+ declare const asMercuriusHook: <TArguments extends unknown[]>(handler: (...arguments_: TArguments) => void) => MercuriusHook<TArguments>;
20
+ export { asMercuriusHook, describeOperation, GraphqlMetrics, UNKNOWN_OPERATION };
@@ -0,0 +1,83 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Injectable } from '@nestjs/common';
11
+ import { Histogram } from '@prometheus-io/client';
12
+ import { performance } from 'node:perf_hooks';
13
+ import { DURATION_BUCKETS_SECONDS } from './http-metrics.js';
14
+ import { MetricsRegistry } from './metrics.registry.js';
15
+ const UNKNOWN_OPERATION = 'unknown';
16
+ const OPERATION_LABEL_MAX_LENGTH = 60;
17
+ const OPERATION_DEFINITION_KIND = 'OperationDefinition';
18
+ const FIELD_KIND = 'Field';
19
+ const kindOf = (node) => node.kind;
20
+ const isOperationDefinition = (node) => kindOf(node) === OPERATION_DEFINITION_KIND;
21
+ const isField = (selection) => kindOf(selection) === FIELD_KIND;
22
+ const describeOperation = (document) => {
23
+ const definition = document.definitions.find(isOperationDefinition);
24
+ if (definition === undefined) {
25
+ return { operation: UNKNOWN_OPERATION, type: UNKNOWN_OPERATION };
26
+ }
27
+ const fields = definition.selectionSet.selections
28
+ .filter(isField)
29
+ .map((selection) => selection.name.value)
30
+ .toSorted((first, second) => first.localeCompare(second));
31
+ const operation = fields.length === 0
32
+ ? UNKNOWN_OPERATION
33
+ : fields.join('+').slice(0, OPERATION_LABEL_MAX_LENGTH);
34
+ return { operation, type: definition.operation };
35
+ };
36
+ let GraphqlMetrics = class GraphqlMetrics {
37
+ metricsRegistry;
38
+ operationDuration;
39
+ pending = new WeakMap();
40
+ constructor(metricsRegistry) {
41
+ this.metricsRegistry = metricsRegistry;
42
+ this.operationDuration = new Histogram({
43
+ buckets: DURATION_BUCKETS_SECONDS,
44
+ help: 'Длительность GraphQL-операции, секунды',
45
+ labelNames: ['operation', 'outcome', 'type'],
46
+ name: 'graphql_operation_duration_seconds',
47
+ registers: [this.metricsRegistry.registry],
48
+ });
49
+ }
50
+ describe(key, document) {
51
+ const started = this.pending.get(key);
52
+ this.pending.set(key, {
53
+ ...describeOperation(document),
54
+ startedAt: started?.startedAt ?? performance.now(),
55
+ });
56
+ }
57
+ finish(key, hasErrors) {
58
+ const started = this.pending.get(key);
59
+ if (started === undefined) {
60
+ return;
61
+ }
62
+ this.pending.delete(key);
63
+ this.operationDuration.observe({
64
+ operation: started.operation,
65
+ outcome: hasErrors ? 'error' : 'ok',
66
+ type: started.type,
67
+ }, (performance.now() - started.startedAt) / 1000);
68
+ }
69
+ start(key) {
70
+ this.pending.set(key, { operation: UNKNOWN_OPERATION, startedAt: performance.now(), type: UNKNOWN_OPERATION });
71
+ }
72
+ };
73
+ GraphqlMetrics = __decorate([
74
+ Injectable(),
75
+ __metadata("design:paramtypes", [MetricsRegistry])
76
+ ], GraphqlMetrics);
77
+ const asMercuriusHook = (handler) => {
78
+ const hook = async (...arguments_) => {
79
+ handler(...arguments_);
80
+ };
81
+ return hook;
82
+ };
83
+ export { asMercuriusHook, describeOperation, GraphqlMetrics, UNKNOWN_OPERATION };
@@ -0,0 +1,17 @@
1
+ import { MetricsRegistry } from './metrics.registry.js';
2
+ declare const UNMATCHED_ROUTE = "unmatched";
3
+ declare const DURATION_BUCKETS_SECONDS: number[];
4
+ interface HttpSampleInterface {
5
+ durationSeconds: number;
6
+ method: string;
7
+ route: string;
8
+ status: number;
9
+ }
10
+ declare const resolveRouteLabel: (routeUrl?: string) => string;
11
+ declare class HttpMetrics {
12
+ private readonly metricsRegistry;
13
+ private readonly requestDuration;
14
+ constructor(metricsRegistry: MetricsRegistry);
15
+ observe({ durationSeconds, method, route, status }: HttpSampleInterface): void;
16
+ }
17
+ export { DURATION_BUCKETS_SECONDS, HttpMetrics, resolveRouteLabel, UNMATCHED_ROUTE };
@@ -0,0 +1,37 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Injectable } from '@nestjs/common';
11
+ import { Histogram } from '@prometheus-io/client';
12
+ import { MetricsRegistry } from './metrics.registry.js';
13
+ const UNMATCHED_ROUTE = 'unmatched';
14
+ const DURATION_BUCKETS_SECONDS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
15
+ const resolveRouteLabel = (routeUrl) => (routeUrl === undefined || routeUrl === '' ? UNMATCHED_ROUTE : routeUrl);
16
+ let HttpMetrics = class HttpMetrics {
17
+ metricsRegistry;
18
+ requestDuration;
19
+ constructor(metricsRegistry) {
20
+ this.metricsRegistry = metricsRegistry;
21
+ this.requestDuration = new Histogram({
22
+ buckets: DURATION_BUCKETS_SECONDS,
23
+ help: 'Длительность обработки HTTP-запроса, секунды',
24
+ labelNames: ['method', 'route', 'status'],
25
+ name: 'http_request_duration_seconds',
26
+ registers: [this.metricsRegistry.registry],
27
+ });
28
+ }
29
+ observe({ durationSeconds, method, route, status }) {
30
+ this.requestDuration.observe({ method, route, status }, durationSeconds);
31
+ }
32
+ };
33
+ HttpMetrics = __decorate([
34
+ Injectable(),
35
+ __metadata("design:paramtypes", [MetricsRegistry])
36
+ ], HttpMetrics);
37
+ export { DURATION_BUCKETS_SECONDS, HttpMetrics, resolveRouteLabel, UNMATCHED_ROUTE };
@@ -0,0 +1,4 @@
1
+ export * from './graphql-metrics.js';
2
+ export * from './http-metrics.js';
3
+ export * from './metrics-http-server.js';
4
+ export * from './metrics.registry.js';
@@ -0,0 +1,4 @@
1
+ export * from './graphql-metrics.js';
2
+ export * from './http-metrics.js';
3
+ export * from './metrics-http-server.js';
4
+ export * from './metrics.registry.js';
@@ -0,0 +1,10 @@
1
+ import type { Server } from 'node:http';
2
+ import type { MetricsRegistry } from './metrics.registry.js';
3
+ type MetricsServerErrorHandler = (error: unknown) => void;
4
+ interface MetricsServerOptionsInterface {
5
+ onError?: MetricsServerErrorHandler | undefined;
6
+ port: number;
7
+ registry: MetricsRegistry;
8
+ }
9
+ declare const startMetricsServer: ({ onError, port, registry }: MetricsServerOptionsInterface) => Server;
10
+ export { startMetricsServer };
@@ -0,0 +1,33 @@
1
+ import { createServer } from 'node:http';
2
+ const METRICS_PATH = '/metrics';
3
+ const NOT_FOUND = 404;
4
+ const OK = 200;
5
+ const SERVER_ERROR = 500;
6
+ const renderMetrics = async (registry, response, onError) => {
7
+ try {
8
+ const exposition = await registry.render();
9
+ response.writeHead(OK, { 'Content-Type': registry.contentType });
10
+ response.end(exposition);
11
+ }
12
+ catch (error) {
13
+ response.writeHead(SERVER_ERROR);
14
+ response.end();
15
+ onError?.(error);
16
+ }
17
+ };
18
+ const respond = async (registry, request, response, onError) => {
19
+ if (request.url !== METRICS_PATH) {
20
+ response.writeHead(NOT_FOUND);
21
+ response.end();
22
+ return;
23
+ }
24
+ await renderMetrics(registry, response, onError);
25
+ };
26
+ const startMetricsServer = ({ onError, port, registry }) => {
27
+ const server = createServer((request, response) => {
28
+ void respond(registry, request, response, onError);
29
+ });
30
+ server.listen(port, '0.0.0.0');
31
+ return server;
32
+ };
33
+ export { startMetricsServer };
@@ -0,0 +1,8 @@
1
+ import { Registry } from '@prometheus-io/client';
2
+ declare class MetricsRegistry {
3
+ readonly registry: Registry<import("@prometheus-io/client").RegistryContentType>;
4
+ get contentType(): string;
5
+ constructor();
6
+ render(): Promise<string>;
7
+ }
8
+ export { MetricsRegistry };
@@ -0,0 +1,28 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Injectable } from '@nestjs/common';
11
+ import { collectDefaultMetrics, Registry } from '@prometheus-io/client';
12
+ let MetricsRegistry = class MetricsRegistry {
13
+ registry = new Registry();
14
+ get contentType() {
15
+ return this.registry.contentType;
16
+ }
17
+ constructor() {
18
+ collectDefaultMetrics({ register: this.registry });
19
+ }
20
+ async render() {
21
+ return this.registry.metrics();
22
+ }
23
+ };
24
+ MetricsRegistry = __decorate([
25
+ Injectable(),
26
+ __metadata("design:paramtypes", [])
27
+ ], MetricsRegistry);
28
+ export { MetricsRegistry };
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "@application-kit/observability",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Наблюдаемость NestJS-процесса: реестр метрик Prometheus, RED-гистограммы HTTP и GraphQL, HTTP-сервер /metrics для процессов без веб-слоя",
5
+ "keywords": [
6
+ "metrics",
7
+ "nestjs",
8
+ "observability",
9
+ "prometheus"
10
+ ],
11
+ "homepage": "https://gitlab.com/application-kit/application-kit/-/tree/main/packages/observability",
12
+ "bugs": "https://gitlab.com/application-kit/application-kit/-/issues",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://gitlab.com/application-kit/application-kit.git",
16
+ "directory": "packages/observability"
17
+ },
18
+ "license": "MIT",
19
+ "author": {
20
+ "name": "application-kit"
21
+ },
22
+ "sideEffects": false,
23
+ "type": "module",
24
+ "exports": {
25
+ "./metrics": {
26
+ "import": {
27
+ "types": "./dist/esm/metrics/index.d.ts",
28
+ "default": "./dist/esm/metrics/index.js"
29
+ },
30
+ "require": {
31
+ "types": "./dist/cjs/metrics/index.d.ts",
32
+ "default": "./dist/cjs/metrics/index.js"
33
+ }
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "main": "./dist/cjs/metrics/index.js",
38
+ "module": "./dist/esm/metrics/index.js",
39
+ "types": "./dist/cjs/metrics/index.d.ts",
40
+ "files": [
41
+ "dist"
42
+ ],
43
+ "scripts": {
44
+ "build": "rm -rf ./dist && node ../../scripts/barrels.mjs create ./src/metrics && tsc --project tsconfig.build.json && tsc --project tsconfig.build.cjs.json && node ../../scripts/barrels.mjs clean ./src && node ../../scripts/mark-cjs.mjs ./dist/cjs",
45
+ "lint:tsc": "tsc --noEmit --pretty --project .",
46
+ "test:mutation": "stryker run",
47
+ "test:unit": "vitest run"
48
+ },
49
+ "devDependencies": {
50
+ "@nestjs/common": "^11.2.7",
51
+ "@prometheus-io/client": "^0.16.0",
52
+ "@stryker-mutator/core": "^10.0.0",
53
+ "@stryker-mutator/vitest-runner": "^10.0.0",
54
+ "@types/node": "^26.2.0",
55
+ "graphql": "^16.14.2",
56
+ "reflect-metadata": "^0.2.2",
57
+ "rxjs": "^7.8.2",
58
+ "typescript": "^6.0.3",
59
+ "vitest": "^4.1.11"
60
+ },
61
+ "peerDependencies": {
62
+ "@nestjs/common": "^11.0.0",
63
+ "@prometheus-io/client": "^0.16.0",
64
+ "graphql": "^16.0.0"
65
+ },
66
+ "peerDependenciesMeta": {
67
+ "graphql": {
68
+ "optional": true
69
+ }
70
+ },
71
+ "engines": {
72
+ "node": ">=24"
73
+ },
74
+ "publishConfig": {
75
+ "access": "public"
76
+ }
6
77
  }