apm-optima 1.0.0 → 1.0.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.
package/README.md CHANGED
@@ -1,96 +1,37 @@
1
- <div align="center">
2
-
3
- <h1>Optima APM</h1>
1
+ # apm-optima
4
2
 
5
- <img src="docs/assets/optima-icon.svg" alt="Optima Icon" width="64" />
3
+ > Lightweight, real-time Application Performance Monitoring (APM) and telemetry library for Node.js web applications.
6
4
 
7
- <p><b>Lightweight, real-time Telemetry & Application Performance Monitoring for Node.js</b></p>
5
+ <div align="center">
8
6
 
9
- [![npm version](https://img.shields.io/npm/v/@optima/core.svg?style=flat-square&color=fc6c26)](https://www.npmjs.com/package/@optima/core)
7
+ [![npm version](https://img.shields.io/npm/v/apm-optima.svg?style=flat-square&color=fc6c26)](https://www.npmjs.com/package/apm-optima)
10
8
  [![license](https://img.shields.io/github/license/Nosalis1/Optima?style=flat-square&color=8A897C)](https://github.com/Nosalis1/Optima/blob/main/LICENSE)
11
- [![node version](https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen?style=flat-square)](https://nodejs.org)
12
- [![npm version](https://img.shields.io/badge/npm-%3E%3D10.0.0-red?style=flat-square)](https://www.npmjs.com/)
13
- [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
14
-
15
- <br/>
16
-
17
- <a href="#key-features">Key Features</a> •
18
- <a href="#architecture">Architecture</a> •
19
- <a href="#quick-start">Quick Start</a> •
20
- <a href="#configuration-options">Configuration</a> •
21
- <a href="#dashboard-preview">Dashboard</a>
9
+ [![github](https://img.shields.io/badge/github-repo-blue?logo=github)](https://github.com/Nosalis1/Optima.git)
22
10
 
23
11
  </div>
24
12
 
25
- ---
26
-
27
- ## Overview
28
-
29
- **Optima** is an in-memory Application Performance Monitoring (APM) library designed for modern Node.js web services. It intercepts HTTP requests, tracks Event Loop lag, computes latency percentiles in real time, and identifies performance anomalies—all while serving an embedded React Dashboard with zero external database dependencies.
30
-
31
- > Built for **Express.js** and **NestJS** applications with low runtime overhead.
32
-
33
- ---
34
-
35
- ## Key Features
36
-
37
- - **Real-time Latency Metrics:** On-the-fly computation of $P_{50}$, $P_{95}$, and $P_{99}$ percentiles.
38
- - **Z-Score Anomaly Detection:** Statistical detection of unexpected response time spikes.
39
- - **In-Memory Storage:** Efficient metric aggregation using typed array (`Uint32Array`) histogram buckets and circular ring buffers.
40
- - **Embedded React Dashboard:** Zero-config static dashboard served directly through your primary Node.js HTTP server.
41
- - **Framework Agnostic Core:** Native support for both **Express** (middleware) and **NestJS** (interceptors/modules).
42
- - **Live Updates:** Low-latency WebSocket layer pushing live metrics straight to the UI.
43
-
44
- ---
45
-
46
- ## Dashboard Preview
13
+ ## Features
47
14
 
48
- <!-- ZAMENI SA STVARNOM SLIKOM KADA JE DODATNA U REPOZITORIJUM -->
49
- <div align="center">
50
- <table border="0">
51
- <tr>
52
- <td width="33.3%"><img src="docs/assets/dashboard-1.png" alt="Optima Dashboard Preview 1" /></td>
53
- <td width="33.3%"><img src="docs/assets/dashboard-2.png" alt="Optima Dashboard Preview 2" /></td>
54
- <td width="33.3%"><img src="docs/assets/dashboard-3.png" alt="Optima Dashboard Preview 3" /></td>
55
- </tr>
56
- </table>
57
- <td width="33.3%"><img src="docs/assets/dashboard-1-dark.png" alt="Optima Dashboard Preview 3" /></td>
58
- <p><i>Real-time monitoring interface served directly via <code>/optima-metrics</code>.</i></p>
59
- </div>
15
+ - **Real-Time Telemetry:** HTTP request latency, status codes, and throughput.
16
+ - **Node.js Diagnostics:** Event Loop lag monitoring, process memory distribution, and active handles.
17
+ - **Embedded Dashboard UI:** Instant built-in dashboard available directly at your metrics route.
18
+ - **Console Logger:** Pretty-printed HTTP request duration and status output.
60
19
 
61
20
  ---
62
21
 
63
- ## Architecture
22
+ ## Installation
64
23
 
65
- Optima is structured as a **Monorepo** managed with `npm workspaces`:
66
-
67
- ```
68
- ├── packages/
69
- │ └── core/ # Telemetry engine, interceptors, and WebSocket adapters (@optima-apm/core)
70
- │ └── dashboard/ # Next.js React Dashboard (exported statically into @optima-apm/core)
71
- ├── apps/ # Integration & demo application (Express & NestJS)
24
+ ```bash
25
+ npm install apm-optima
72
26
  ```
73
27
 
74
28
  ---
75
29
 
76
- ## Quick Start
77
-
78
- ### Installation
79
-
80
- ```bash
81
- npm install @optima-apm/core
82
- # or
83
- pnpm add @optima-apm/core
84
- # or
85
- yarn add @optima-apm/core
86
- ```
87
-
88
- ### Express.js Integration
30
+ ## Quick Start (Express)
89
31
 
90
- Attach Optima using setupOptima and hook the HTTP server instance:
91
- ```ts
32
+ ```typescript
92
33
  const express = require('express');
93
- const { setupOptima } = require('@optima-apm/core/express');
34
+ const { setupOptima } = require('apm-optima/express');
94
35
 
95
36
  const app = express();
96
37
  app.use(express.json());
@@ -116,12 +57,13 @@ const server = app.listen(3000, () => {
116
57
  const stopMetrics = optima.attachServer(server);
117
58
  ```
118
59
 
119
- ### NestJS Integration
60
+ ---
61
+
62
+ ## Quick Start (NestJS)
120
63
 
121
- Import MetricsModule into your root application module:
122
64
  ```ts
123
65
  import { Module } from '@nestjs/common';
124
- import { MetricsModule } from '@optima-apm/core/nest';
66
+ import { MetricsModule } from 'apm-optima/nest';
125
67
 
126
68
  @Module({
127
69
  imports: [
@@ -138,10 +80,10 @@ import { MetricsModule } from '@optima-apm/core/nest';
138
80
  export class AppModule {}
139
81
  ```
140
82
 
141
- ### Configuration Options
83
+ ## Configuration Options
142
84
 
143
85
  | Option | Type | Default | Description |
144
- | --- | --- | --- | --- |
86
+ | :--- | :--- | :--- | :--- |
145
87
  | `dashboardPath` | `string \| false` | `/optima-metrics` | Route endpoint for serving the embedded UI (`false` to disable). |
146
88
  | `simulation` | `false \| { intervalMs: number, requestsPerTick: number }` | `false` | Generates synthetic traffic for local testing and load simulation. |
147
89
  | `publisher.intervalMs` | `number` | `1000` | Broadcast interval (in ms) for pushing telemetry updates over WebSockets. |
@@ -154,13 +96,6 @@ export class AppModule {}
154
96
  | `ringBufferSize` | `number` | `60` | Capacity of the internal ring buffer used for storing time-series data. |
155
97
  | `alertBufferSize` | `number` | `100` | Maximum capacity of the buffer holding recent alerts and detected anomalies. |
156
98
 
157
- ## Contributing
158
-
159
- Contributions, issues, and feature requests are welcome!
160
- Feel free to check out the [issues page](https://github.com/Nosalis1/Optima/issues).
161
-
162
- Please read our [Contributing Guidelines](CONTRIBUTING.md) before submitting a Pull Request or opening an issue.
163
-
164
99
  ## License
165
100
 
166
- Distributed under the MIT License. See [`LICENSE`](LICENSE) for more information.
101
+ [MIT](LICENSE)
@@ -25,7 +25,6 @@ class ConfigManager {
25
25
  '*.css',
26
26
  '/favicon.ico',
27
27
  '/metrics_pack',
28
- '/',
29
28
  '/health',
30
29
  '/optima-metrics/**',
31
30
  '/optima-metrics/*',
@@ -5,7 +5,7 @@ declare class Logger {
5
5
  private static readonly DIM;
6
6
  private static readonly COLORS;
7
7
  static log(req: Request, res: Response, duration: number): void;
8
- static debug(message: string): void;
8
+ static debug(message: string, ...args: unknown[]): void;
9
9
  static duration(message: string, duration: number): void;
10
10
  }
11
11
  export default Logger;
@@ -41,9 +41,9 @@ class Logger {
41
41
  `• ${statusCode} • ` +
42
42
  `${timing}`);
43
43
  }
44
- static debug(message) {
44
+ static debug(message, ...args) {
45
45
  const timestamp = new Date().toISOString().split('T')[1].slice(0, -1);
46
- console.log(`${Logger.DIM}[${timestamp}]${Logger.RESET} ${Logger.DIM}${message}${Logger.RESET}`);
46
+ console.log(`${Logger.DIM}[${timestamp}]${Logger.RESET} [Optima] ${Logger.DIM}${message}${Logger.RESET}`, ...args);
47
47
  }
48
48
  static duration(message, duration) {
49
49
  return; // Disable duration logging for now
@@ -1,21 +1,32 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.setupOptima = setupOptima;
4
7
  const config_1 = require("../config");
5
8
  const metrics_middleware_1 = require("./metrics.middleware");
6
9
  const metrics_dashboard_1 = require("./metrics.dashboard");
7
10
  const metrics_bootstrap_1 = require("./metrics.bootstrap");
11
+ const logger_1 = __importDefault(require("../core/telemetry/logger"));
8
12
  function setupOptima(app, options) {
13
+ logger_1.default.debug('Initializing Optima with provided configuration options...');
9
14
  config_1.ConfigManager.getInstance().initialize(options);
10
15
  const config = config_1.ConfigManager.getInstance().get();
11
16
  // Registering the metrics middleware
12
17
  app.use(metrics_middleware_1.expressMetricsMiddleware);
18
+ logger_1.default.debug('Middlware for metrics collection has been registered successfully.');
13
19
  // Attaching the dashboard on provided path
14
20
  if (config.dashboardPath !== false) {
15
21
  (0, metrics_dashboard_1.attachDashboard)(app, config.dashboardPath);
22
+ logger_1.default.debug(`Dashboard has been attached at path: ${config.dashboardPath}`);
23
+ }
24
+ else {
25
+ logger_1.default.debug('Dashboard attachment skipped as per configuration.');
16
26
  }
17
27
  return {
18
28
  attachServer: (server) => {
29
+ logger_1.default.debug('Attaching server for metrics collection...');
19
30
  return (0, metrics_bootstrap_1.expressMetricsBootstrap)(server);
20
31
  }
21
32
  };
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.ExpressWebSocketAdapter = void 0;
4
7
  const socket_io_1 = require("socket.io");
5
8
  const delivery_1 = require("../core/delivery");
6
9
  const config_1 = require("../config");
10
+ const logger_1 = __importDefault(require("../core/telemetry/logger"));
7
11
  class ExpressWebSocketAdapter {
8
12
  server;
9
13
  provider;
@@ -14,7 +18,7 @@ class ExpressWebSocketAdapter {
14
18
  }
15
19
  init() {
16
20
  if (this.io) {
17
- console.warn('[Optima] WebSocket server is already initialized.');
21
+ logger_1.default.debug('WebSocket server is already initialized.');
18
22
  return;
19
23
  }
20
24
  this.io = new socket_io_1.Server(this.server, {
@@ -27,15 +31,15 @@ class ExpressWebSocketAdapter {
27
31
  methods: ['GET', 'POST'],
28
32
  },
29
33
  });
30
- console.log('[Optima] WebSocket server initialized successfully.');
34
+ logger_1.default.debug('WebSocket server initialized successfully.');
31
35
  this.setupEvents();
32
36
  }
33
37
  setupEvents() {
34
38
  if (!this.io)
35
39
  return;
36
- console.log('[Optima] Setting up WebSocket event bindings.');
40
+ logger_1.default.debug('Setting up WebSocket event bindings.');
37
41
  this.io.on('connection', socket => {
38
- console.log(`[Optima] New WebSocket connection: ${socket.id}`);
42
+ logger_1.default.debug(`New WebSocket connection: ${socket.id}`);
39
43
  this.setupClient(socket);
40
44
  });
41
45
  }
@@ -56,7 +60,7 @@ class ExpressWebSocketAdapter {
56
60
  socket.emit(delivery_1.WebSocketEvents.RESPONSE_HEALTH_DATA, this.provider.getHealthData());
57
61
  });
58
62
  socket.on('disconnect', () => {
59
- console.log(`[Optima] WebSocket disconnected: ${socket.id}`);
63
+ logger_1.default.debug(`WebSocket disconnected: ${socket.id}`);
60
64
  });
61
65
  }
62
66
  broadcast(event, data) {
@@ -1,4 +1,7 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.expressMetricsBootstrap = expressMetricsBootstrap;
4
7
  const metrics_websocket_adapter_1 = require("./metrics-websocket.adapter");
@@ -7,6 +10,7 @@ const simulation_1 = require("../simulation/simulation");
7
10
  const delivery_1 = require("../core/delivery");
8
11
  const correlation_service_1 = require("../core/telemetry/correlation.service");
9
12
  const config_1 = require("../config");
13
+ const logger_1 = __importDefault(require("../core/telemetry/logger"));
10
14
  function expressMetricsBootstrap(server) {
11
15
  const config = (0, config_1.getConfig)();
12
16
  let simulator = null;
@@ -25,7 +29,7 @@ function expressMetricsBootstrap(server) {
25
29
  collector_service_1.collectorService.tick();
26
30
  correlation_service_1.correlationService.tick();
27
31
  }, config.tickIntervalMs);
28
- console.log('[Optima] Uspešno inicijalizovani svi podsistemi monitoringa.');
32
+ logger_1.default.debug('Metrics bootstrap initialized successfully.');
29
33
  return () => {
30
34
  simulator?.stop();
31
35
  publisher.stop();
@@ -11,19 +11,23 @@ var __metadata = (this && this.__metadata) || function (k, v) {
11
11
  var __param = (this && this.__param) || function (paramIndex, decorator) {
12
12
  return function (target, key) { decorator(target, key, paramIndex); }
13
13
  };
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
14
17
  Object.defineProperty(exports, "__esModule", { value: true });
15
18
  exports.NestWebSocketAdapter = void 0;
16
19
  const websockets_1 = require("@nestjs/websockets");
17
20
  const delivery_1 = require("../core/delivery");
18
21
  const collector_service_1 = require("../core/telemetry/collector.service");
22
+ const logger_1 = __importDefault(require("../core/telemetry/logger"));
19
23
  let NestWebSocketAdapter = class NestWebSocketAdapter {
20
24
  server;
21
25
  init() { }
22
26
  handleConnection(socket) {
23
- console.log('[Optima] Dashboard klijent se povezao.', socket.id);
27
+ logger_1.default.debug('Dashboard client connected.', socket.id);
24
28
  }
25
29
  handleDisconnect(socket) {
26
- console.log('[Optima] Dashboard klijent se odjavio.', socket.id);
30
+ logger_1.default.debug('Dashboard client disconnected.', socket.id);
27
31
  }
28
32
  handleSystemData(socket) {
29
33
  socket.emit(delivery_1.WebSocketEvents.RESPONSE_SYSTEM_DATA, collector_service_1.collectorService.getSystemStaticInfo());
@@ -11,6 +11,9 @@ var __metadata = (this && this.__metadata) || function (k, v) {
11
11
  var __param = (this && this.__param) || function (paramIndex, decorator) {
12
12
  return function (target, key) { decorator(target, key, paramIndex); }
13
13
  };
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
14
17
  Object.defineProperty(exports, "__esModule", { value: true });
15
18
  exports.MetricsBootstrapService = void 0;
16
19
  const common_1 = require("@nestjs/common");
@@ -19,6 +22,7 @@ const correlation_service_1 = require("../core/telemetry/correlation.service");
19
22
  const delivery_1 = require("../core/delivery");
20
23
  const simulation_1 = require("../simulation/simulation");
21
24
  const metrics_websocket_adapter_1 = require("./metrics-websocket.adapter");
25
+ const logger_1 = __importDefault(require("../core/telemetry/logger"));
22
26
  let MetricsBootstrapService = class MetricsBootstrapService {
23
27
  websocket;
24
28
  config;
@@ -44,7 +48,7 @@ let MetricsBootstrapService = class MetricsBootstrapService {
44
48
  collector_service_1.collectorService.tick();
45
49
  correlation_service_1.correlationService.tick();
46
50
  }, this.config.tickIntervalMs);
47
- console.log('[Optima] Nest metrics bootstrap initialized.');
51
+ logger_1.default.debug('Nest metrics bootstrap initialized.');
48
52
  }
49
53
  onApplicationShutdown() {
50
54
  this.simulator?.stop();
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.ScenarioController = exports.scenario = void 0;
4
7
  exports.updateScenarios = updateScenarios;
8
+ const logger_1 = __importDefault(require("../core/telemetry/logger"));
5
9
  const utility_1 = require("./utility");
6
10
  exports.scenario = {
7
11
  trafficMultiplier: 1,
@@ -16,7 +20,7 @@ function updateScenarios() {
16
20
  if (now > exports.scenario.latencySpikeUntil && (0, utility_1.probability)(0.002)) {
17
21
  exports.scenario.trafficMultiplier = 3;
18
22
  exports.scenario.latencySpikeUntil = now + 10000;
19
- console.log("📈 Traffic spike started");
23
+ logger_1.default.debug("Traffic spike started");
20
24
  }
21
25
  if (now > exports.scenario.latencySpikeUntil) {
22
26
  exports.scenario.trafficMultiplier = 1;
@@ -24,17 +28,17 @@ function updateScenarios() {
24
28
  // database slowdown
25
29
  if (now > exports.scenario.databaseSlowUntil && (0, utility_1.probability)(0.001)) {
26
30
  exports.scenario.databaseSlowUntil = now + 12000;
27
- console.log("🐢 Database slowdown");
31
+ logger_1.default.debug("Database slowdown");
28
32
  }
29
33
  // auth outage
30
34
  if (now > exports.scenario.authDownUntil && (0, utility_1.probability)(0.0005)) {
31
35
  exports.scenario.authDownUntil = now + 8000;
32
- console.log("🔐 Auth outage");
36
+ logger_1.default.debug("Auth outage");
33
37
  }
34
38
  // memory leak
35
39
  if (!exports.scenario.memoryLeak && (0, utility_1.probability)(0.0002)) {
36
40
  exports.scenario.memoryLeak = true;
37
- console.log("🧠 Memory leak started");
41
+ logger_1.default.debug("Memory leak started");
38
42
  }
39
43
  }
40
44
  class ScenarioController {
@@ -48,19 +52,19 @@ class ScenarioController {
48
52
  case "TRAFFIC_SPIKE":
49
53
  this.state.trafficMultiplier = 4;
50
54
  this.state.latencySpikeUntil = now + 30000;
51
- console.log("Manual traffic spike!");
55
+ logger_1.default.debug("Manual traffic spike!");
52
56
  break;
53
57
  case "DATABASE_SLOWDOWN":
54
58
  this.state.databaseSlowUntil = now + 60000;
55
- console.log("Manual database slowdown!");
59
+ logger_1.default.debug("Manual database slowdown!");
56
60
  break;
57
61
  case "AUTH_OUTAGE":
58
62
  this.state.authDownUntil = now + 30000;
59
- console.log("Manual auth outage!");
63
+ logger_1.default.debug("Manual auth outage!");
60
64
  break;
61
65
  case "MEMORY_LEAK":
62
66
  this.state.memoryLeak = true;
63
- console.log("Manual memory leak!");
67
+ logger_1.default.debug("Manual memory leak!");
64
68
  break;
65
69
  case "RESET":
66
70
  this.reset();
@@ -90,7 +94,7 @@ class ScenarioController {
90
94
  this.state.authDownUntil = 0;
91
95
  this.state.latencySpikeUntil = 0;
92
96
  this.state.memoryLeak = false;
93
- console.log("Scenarios reset!");
97
+ logger_1.default.debug("Scenarios reset!");
94
98
  }
95
99
  }
96
100
  exports.ScenarioController = ScenarioController;
@@ -1,4 +1,7 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.TrafficSimulator = void 0;
4
7
  const local_repository_1 = require("../core/storage/local.repository");
@@ -6,6 +9,7 @@ const config_1 = require("./config");
6
9
  const scenarios_1 = require("./scenarios");
7
10
  const journey_1 = require("./journey");
8
11
  const utility_1 = require("./utility");
12
+ const logger_1 = __importDefault(require("../core/telemetry/logger"));
9
13
  function generateLatency(endpoint) {
10
14
  const r = Math.random();
11
15
  // 90% normal traffic
@@ -122,7 +126,7 @@ class TrafficSimulator {
122
126
  this.running = true;
123
127
  const interval = options?.intervalMs ?? 100;
124
128
  const baseRequests = options?.requestsPerTick ?? 20;
125
- console.log("Traffic simulation started!");
129
+ logger_1.default.debug("Traffic simulation started!");
126
130
  this.timer = setInterval(() => {
127
131
  if (IS_STABLE) {
128
132
  const request = createStableRequest();
@@ -145,7 +149,7 @@ class TrafficSimulator {
145
149
  clearInterval(this.timer);
146
150
  this.timer = undefined;
147
151
  this.running = false;
148
- console.log("Traffic simulation stopped!");
152
+ logger_1.default.debug("Traffic simulation stopped!");
149
153
  }
150
154
  isRunning() {
151
155
  return this.running;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apm-optima",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "publishConfig": {
@@ -34,6 +34,7 @@
34
34
  "files": [
35
35
  "dist",
36
36
  "README.md",
37
+ "LICENSE",
37
38
  "package.json"
38
39
  ],
39
40
  "scripts": {
@@ -68,4 +69,4 @@
68
69
  "ts-jest": "^29.0.0",
69
70
  "typescript": "^5.0.0"
70
71
  }
71
- }
72
+ }