@macss/modular-api 0.4.3 → 0.4.4

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.
@@ -21,6 +21,9 @@ function worstStatus(a, b) {
21
21
  * Result returned by a single {@link HealthCheck}.
22
22
  */
23
23
  class HealthCheckResult {
24
+ status;
25
+ responseTime;
26
+ output;
24
27
  constructor(status, options) {
25
28
  this.status = status;
26
29
  this.responseTime = options?.responseTime;
@@ -13,6 +13,10 @@ const health_check_1 = require("./health_check");
13
13
  * `httpStatusCode`: 200 for pass/warn, 503 for fail.
14
14
  */
15
15
  class HealthResponse {
16
+ status;
17
+ version;
18
+ releaseId;
19
+ checks;
16
20
  constructor(options) {
17
21
  this.status = options.status;
18
22
  this.version = options.version;
@@ -51,8 +55,10 @@ exports.HealthResponse = HealthResponse;
51
55
  * ```
52
56
  */
53
57
  class HealthService {
58
+ version;
59
+ releaseId;
60
+ checks = [];
54
61
  constructor(options) {
55
- this.checks = [];
56
62
  this.version = options.version;
57
63
  this.releaseId = options.releaseId ?? process.env.RELEASE_ID ?? `${options.version}-debug`;
58
64
  }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Signals that the raw JSON payload failed structural validation
3
+ * (missing required field or wrong JSON type).
4
+ *
5
+ * The handler catches this and returns HTTP 400 with `{ error: message }`.
6
+ * Business-rule validation belongs in `UseCase.validate()` instead.
7
+ */
8
+ export declare class InputValidationError extends Error {
9
+ constructor(message: string);
10
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // core/input_validation_error.ts
4
+ // Thrown by Input.validateJson when required fields are missing
5
+ // or have the wrong JSON type.
6
+ //
7
+ // Error message contract (identical across all 3 SDKs for parity):
8
+ // - "Missing required field: {name}"
9
+ // - "Field '{name}' must be of type {type}"
10
+ // ============================================================
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.InputValidationError = void 0;
13
+ /**
14
+ * Signals that the raw JSON payload failed structural validation
15
+ * (missing required field or wrong JSON type).
16
+ *
17
+ * The handler catches this and returns HTTP 400 with `{ error: message }`.
18
+ * Business-rule validation belongs in `UseCase.validate()` instead.
19
+ */
20
+ class InputValidationError extends Error {
21
+ constructor(message) {
22
+ super(message);
23
+ this.name = 'InputValidationError';
24
+ }
25
+ }
26
+ exports.InputValidationError = InputValidationError;
@@ -44,6 +44,10 @@ const LEVEL_NAME = {
44
44
  * In tests, pass a capturing function to inspect output without side-effects.
45
45
  */
46
46
  class RequestScopedLogger {
47
+ traceId;
48
+ logLevel;
49
+ serviceName;
50
+ writeFn;
47
51
  constructor(traceId, logLevel, serviceName, writeFn = (line) => process.stdout.write(line + '\n')) {
48
52
  this.traceId = traceId;
49
53
  this.logLevel = logLevel;
@@ -0,0 +1,100 @@
1
+ /** A single data point collected from a metric. */
2
+ export interface MetricSample {
3
+ readonly name: string;
4
+ readonly labels: Record<string, string>;
5
+ readonly value: number;
6
+ /** Optional suffix such as `_bucket`, `_count`, `_sum`. */
7
+ readonly suffix: string;
8
+ }
9
+ /** Labeled counter child — holds a value for a specific label combination. */
10
+ export declare class LabeledCounter {
11
+ readonly labels: Readonly<Record<string, string>>;
12
+ private _value;
13
+ constructor(labels: Readonly<Record<string, string>>);
14
+ get value(): number;
15
+ /** Increments by `amount` (must be > 0). */
16
+ inc(amount?: number): void;
17
+ }
18
+ /** Monotonically increasing counter (Prometheus COUNTER type). */
19
+ export declare class Counter {
20
+ readonly name: string;
21
+ readonly help: string;
22
+ readonly type: "counter";
23
+ private _value;
24
+ private readonly _children;
25
+ constructor(opts: {
26
+ name: string;
27
+ help: string;
28
+ });
29
+ get value(): number;
30
+ /** Increments by `amount` (must be > 0). */
31
+ inc(amount?: number): void;
32
+ inc(labels: Record<string, string>, amount?: number): void;
33
+ /** Returns (or creates) a child counter for the given label values. */
34
+ labels(labelValues: Record<string, string>): LabeledCounter;
35
+ /** Collects samples from all labeled children. */
36
+ collect(): MetricSample[];
37
+ }
38
+ /** Labeled gauge child — holds a value for a specific label combination. */
39
+ export declare class LabeledGauge {
40
+ readonly labels: Readonly<Record<string, string>>;
41
+ private _value;
42
+ constructor(labels: Readonly<Record<string, string>>);
43
+ get value(): number;
44
+ set(v: number): void;
45
+ inc(amount?: number): void;
46
+ dec(amount?: number): void;
47
+ }
48
+ /** Value that can go up and down (Prometheus GAUGE type). */
49
+ export declare class Gauge {
50
+ readonly name: string;
51
+ readonly help: string;
52
+ readonly type: "gauge";
53
+ private _value;
54
+ private readonly _children;
55
+ constructor(opts: {
56
+ name: string;
57
+ help: string;
58
+ });
59
+ get value(): number;
60
+ set(v: number): void;
61
+ set(labels: Record<string, string>, v: number): void;
62
+ inc(amount?: number): void;
63
+ inc(labels: Record<string, string>, amount?: number): void;
64
+ dec(amount?: number): void;
65
+ dec(labels: Record<string, string>, amount?: number): void;
66
+ labels(labelValues: Record<string, string>): LabeledGauge;
67
+ collect(): MetricSample[];
68
+ }
69
+ /** Default Prometheus histogram buckets. */
70
+ export declare const DEFAULT_BUCKETS: readonly number[];
71
+ /** Labeled histogram child — holds buckets for a specific label combination. */
72
+ export declare class LabeledHistogram {
73
+ readonly labels: Readonly<Record<string, string>>;
74
+ private readonly _boundaries;
75
+ private readonly _cumulativeCounts;
76
+ private _sum;
77
+ private _count;
78
+ constructor(labels: Readonly<Record<string, string>>, boundaries: readonly number[]);
79
+ observe(value: number): void;
80
+ collect(metricName: string): MetricSample[];
81
+ }
82
+ /** Records observations in pre-defined buckets (Prometheus HISTOGRAM type). */
83
+ export declare class Histogram {
84
+ readonly name: string;
85
+ readonly help: string;
86
+ readonly buckets: readonly number[];
87
+ readonly type: "histogram";
88
+ private readonly _children;
89
+ constructor(opts: {
90
+ name: string;
91
+ help: string;
92
+ buckets?: number[];
93
+ });
94
+ /** Observe a value (must be >= 0). */
95
+ observe(value: number): void;
96
+ observe(labels: Record<string, string>, value: number): void;
97
+ labels(labelValues: Record<string, string>): LabeledHistogram;
98
+ /** Collects all samples across all label combinations. */
99
+ collect(): MetricSample[];
100
+ }
@@ -0,0 +1,284 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // core/metrics/metric.ts
4
+ // Prometheus-compatible metric types: Counter, Gauge, Histogram.
5
+ // Zero external dependencies — pure TypeScript implementation.
6
+ // Mirror of metric.dart and metric.py.
7
+ // ============================================================
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.Histogram = exports.LabeledHistogram = exports.DEFAULT_BUCKETS = exports.Gauge = exports.LabeledGauge = exports.Counter = exports.LabeledCounter = void 0;
10
+ // ── Shared helpers ───────────────────────────────────────────
11
+ /** Canonical key for a label set so we can reuse children. */
12
+ function labelKey(labels) {
13
+ return Object.keys(labels)
14
+ .sort()
15
+ .map((k) => `${k}=${labels[k]}`)
16
+ .join(',');
17
+ }
18
+ // ── Counter ──────────────────────────────────────────────────
19
+ /** Labeled counter child — holds a value for a specific label combination. */
20
+ class LabeledCounter {
21
+ labels;
22
+ _value = 0;
23
+ constructor(labels) {
24
+ this.labels = labels;
25
+ }
26
+ get value() {
27
+ return this._value;
28
+ }
29
+ /** Increments by `amount` (must be > 0). */
30
+ inc(amount = 1) {
31
+ if (amount <= 0) {
32
+ throw new Error(`Counter increment must be positive, got ${amount}`);
33
+ }
34
+ this._value += amount;
35
+ }
36
+ }
37
+ exports.LabeledCounter = LabeledCounter;
38
+ /** Monotonically increasing counter (Prometheus COUNTER type). */
39
+ class Counter {
40
+ name;
41
+ help;
42
+ type = 'counter';
43
+ _value = 0;
44
+ _children = new Map();
45
+ constructor(opts) {
46
+ this.name = opts.name;
47
+ this.help = opts.help;
48
+ }
49
+ get value() {
50
+ return this._value;
51
+ }
52
+ inc(labelsOrAmount, amount) {
53
+ if (labelsOrAmount === undefined || typeof labelsOrAmount === 'number') {
54
+ // inc() or inc(amount)
55
+ const a = labelsOrAmount ?? 1;
56
+ if (a <= 0)
57
+ throw new Error(`Counter increment must be positive, got ${a}`);
58
+ this._value += a;
59
+ }
60
+ else {
61
+ // inc(labels) or inc(labels, amount)
62
+ this.labels(labelsOrAmount).inc(amount ?? 1);
63
+ }
64
+ }
65
+ /** Returns (or creates) a child counter for the given label values. */
66
+ labels(labelValues) {
67
+ const key = labelKey(labelValues);
68
+ let child = this._children.get(key);
69
+ if (!child) {
70
+ child = new LabeledCounter(Object.freeze({ ...labelValues }));
71
+ this._children.set(key, child);
72
+ }
73
+ return child;
74
+ }
75
+ /** Collects samples from all labeled children. */
76
+ collect() {
77
+ return Array.from(this._children.values()).map((child) => ({
78
+ name: this.name,
79
+ labels: child.labels,
80
+ value: child.value,
81
+ suffix: '',
82
+ }));
83
+ }
84
+ }
85
+ exports.Counter = Counter;
86
+ // ── Gauge ────────────────────────────────────────────────────
87
+ /** Labeled gauge child — holds a value for a specific label combination. */
88
+ class LabeledGauge {
89
+ labels;
90
+ _value = 0;
91
+ constructor(labels) {
92
+ this.labels = labels;
93
+ }
94
+ get value() {
95
+ return this._value;
96
+ }
97
+ set(v) {
98
+ this._value = v;
99
+ }
100
+ inc(amount = 1) {
101
+ this._value += amount;
102
+ }
103
+ dec(amount = 1) {
104
+ this._value -= amount;
105
+ }
106
+ }
107
+ exports.LabeledGauge = LabeledGauge;
108
+ /** Value that can go up and down (Prometheus GAUGE type). */
109
+ class Gauge {
110
+ name;
111
+ help;
112
+ type = 'gauge';
113
+ _value = 0;
114
+ _children = new Map();
115
+ constructor(opts) {
116
+ this.name = opts.name;
117
+ this.help = opts.help;
118
+ }
119
+ get value() {
120
+ return this._value;
121
+ }
122
+ set(labelsOrValue, v) {
123
+ if (typeof labelsOrValue === 'number') {
124
+ this._value = labelsOrValue;
125
+ }
126
+ else {
127
+ this.labels(labelsOrValue).set(v);
128
+ }
129
+ }
130
+ inc(labelsOrAmount, amount) {
131
+ if (labelsOrAmount === undefined || typeof labelsOrAmount === 'number') {
132
+ this._value += labelsOrAmount ?? 1;
133
+ }
134
+ else {
135
+ this.labels(labelsOrAmount).inc(amount ?? 1);
136
+ }
137
+ }
138
+ dec(labelsOrAmount, amount) {
139
+ if (labelsOrAmount === undefined || typeof labelsOrAmount === 'number') {
140
+ this._value -= labelsOrAmount ?? 1;
141
+ }
142
+ else {
143
+ this.labels(labelsOrAmount).dec(amount ?? 1);
144
+ }
145
+ }
146
+ labels(labelValues) {
147
+ const key = labelKey(labelValues);
148
+ let child = this._children.get(key);
149
+ if (!child) {
150
+ child = new LabeledGauge(Object.freeze({ ...labelValues }));
151
+ this._children.set(key, child);
152
+ }
153
+ return child;
154
+ }
155
+ collect() {
156
+ return Array.from(this._children.values()).map((child) => ({
157
+ name: this.name,
158
+ labels: child.labels,
159
+ value: child.value,
160
+ suffix: '',
161
+ }));
162
+ }
163
+ }
164
+ exports.Gauge = Gauge;
165
+ // ── Histogram ────────────────────────────────────────────────
166
+ /** Default Prometheus histogram buckets. */
167
+ exports.DEFAULT_BUCKETS = [
168
+ 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
169
+ ];
170
+ /** Formats bucket boundary for Prometheus (no trailing zeros except ".0"). */
171
+ function formatBucket(v) {
172
+ if (Number.isInteger(v))
173
+ return v.toFixed(1);
174
+ return String(v);
175
+ }
176
+ function validateBuckets(b) {
177
+ if (b.length === 0)
178
+ throw new Error('buckets must not be empty');
179
+ for (let i = 1; i < b.length; i++) {
180
+ if (b[i] <= b[i - 1]) {
181
+ throw new Error('buckets must be sorted in increasing order');
182
+ }
183
+ }
184
+ }
185
+ /** Labeled histogram child — holds buckets for a specific label combination. */
186
+ class LabeledHistogram {
187
+ labels;
188
+ _boundaries;
189
+ _cumulativeCounts;
190
+ _sum = 0;
191
+ _count = 0;
192
+ constructor(labels, boundaries) {
193
+ this.labels = labels;
194
+ this._boundaries = boundaries;
195
+ this._cumulativeCounts = new Array(boundaries.length + 1).fill(0);
196
+ }
197
+ observe(value) {
198
+ if (value < 0)
199
+ throw new Error(`Histogram value must be non-negative, got ${value}`);
200
+ this._count++;
201
+ this._sum += value;
202
+ for (let i = 0; i < this._boundaries.length; i++) {
203
+ if (value <= this._boundaries[i]) {
204
+ this._cumulativeCounts[i]++;
205
+ }
206
+ }
207
+ // +Inf bucket always gets +1
208
+ this._cumulativeCounts[this._boundaries.length]++;
209
+ }
210
+ collect(metricName) {
211
+ const samples = [];
212
+ for (let i = 0; i < this._boundaries.length; i++) {
213
+ samples.push({
214
+ name: metricName,
215
+ labels: { ...this.labels, le: formatBucket(this._boundaries[i]) },
216
+ value: this._cumulativeCounts[i],
217
+ suffix: '_bucket',
218
+ });
219
+ }
220
+ // +Inf bucket
221
+ samples.push({
222
+ name: metricName,
223
+ labels: { ...this.labels, le: '+Inf' },
224
+ value: this._cumulativeCounts[this._boundaries.length],
225
+ suffix: '_bucket',
226
+ });
227
+ // _count
228
+ samples.push({
229
+ name: metricName,
230
+ labels: this.labels,
231
+ value: this._count,
232
+ suffix: '_count',
233
+ });
234
+ // _sum
235
+ samples.push({
236
+ name: metricName,
237
+ labels: this.labels,
238
+ value: this._sum,
239
+ suffix: '_sum',
240
+ });
241
+ return samples;
242
+ }
243
+ }
244
+ exports.LabeledHistogram = LabeledHistogram;
245
+ /** Records observations in pre-defined buckets (Prometheus HISTOGRAM type). */
246
+ class Histogram {
247
+ name;
248
+ help;
249
+ buckets;
250
+ type = 'histogram';
251
+ _children = new Map();
252
+ constructor(opts) {
253
+ this.name = opts.name;
254
+ this.help = opts.help;
255
+ this.buckets = opts.buckets ?? [...exports.DEFAULT_BUCKETS];
256
+ validateBuckets(this.buckets);
257
+ }
258
+ observe(labelsOrValue, value) {
259
+ if (typeof labelsOrValue === 'number') {
260
+ this.labels({}).observe(labelsOrValue);
261
+ }
262
+ else {
263
+ this.labels(labelsOrValue).observe(value);
264
+ }
265
+ }
266
+ labels(labelValues) {
267
+ const key = labelKey(labelValues);
268
+ let child = this._children.get(key);
269
+ if (!child) {
270
+ child = new LabeledHistogram(Object.freeze({ ...labelValues }), this.buckets);
271
+ this._children.set(key, child);
272
+ }
273
+ return child;
274
+ }
275
+ /** Collects all samples across all label combinations. */
276
+ collect() {
277
+ const samples = [];
278
+ for (const child of this._children.values()) {
279
+ samples.push(...child.collect(this.name));
280
+ }
281
+ return samples;
282
+ }
283
+ }
284
+ exports.Histogram = Histogram;
@@ -1,21 +1,35 @@
1
- import { Registry, Counter, Gauge, Histogram, type CounterConfiguration, type GaugeConfiguration, type HistogramConfiguration } from 'prom-client';
1
+ import { Counter, Gauge, Histogram } from './metric';
2
2
  /**
3
- * Internal registry wrapping prom-client's `Registry`.
3
+ * Internal registry that holds all metrics and serializes them.
4
4
  *
5
5
  * On construction, registers `process_start_time_seconds` as a gauge
6
6
  * set to the current epoch in seconds.
7
7
  */
8
8
  export declare class MetricRegistry {
9
- readonly registry: Registry;
10
- private readonly names;
9
+ private readonly _metrics;
10
+ private readonly _names;
11
11
  constructor();
12
- createCounter<T extends string = string>(config: Pick<CounterConfiguration<T>, 'name' | 'help' | 'labelNames'>): Counter<T>;
13
- createGauge<T extends string = string>(config: Pick<GaugeConfiguration<T>, 'name' | 'help' | 'labelNames'>): Gauge<T>;
14
- createHistogram<T extends string = string>(config: Pick<HistogramConfiguration<T>, 'name' | 'help' | 'labelNames' | 'buckets'>): Histogram<T>;
12
+ createCounter(config: {
13
+ name: string;
14
+ help: string;
15
+ labelNames?: readonly string[];
16
+ }): Counter;
17
+ createGauge(config: {
18
+ name: string;
19
+ help: string;
20
+ labelNames?: readonly string[];
21
+ }): Gauge;
22
+ createHistogram(config: {
23
+ name: string;
24
+ help: string;
25
+ labelNames?: readonly string[];
26
+ buckets?: number[];
27
+ }): Histogram;
15
28
  /** Serializes all metrics to Prometheus text exposition format. */
16
- serialize(): Promise<string>;
17
- /** Content type for the Prometheus text format. */
18
- get contentType(): string;
29
+ serialize(): string;
30
+ private serializeCounter;
31
+ private serializeGauge;
32
+ private serializeHistogram;
19
33
  private assertUnique;
20
34
  }
21
35
  /**
@@ -25,8 +39,21 @@ export declare class MetricRegistry {
25
39
  export declare class MetricsRegistrar {
26
40
  private readonly registry;
27
41
  constructor(registry: MetricRegistry);
28
- createCounter<T extends string = string>(config: Pick<CounterConfiguration<T>, 'name' | 'help' | 'labelNames'>): Counter<T>;
29
- createGauge<T extends string = string>(config: Pick<GaugeConfiguration<T>, 'name' | 'help' | 'labelNames'>): Gauge<T>;
30
- createHistogram<T extends string = string>(config: Pick<HistogramConfiguration<T>, 'name' | 'help' | 'labelNames' | 'buckets'>): Histogram<T>;
42
+ createCounter(config: {
43
+ name: string;
44
+ help: string;
45
+ labelNames?: readonly string[];
46
+ }): Counter;
47
+ createGauge(config: {
48
+ name: string;
49
+ help: string;
50
+ labelNames?: readonly string[];
51
+ }): Gauge;
52
+ createHistogram(config: {
53
+ name: string;
54
+ help: string;
55
+ labelNames?: readonly string[];
56
+ buckets?: number[];
57
+ }): Histogram;
31
58
  private validate;
32
59
  }