@plyaz/types 1.23.0 → 1.23.2

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.
@@ -0,0 +1,548 @@
1
+ /**
2
+ * Monitoring/Observability Types
3
+ *
4
+ * Adapter-based observability system supporting multiple providers
5
+ * (Datadog, Grafana, OpenTelemetry, etc.) with parallel and priority modes.
6
+ *
7
+ * All types are prefixed with "Monitoring" for this dedicated module.
8
+ *
9
+ * @module observability/types
10
+ */
11
+ /**
12
+ * Supported observability providers
13
+ * Currently implemented: 'datadog', 'console', 'noop'
14
+ * Planned: 'grafana', 'opentelemetry', 'prometheus', 'newrelic', 'custom'
15
+ */
16
+ export type MonitoringObservabilityProvider = 'datadog' | 'console' | 'noop' | 'custom';
17
+ /**
18
+ * Metric types
19
+ */
20
+ export type MonitoringMetricType = 'counter' | 'gauge' | 'histogram' | 'summary';
21
+ /**
22
+ * Span status for tracing
23
+ */
24
+ export type MonitoringSpanStatus = 'ok' | 'error' | 'unset';
25
+ /**
26
+ * Log levels
27
+ */
28
+ export type MonitoringLogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
29
+ /**
30
+ * Base metric options
31
+ */
32
+ export interface MonitoringMetricOptions {
33
+ /** Metric name (e.g., 'http.request.duration') */
34
+ name: string;
35
+ /** Human-readable description */
36
+ description?: string;
37
+ /** Unit of measurement (e.g., 'ms', 'bytes', 'count') */
38
+ unit?: string;
39
+ /** Tags/labels for the metric */
40
+ tags?: Record<string, string | number | boolean>;
41
+ }
42
+ /**
43
+ * Counter metric (monotonically increasing)
44
+ */
45
+ export interface MonitoringCounterMetric extends MonitoringMetricOptions {
46
+ type: 'counter';
47
+ /** Value to increment by (default: 1) */
48
+ value?: number;
49
+ }
50
+ /**
51
+ * Gauge metric (can go up or down)
52
+ */
53
+ export interface MonitoringGaugeMetric extends MonitoringMetricOptions {
54
+ type: 'gauge';
55
+ /** Current value */
56
+ value: number;
57
+ }
58
+ /**
59
+ * Histogram metric (distribution of values)
60
+ */
61
+ export interface MonitoringHistogramMetric extends MonitoringMetricOptions {
62
+ type: 'histogram';
63
+ /** Value to record */
64
+ value: number;
65
+ /** Bucket boundaries (optional) */
66
+ buckets?: number[];
67
+ }
68
+ /**
69
+ * Summary metric (percentiles)
70
+ */
71
+ export interface MonitoringSummaryMetric extends MonitoringMetricOptions {
72
+ type: 'summary';
73
+ /** Value to record */
74
+ value: number;
75
+ /** Percentiles to track (e.g., [0.5, 0.9, 0.99]) */
76
+ percentiles?: number[];
77
+ }
78
+ /**
79
+ * Union of all metric types
80
+ */
81
+ export type MonitoringMetric = MonitoringCounterMetric | MonitoringGaugeMetric | MonitoringHistogramMetric | MonitoringSummaryMetric;
82
+ /**
83
+ * Span context for distributed tracing
84
+ */
85
+ export interface MonitoringSpanContext {
86
+ /** Unique trace ID */
87
+ traceId: string;
88
+ /** Unique span ID */
89
+ spanId: string;
90
+ /** Parent span ID (if any) */
91
+ parentSpanId?: string;
92
+ /** Sampling decision */
93
+ sampled?: boolean;
94
+ }
95
+ /**
96
+ * Span attributes following OpenTelemetry semantic conventions.
97
+ * Property names use dot notation as per OTel spec (e.g., 'service.name').
98
+ */
99
+ export interface MonitoringSpanAttributes {
100
+ /** Service name */
101
+ 'service.name'?: string;
102
+ /** Operation name */
103
+ 'operation.name'?: string;
104
+ /** HTTP method */
105
+ 'http.method'?: string;
106
+ /** HTTP URL */
107
+ 'http.url'?: string;
108
+ /** HTTP status code */
109
+ 'http.status_code'?: number;
110
+ /** Database system */
111
+ 'db.system'?: string;
112
+ /** Database statement */
113
+ 'db.statement'?: string;
114
+ /** Error flag */
115
+ error?: boolean;
116
+ /** Error message */
117
+ 'error.message'?: string;
118
+ /** Custom attributes */
119
+ [key: string]: string | number | boolean | undefined;
120
+ }
121
+ /**
122
+ * Span event (point-in-time occurrence within a span)
123
+ */
124
+ export interface MonitoringSpanEvent {
125
+ /** Event name */
126
+ name: string;
127
+ /** Event timestamp */
128
+ timestamp?: number;
129
+ /** Event attributes */
130
+ attributes?: Record<string, string | number | boolean>;
131
+ }
132
+ /**
133
+ * Options for creating a span
134
+ */
135
+ export interface MonitoringSpanOptions {
136
+ /** Span name (operation being traced) */
137
+ name: string;
138
+ /** Span kind */
139
+ kind?: 'internal' | 'server' | 'client' | 'producer' | 'consumer';
140
+ /** Initial attributes */
141
+ attributes?: MonitoringSpanAttributes;
142
+ /** Parent span context (for distributed tracing) */
143
+ parentContext?: MonitoringSpanContext;
144
+ /** Start time (default: now) */
145
+ startTime?: number;
146
+ }
147
+ /**
148
+ * Active span interface
149
+ */
150
+ export interface MonitoringSpan {
151
+ /** Span context */
152
+ context: MonitoringSpanContext;
153
+ /** Set attribute on span */
154
+ setAttribute(key: string, value: string | number | boolean): void;
155
+ /** Set multiple attributes */
156
+ setAttributes(attributes: MonitoringSpanAttributes): void;
157
+ /** Add event to span */
158
+ addEvent(event: MonitoringSpanEvent): void;
159
+ /** Set span status */
160
+ setStatus(status: MonitoringSpanStatus, message?: string): void;
161
+ /** End the span */
162
+ end(endTime?: number): void;
163
+ /** Record exception */
164
+ recordException(error: Error): void;
165
+ }
166
+ /**
167
+ * Structured log entry
168
+ */
169
+ export interface MonitoringLogEntry {
170
+ /** Log level */
171
+ level: MonitoringLogLevel;
172
+ /** Log message */
173
+ message: string;
174
+ /** Timestamp */
175
+ timestamp?: number;
176
+ /** Service/component name */
177
+ service?: string;
178
+ /** Additional context */
179
+ context?: Record<string, unknown>;
180
+ /** Associated trace ID */
181
+ traceId?: string;
182
+ /** Associated span ID */
183
+ spanId?: string;
184
+ /** Error object (if logging an error) */
185
+ error?: Error;
186
+ }
187
+ /**
188
+ * Custom event for observability
189
+ */
190
+ export interface MonitoringObservabilityEvent {
191
+ /** Event name */
192
+ name: string;
193
+ /** Event timestamp */
194
+ timestamp?: number;
195
+ /** Event properties */
196
+ properties?: Record<string, unknown>;
197
+ /** Associated tags */
198
+ tags?: Record<string, string>;
199
+ }
200
+ /**
201
+ * Base observability adapter interface.
202
+ *
203
+ * All observability providers (Datadog, Grafana, OpenTelemetry, etc.)
204
+ * must implement this interface.
205
+ *
206
+ * @example
207
+ * ```typescript
208
+ * class DatadogAdapter implements ObservabilityAdapter {
209
+ * readonly provider = 'datadog';
210
+ * readonly name = 'DatadogAdapter';
211
+ *
212
+ * async initialize(config: DatadogConfig): Promise<void> {
213
+ * // Initialize Datadog client
214
+ * }
215
+ *
216
+ * async recordMetric(metric: Metric): Promise<void> {
217
+ * // Send to Datadog
218
+ * }
219
+ *
220
+ * // ... other methods
221
+ * }
222
+ * ```
223
+ */
224
+ export interface MonitoringObservabilityAdapter {
225
+ /** Provider type */
226
+ readonly provider: MonitoringObservabilityProvider;
227
+ /** Adapter name for logging */
228
+ readonly name: string;
229
+ /** Whether the adapter is initialized */
230
+ readonly isInitialized: boolean;
231
+ /**
232
+ * Initialize the adapter with provider-specific config
233
+ */
234
+ initialize(config: MonitoringObservabilityAdapterConfig): Promise<void>;
235
+ /**
236
+ * Shutdown/cleanup the adapter
237
+ */
238
+ shutdown(): Promise<void>;
239
+ /**
240
+ * Check if adapter is healthy/connected
241
+ */
242
+ isHealthy(): Promise<boolean>;
243
+ /**
244
+ * Record a metric
245
+ */
246
+ recordMetric(metric: MonitoringMetric): Promise<void>;
247
+ /**
248
+ * Increment a counter
249
+ */
250
+ incrementCounter(name: string, value?: number, tags?: Record<string, string>): Promise<void>;
251
+ /**
252
+ * Set a gauge value
253
+ */
254
+ setGauge(name: string, value: number, tags?: Record<string, string>): Promise<void>;
255
+ /**
256
+ * Record a histogram value
257
+ */
258
+ recordHistogram(name: string, value: number, tags?: Record<string, string>): Promise<void>;
259
+ /**
260
+ * Start a new span
261
+ */
262
+ startSpan(options: MonitoringSpanOptions): MonitoringSpan;
263
+ /**
264
+ * Get current active span (if any)
265
+ */
266
+ getActiveSpan(): MonitoringSpan | null;
267
+ /**
268
+ * Run a function within a span
269
+ */
270
+ withSpan<T>(options: MonitoringSpanOptions, fn: (span: MonitoringSpan) => Promise<T>): Promise<T>;
271
+ /**
272
+ * Send a log entry
273
+ */
274
+ log(entry: MonitoringLogEntry): Promise<void>;
275
+ /**
276
+ * Send a custom event
277
+ */
278
+ sendEvent(event: MonitoringObservabilityEvent): Promise<void>;
279
+ /**
280
+ * Flush any buffered data
281
+ */
282
+ flush(): Promise<void>;
283
+ }
284
+ /**
285
+ * Base adapter configuration
286
+ */
287
+ export interface MonitoringObservabilityAdapterConfig {
288
+ /** Enable/disable the adapter */
289
+ enabled?: boolean;
290
+ /** Service name for tagging */
291
+ serviceName?: string;
292
+ /** Environment (production, staging, development) */
293
+ environment?: string;
294
+ /** Default tags to add to all metrics/spans */
295
+ defaultTags?: Record<string, string>;
296
+ /** Sampling rate for traces (0.0 to 1.0) */
297
+ samplingRate?: number;
298
+ /** Flush interval in milliseconds */
299
+ flushInterval?: number;
300
+ /** Buffer size before auto-flush */
301
+ bufferSize?: number;
302
+ }
303
+ /**
304
+ * Datadog-specific configuration
305
+ */
306
+ export interface MonitoringDatadogAdapterConfig extends MonitoringObservabilityAdapterConfig {
307
+ /** Datadog API key */
308
+ apiKey: string;
309
+ /** Datadog site (e.g., 'datadoghq.com', 'datadoghq.eu') */
310
+ site?: string;
311
+ /** Enable APM tracing */
312
+ apmEnabled?: boolean;
313
+ /** Enable RUM (Real User Monitoring) */
314
+ rumEnabled?: boolean;
315
+ /** RUM application ID */
316
+ rumApplicationId?: string;
317
+ /** RUM client token */
318
+ rumClientToken?: string;
319
+ }
320
+ /**
321
+ * OpenTelemetry-specific configuration
322
+ */
323
+ export interface MonitoringOpenTelemetryAdapterConfig extends MonitoringObservabilityAdapterConfig {
324
+ /** OTLP endpoint URL */
325
+ endpoint: string;
326
+ /** Headers for OTLP exporter */
327
+ headers?: Record<string, string>;
328
+ /** Export interval in milliseconds */
329
+ exportInterval?: number;
330
+ /** Resource attributes */
331
+ resourceAttributes?: Record<string, string>;
332
+ }
333
+ /**
334
+ * Grafana/Prometheus-specific configuration
335
+ */
336
+ export interface MonitoringGrafanaAdapterConfig extends MonitoringObservabilityAdapterConfig {
337
+ /** Push gateway URL (for Prometheus) */
338
+ pushGatewayUrl?: string;
339
+ /** Grafana Cloud user */
340
+ grafanaCloudUser?: string;
341
+ /** Grafana Cloud API key */
342
+ grafanaCloudApiKey?: string;
343
+ /** Loki endpoint for logs */
344
+ lokiEndpoint?: string;
345
+ /** Tempo endpoint for traces */
346
+ tempoEndpoint?: string;
347
+ }
348
+ /**
349
+ * Console adapter configuration (for development)
350
+ */
351
+ export interface MonitoringConsoleAdapterConfig extends MonitoringObservabilityAdapterConfig {
352
+ /** Pretty print output */
353
+ prettyPrint?: boolean;
354
+ /** Include timestamps */
355
+ includeTimestamps?: boolean;
356
+ /** Log level filter */
357
+ logLevel?: MonitoringLogLevel;
358
+ }
359
+ /**
360
+ * Mode for composite adapter
361
+ */
362
+ export type MonitoringCompositeMode = 'parallel' | 'priority';
363
+ /**
364
+ * Configuration for composite adapter
365
+ */
366
+ export interface MonitoringCompositeAdapterConfig extends MonitoringObservabilityAdapterConfig {
367
+ /** Execution mode */
368
+ mode: MonitoringCompositeMode;
369
+ /**
370
+ * Child adapters to use.
371
+ * For 'parallel': all adapters receive data simultaneously
372
+ * For 'priority': try first adapter, fallback to next on failure
373
+ */
374
+ adapters: MonitoringObservabilityAdapter[];
375
+ /**
376
+ * For 'priority' mode: continue to next adapter on these error types
377
+ * Default: all errors trigger fallback
378
+ */
379
+ fallbackOnErrors?: string[];
380
+ /**
381
+ * For 'parallel' mode: fail if any adapter fails (default: false)
382
+ * If false, logs errors but continues
383
+ */
384
+ failOnAnyError?: boolean;
385
+ /**
386
+ * Timeout for each adapter operation in ms (default: 5000)
387
+ */
388
+ adapterTimeout?: number;
389
+ }
390
+ /**
391
+ * Operation context for service hooks
392
+ */
393
+ export interface MonitoringOperationContext {
394
+ /** Service name */
395
+ serviceName: string;
396
+ /** Operation name (e.g., 'create', 'update', 'delete') */
397
+ operation: string;
398
+ /** Entity type (e.g., 'user', 'topic') */
399
+ entityType?: string;
400
+ /** Entity ID (if applicable) */
401
+ entityId?: string;
402
+ /** Start timestamp */
403
+ startTime: number;
404
+ /** Custom attributes */
405
+ attributes?: Record<string, unknown>;
406
+ /** Parent trace context */
407
+ parentContext?: MonitoringSpanContext;
408
+ }
409
+ /**
410
+ * Operation result for service hooks
411
+ */
412
+ export interface MonitoringOperationResult {
413
+ /** Whether operation succeeded */
414
+ success: boolean;
415
+ /** Duration in milliseconds */
416
+ duration: number;
417
+ /** Error (if failed) */
418
+ error?: Error;
419
+ /** Result data (optional) */
420
+ data?: unknown;
421
+ }
422
+ /**
423
+ * Adapter with priority and failover configuration.
424
+ * Higher priority = tried first in priority mode, executed first in parallel mode.
425
+ */
426
+ export interface MonitoringAdapterWithPriority {
427
+ /** The adapter instance (should be pre-initialized) */
428
+ adapter: MonitoringObservabilityAdapter;
429
+ /**
430
+ * Priority level (higher = more important)
431
+ * - In priority mode: higher priority adapters are tried first
432
+ * - In parallel mode: higher priority adapters are executed first
433
+ * Default: 0
434
+ */
435
+ priority?: number;
436
+ /**
437
+ * Mark this adapter as a failover/fallback adapter.
438
+ * - In parallel mode: failover adapters only receive data if primary adapters fail
439
+ * - In priority mode: failover adapters are only tried after all primary adapters fail
440
+ * Default: false
441
+ */
442
+ failover?: boolean;
443
+ }
444
+ /**
445
+ * Internal adapter entry with resolved metadata.
446
+ * Used by ObservabilityService to track adapter configuration.
447
+ */
448
+ export interface MonitoringAdapterEntry {
449
+ /** The adapter instance */
450
+ adapter: MonitoringObservabilityAdapter;
451
+ /** Resolved priority level */
452
+ priority: number;
453
+ /** Whether this is a failover adapter */
454
+ failover: boolean;
455
+ }
456
+ /**
457
+ * Configuration for ObservabilityService.
458
+ *
459
+ * Note: Adapter-specific configs (apiKey, endpoints, etc.) are NOT here.
460
+ * Each adapter is initialized separately with its own config before being passed here.
461
+ */
462
+ export interface MonitoringObservabilityServiceConfig {
463
+ /**
464
+ * Execution mode
465
+ * - 'single': Use only one adapter (default)
466
+ * - 'parallel': Send to all adapters simultaneously
467
+ * - 'priority': Try adapters in order, use first successful
468
+ */
469
+ mode?: 'single' | 'parallel' | 'priority';
470
+ /**
471
+ * Single adapter (for 'single' mode).
472
+ * Should be pre-initialized.
473
+ */
474
+ adapter?: MonitoringObservabilityAdapter | MonitoringAdapterWithPriority;
475
+ /**
476
+ * Multiple adapters (for 'parallel' or 'priority' mode).
477
+ * Can be plain adapters or adapters with priority config.
478
+ * Should be pre-initialized.
479
+ */
480
+ adapters?: (MonitoringObservabilityAdapter | MonitoringAdapterWithPriority)[];
481
+ /** Timeout for adapter operations in ms (default: 5000) */
482
+ adapterTimeout?: number;
483
+ /** For parallel mode: fail if any adapter fails (default: false) */
484
+ failOnAnyError?: boolean;
485
+ /** For priority mode: error types that trigger fallback (default: all) */
486
+ fallbackOnErrors?: string[];
487
+ }
488
+ /**
489
+ * Interface for ObservabilityService (for dependency injection typing)
490
+ */
491
+ export interface MonitoringObservabilityServiceInterface {
492
+ readonly isReady: boolean;
493
+ incrementCounter(name: string, value?: number, tags?: Record<string, string>): Promise<void>;
494
+ setGauge(name: string, value: number, tags?: Record<string, string>): Promise<void>;
495
+ recordHistogram(name: string, value: number, tags?: Record<string, string>): Promise<void>;
496
+ recordMetric(metric: MonitoringMetric): Promise<void>;
497
+ startSpan(options: MonitoringSpanOptions): MonitoringSpan;
498
+ withSpan<T>(options: MonitoringSpanOptions, fn: (span: MonitoringSpan) => Promise<T>): Promise<T>;
499
+ getActiveSpan(): MonitoringSpan | null;
500
+ log(entry: MonitoringLogEntry): Promise<void>;
501
+ sendEvent(event: MonitoringObservabilityEvent): Promise<void>;
502
+ trackOperation<T>(context: MonitoringOperationContext, operation: () => Promise<T>): Promise<{
503
+ result: T;
504
+ metrics: MonitoringOperationResult;
505
+ }>;
506
+ shutdown(): Promise<void>;
507
+ flush(): Promise<void>;
508
+ isHealthy(): Promise<boolean>;
509
+ }
510
+ /**
511
+ * Pre-defined metric names for consistency
512
+ */
513
+ export declare const OBSERVABILITY_METRICS: {
514
+ readonly SERVICE_OPERATION_DURATION: "service.operation.duration";
515
+ readonly SERVICE_OPERATION_COUNT: "service.operation.count";
516
+ readonly SERVICE_OPERATION_ERROR: "service.operation.error";
517
+ readonly DB_QUERY_DURATION: "db.query.duration";
518
+ readonly DB_QUERY_COUNT: "db.query.count";
519
+ readonly DB_CONNECTION_POOL_SIZE: "db.connection.pool.size";
520
+ readonly DB_CONNECTION_POOL_USED: "db.connection.pool.used";
521
+ readonly CACHE_HIT: "cache.hit";
522
+ readonly CACHE_MISS: "cache.miss";
523
+ readonly CACHE_SET: "cache.set";
524
+ readonly CACHE_DELETE: "cache.delete";
525
+ readonly API_REQUEST_DURATION: "api.request.duration";
526
+ readonly API_REQUEST_COUNT: "api.request.count";
527
+ readonly API_REQUEST_ERROR: "api.request.error";
528
+ readonly TRANSACTION_DURATION: "transaction.duration";
529
+ readonly TRANSACTION_COUNT: "transaction.count";
530
+ readonly TRANSACTION_ROLLBACK: "transaction.rollback";
531
+ };
532
+ /**
533
+ * Pre-defined span names for consistency
534
+ */
535
+ export declare const OBSERVABILITY_SPANS: {
536
+ readonly SERVICE_CREATE: "service.create";
537
+ readonly SERVICE_UPDATE: "service.update";
538
+ readonly SERVICE_DELETE: "service.delete";
539
+ readonly SERVICE_GET: "service.get";
540
+ readonly SERVICE_LIST: "service.list";
541
+ readonly SERVICE_BULK_CREATE: "service.bulk_create";
542
+ readonly SERVICE_BULK_DELETE: "service.bulk_delete";
543
+ readonly SERVICE_TRANSACTION: "service.transaction";
544
+ readonly DB_QUERY: "db.query";
545
+ readonly CACHE_GET: "cache.get";
546
+ readonly CACHE_SET: "cache.set";
547
+ readonly API_REQUEST: "api.request";
548
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plyaz/types",
3
- "version": "1.23.0",
3
+ "version": "1.23.2",
4
4
  "author": "Redeemer Pace",
5
5
  "license": "ISC",
6
6
  "description": "Provides shared TypeScript types and schema utilities for validation and parsing in the @playz ecosystem.",
@@ -20,6 +20,11 @@
20
20
  "import": "./dist/examples/index.js",
21
21
  "require": "./dist/examples/index.cjs"
22
22
  },
23
+ "./observability": {
24
+ "types": "./dist/observability/index.d.ts",
25
+ "import": "./dist/observability/index.js",
26
+ "require": "./dist/observability/index.cjs"
27
+ },
23
28
  "./api": {
24
29
  "types": "./dist/api/index.d.ts",
25
30
  "import": "./dist/api/index.js",