@layerall/plugin-prometheus 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sidarta Veloso
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 ADDED
@@ -0,0 +1,78 @@
1
+ # @layerall/plugin-prometheus
2
+
3
+ > Prometheus observer pronto para o `Router` do `@layerall/core` — métricas automáticas via `prom-client`.
4
+
5
+ ## Instalação
6
+
7
+ ```bash
8
+ npm install @layerall/core @layerall/plugin-prometheus prom-client
9
+ ```
10
+
11
+ > `prom-client` é uma peer dependency — você precisa instalá-lo no seu backend.
12
+
13
+ ## Métricas expostas
14
+
15
+ | Métrica | Tipo | Labels |
16
+ |---|---|---|
17
+ | `layerall_requests_total` | Counter | `provider`, `operation`, `status` |
18
+ | `layerall_latency_seconds` | Histogram | `provider`, `operation` |
19
+ | `layerall_attempts_total` | Counter | `provider`, `operation`, `result` |
20
+ | `layerall_errors_total` | Counter | `provider`, `code` |
21
+
22
+ O prefixo `layerall_` é configurável (`prefix: 'allx_'`).
23
+
24
+ ## Uso básico
25
+
26
+ ```ts
27
+ import { PrometheusObserver } from '@layerall/plugin-prometheus';
28
+ import { Router } from '@layerall/core';
29
+
30
+ const observer = new PrometheusObserver();
31
+ const router = new Router({ providers, policy, observer });
32
+
33
+ // no seu HTTP server
34
+ app.get('/metrics', async (_req, res) => {
35
+ res.set('Content-Type', observer.metricRegistry.contentType);
36
+ res.end(await observer.metricRegistry.metrics());
37
+ });
38
+ ```
39
+
40
+ ## Factory `createMetricsRouter`
41
+
42
+ Constrói o Router já com o observer injetado:
43
+
44
+ ```ts
45
+ import { createMetricsRouter } from '@layerall/plugin-prometheus';
46
+
47
+ const { router, observer } = createMetricsRouter({ providers, policy });
48
+
49
+ app.get('/metrics', async (_req, res) => {
50
+ res.set('Content-Type', observer.metricRegistry.contentType);
51
+ res.end(await observer.metricRegistry.metrics());
52
+ });
53
+
54
+ await router.execute('create', { data: {} });
55
+ ```
56
+
57
+ ## Registry customizada
58
+
59
+ Por padrão, as métricas vão para o registro global do `prom-client` (qualquer endpoint `/metrics` as vê). Para isolar (útil em testes), passe uma Registry própria:
60
+
61
+ ```ts
62
+ import { Registry } from 'prom-client';
63
+ import { PrometheusObserver } from '@layerall/plugin-prometheus';
64
+
65
+ const registry = new Registry();
66
+ const observer = new PrometheusObserver({ registry, prefix: 'allx_' });
67
+ ```
68
+
69
+ ## Prefixo customizado
70
+
71
+ ```ts
72
+ const observer = new PrometheusObserver({ prefix: 'allx_' });
73
+ // métricas viram allx_requests_total, allx_latency_seconds, ...
74
+ ```
75
+
76
+ ## License
77
+
78
+ MIT © Sidarta Veloso
@@ -0,0 +1,63 @@
1
+ import { Registry } from 'prom-client';
2
+ import { RouterOptions, Observer, AttemptLog, OperationResult, Router } from '@layerall/core';
3
+
4
+ interface PrometheusObserverOptions {
5
+ /**
6
+ * Registry where metrics will be registered. Defaults to the global
7
+ * `prom-client` registry so `/metrics` endpoints pick them up automatically.
8
+ * Pass a custom `Registry` to isolate metrics (useful in tests).
9
+ */
10
+ registry?: Registry;
11
+ /**
12
+ * Prefix applied to all metric names. Defaults to `layerall_`.
13
+ */
14
+ prefix?: string;
15
+ }
16
+ /**
17
+ * Observer that increments Prometheus metrics for every LayerAll Router
18
+ * execution. Register it on a `Router` (or use `createMetricsRouter`) and
19
+ * scrape `registry.metrics()` from your `/metrics` endpoint.
20
+ *
21
+ * Metrics exposed:
22
+ * - `<prefix>requests_total{provider,operation,status}` — Counter
23
+ * - `<prefix>latency_seconds{provider,operation}` — Histogram
24
+ * - `<prefix>attempts_total{provider,operation,result}` — Counter
25
+ * - `<prefix>errors_total{provider,code}` — Counter
26
+ */
27
+ declare class PrometheusObserver implements Observer {
28
+ private readonly registry;
29
+ private readonly prefix;
30
+ private readonly requestsTotal;
31
+ private readonly latencySeconds;
32
+ private readonly attemptsTotal;
33
+ private readonly errorsTotal;
34
+ constructor(opts?: PrometheusObserverOptions);
35
+ /** Registry used by this observer — exposes `metrics()` and `contentType`. */
36
+ get metricRegistry(): Registry;
37
+ onStart(): void;
38
+ onAttempt(log: AttemptLog): void;
39
+ onFinish(res: OperationResult): void;
40
+ }
41
+ interface CreateMetricsRouterOptions extends RouterOptions {
42
+ prometheus?: PrometheusObserverOptions;
43
+ }
44
+ /**
45
+ * Convenience factory: builds a `Router` with a `PrometheusObserver` already
46
+ * wired in. Returns both the router and the observer so you can scrape the
47
+ * registry from your `/metrics` endpoint.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * const { router, observer } = createMetricsRouter({ providers, policy });
52
+ * server.get('/metrics', (_req, res) => {
53
+ * res.set('Content-Type', observer.metricRegistry.contentType);
54
+ * res.end(observer.metricRegistry.metrics());
55
+ * });
56
+ * ```
57
+ */
58
+ declare function createMetricsRouter(opts: CreateMetricsRouterOptions): {
59
+ router: Router;
60
+ observer: PrometheusObserver;
61
+ };
62
+
63
+ export { type CreateMetricsRouterOptions, PrometheusObserver, type PrometheusObserverOptions, createMetricsRouter };
package/dist/index.js ADDED
@@ -0,0 +1,86 @@
1
+ // src/observer.ts
2
+ import { Counter, Histogram, register as defaultRegistry } from "prom-client";
3
+ import { Router } from "@layerall/core";
4
+ var PrometheusObserver = class {
5
+ constructor(opts = {}) {
6
+ this.registry = opts.registry ?? defaultRegistry;
7
+ this.prefix = opts.prefix ?? "layerall_";
8
+ const labels = {
9
+ requests: ["provider", "operation", "status"],
10
+ latency: ["provider", "operation"],
11
+ attempts: ["provider", "operation", "result"],
12
+ errors: ["provider", "code"]
13
+ };
14
+ this.requestsTotal = new Counter({
15
+ name: `${this.prefix}requests_total`,
16
+ help: "Total LayerAll requests by provider, operation and final status.",
17
+ labelNames: [...labels.requests],
18
+ registers: [this.registry]
19
+ });
20
+ this.latencySeconds = new Histogram({
21
+ name: `${this.prefix}latency_seconds`,
22
+ help: "LayerAll request latency in seconds, by provider and operation.",
23
+ labelNames: [...labels.latency],
24
+ buckets: [0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10],
25
+ registers: [this.registry]
26
+ });
27
+ this.attemptsTotal = new Counter({
28
+ name: `${this.prefix}attempts_total`,
29
+ help: "Total LayerAll provider attempts by provider, operation and result.",
30
+ labelNames: [...labels.attempts],
31
+ registers: [this.registry]
32
+ });
33
+ this.errorsTotal = new Counter({
34
+ name: `${this.prefix}errors_total`,
35
+ help: "Total LayerAll failed attempts by provider and error code.",
36
+ labelNames: [...labels.errors],
37
+ registers: [this.registry]
38
+ });
39
+ }
40
+ /** Registry used by this observer — exposes `metrics()` and `contentType`. */
41
+ get metricRegistry() {
42
+ return this.registry;
43
+ }
44
+ onStart() {
45
+ }
46
+ onAttempt(log) {
47
+ this.attemptsTotal.inc({
48
+ provider: log.provider,
49
+ operation: log.operation,
50
+ result: log.ok ? "ok" : "fail"
51
+ });
52
+ if (!log.ok) {
53
+ this.errorsTotal.inc({
54
+ provider: log.provider,
55
+ code: log.errorCode ?? log.error ?? "unknown"
56
+ });
57
+ }
58
+ }
59
+ onFinish(res) {
60
+ this.requestsTotal.inc({
61
+ provider: res.provider,
62
+ operation: res.operation,
63
+ status: res.status
64
+ });
65
+ this.latencySeconds.observe(
66
+ { provider: res.provider, operation: res.operation },
67
+ res.latencyMs / 1e3
68
+ );
69
+ }
70
+ };
71
+ function createMetricsRouter(opts) {
72
+ const observer = new PrometheusObserver(opts.prometheus);
73
+ const router = new Router({
74
+ providers: opts.providers,
75
+ policy: opts.policy,
76
+ tenant: opts.tenant,
77
+ observer,
78
+ defaultStrategy: opts.defaultStrategy,
79
+ defaultTimeoutMs: opts.defaultTimeoutMs
80
+ });
81
+ return { router, observer };
82
+ }
83
+ export {
84
+ PrometheusObserver,
85
+ createMetricsRouter
86
+ };
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@layerall/plugin-prometheus",
3
+ "version": "0.1.0",
4
+ "description": "Prometheus observer for LayerAll Router — ready-to-use metrics via prom-client",
5
+ "keywords": [
6
+ "prometheus",
7
+ "metrics",
8
+ "observability",
9
+ "layerall",
10
+ "prom-client",
11
+ "orchestration"
12
+ ],
13
+ "author": "Sidarta Veloso <sidartaveloso@gmail.com>",
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/sidartaveloso/layerall.git",
18
+ "directory": "packages/plugin-prometheus"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/sidartaveloso/layerall/issues"
22
+ },
23
+ "homepage": "https://github.com/sidartaveloso/layerall#readme",
24
+ "type": "module",
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "main": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js"
34
+ }
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "README.md"
39
+ ],
40
+ "dependencies": {
41
+ "@layerall/core": "0.1.0"
42
+ },
43
+ "peerDependencies": {
44
+ "prom-client": "^15.0.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "prom-client": {
48
+ "optional": true
49
+ }
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "^20.11.30",
53
+ "@vitest/coverage-v8": "^2.1.0",
54
+ "prom-client": "^15.1.0",
55
+ "tsup": "^8.3.0",
56
+ "typescript": "^5.6.0",
57
+ "vitest": "^2.1.0"
58
+ },
59
+ "scripts": {
60
+ "build": "tsup src/index.ts --format esm --dts",
61
+ "dev": "tsup src/index.ts --format esm --dts --watch",
62
+ "clean": "rm -rf dist",
63
+ "lint": "tsc --noEmit",
64
+ "typecheck": "tsc --noEmit",
65
+ "test": "vitest run --coverage",
66
+ "test:watch": "vitest",
67
+ "test:no-coverage": "vitest run"
68
+ }
69
+ }