@angarika/backend-metrics 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Angarika contributors
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.
@@ -0,0 +1,16 @@
1
+ import { type Server } from 'node:http';
2
+ import type { RequestMetricsPort } from '@angarika/backend-core';
3
+ /** Prometheus text format 0.0.4 без зависимостей. */
4
+ export declare class Metrics implements RequestMetricsPort {
5
+ #private;
6
+ constructor(version?: string);
7
+ recordRequest(status: number, durationMs: number, channel: string, method: string): void;
8
+ recordContact(result: 'sent' | 'honeypot' | 'error'): void;
9
+ render(): string;
10
+ }
11
+ export interface MetricsServer {
12
+ server: Server;
13
+ close(): Promise<void>;
14
+ }
15
+ /** Только loopback: публичный /metrics не отдаём. */
16
+ export declare function startMetricsServer(metrics: Metrics, port?: number, host?: string): MetricsServer;
package/dist/index.js ADDED
@@ -0,0 +1,83 @@
1
+ import { createServer } from 'node:http';
2
+ const BUCKETS = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000];
3
+ /** Prometheus text format 0.0.4 без зависимостей. */
4
+ export class Metrics {
5
+ #requests = new Map();
6
+ #buckets = BUCKETS.map(() => 0);
7
+ #version;
8
+ #count = 0;
9
+ #sum = 0;
10
+ constructor(version = '0.0.0') {
11
+ this.#version = version;
12
+ }
13
+ recordRequest(status, durationMs, channel, method) {
14
+ this.#bump(`angarika_http_requests_total{method="${method}",status="${String(status)}",channel="${channel}"}`);
15
+ this.#count += 1;
16
+ this.#sum += durationMs;
17
+ for (let index = 0; index < BUCKETS.length; index += 1) {
18
+ const bucket = BUCKETS[index];
19
+ if (bucket !== undefined && durationMs <= bucket) {
20
+ this.#buckets[index] = (this.#buckets[index] ?? 0) + 1;
21
+ }
22
+ }
23
+ }
24
+ recordContact(result) {
25
+ this.#bump(`angarika_contact_messages_total{result="${result}"}`);
26
+ }
27
+ render() {
28
+ const lines = [
29
+ '# HELP angarika_build_info Build version',
30
+ '# TYPE angarika_build_info gauge',
31
+ `angarika_build_info{version="${this.#version}"} 1`,
32
+ '# HELP angarika_contact_messages_total Contact form results',
33
+ '# TYPE angarika_contact_messages_total counter',
34
+ '# HELP angarika_http_requests_total HTTP-запросы по методу, статусу и каналу',
35
+ '# TYPE angarika_http_requests_total counter',
36
+ ];
37
+ for (const [line, value] of [...this.#requests].sort(([a], [b]) => a.localeCompare(b))) {
38
+ lines.push(`${line} ${String(value)}`);
39
+ }
40
+ lines.push('# HELP angarika_http_request_duration_ms Длительность обработки запроса, мс', '# TYPE angarika_http_request_duration_ms histogram');
41
+ for (let index = 0; index < BUCKETS.length; index += 1) {
42
+ const bucket = BUCKETS[index] ?? 0;
43
+ lines.push(`angarika_http_request_duration_ms_bucket{le="${String(bucket)}"} ${String(this.#buckets[index] ?? 0)}`);
44
+ }
45
+ lines.push(`angarika_http_request_duration_ms_bucket{le="+Inf"} ${String(this.#count)}`);
46
+ lines.push(`angarika_http_request_duration_ms_sum ${String(this.#sum)}`);
47
+ lines.push(`angarika_http_request_duration_ms_count ${String(this.#count)}`);
48
+ return `${lines.join('\n')}\n`;
49
+ }
50
+ #bump(key) {
51
+ this.#requests.set(key, (this.#requests.get(key) ?? 0) + 1);
52
+ }
53
+ }
54
+ /** Только loopback: публичный /metrics не отдаём. */
55
+ export function startMetricsServer(metrics, port = 9464, host = '127.0.0.1') {
56
+ if (!Number.isSafeInteger(port) || port <= 0) {
57
+ throw new TypeError('metrics: port должен быть положительным целым');
58
+ }
59
+ const server = createServer((request, response) => {
60
+ if (request.url !== '/' && request.url !== '/metrics') {
61
+ response.writeHead(404).end();
62
+ return;
63
+ }
64
+ response.writeHead(200, { 'content-type': 'text/plain; version=0.0.4; charset=utf-8' });
65
+ response.end(metrics.render());
66
+ });
67
+ server.listen(port, host);
68
+ // Вспомогательный listener не должен ронять сайт при EADDRINUSE.
69
+ server.on('error', () => {
70
+ server.close();
71
+ });
72
+ return {
73
+ server,
74
+ close: () => new Promise((resolve, reject) => {
75
+ server.close((error) => {
76
+ if (error === undefined)
77
+ resolve();
78
+ else
79
+ reject(error);
80
+ });
81
+ }),
82
+ };
83
+ }
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@angarika/backend-metrics",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "description": "Prometheus-метрики без зависимостей для Angarika",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "main": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "dependencies": {
14
+ "@angarika/backend-core": "^1.0.0"
15
+ },
16
+ "devDependencies": {
17
+ "@types/node": "^26.6.11",
18
+ "typescript": "5.9.3",
19
+ "vitest": "3.2.4"
20
+ },
21
+ "scripts": {
22
+ "build": "tsc -p tsconfig.build.json",
23
+ "typecheck": "tsc --noEmit",
24
+ "test": "vitest run"
25
+ }
6
26
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.