@oas-tools/oas-telemetry 0.6.2 → 0.7.0-alpha.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.
Files changed (131) hide show
  1. package/README.md +442 -442
  2. package/dist/{config.cjs → cjs/config.cjs} +6 -7
  3. package/dist/{exporters → cjs/exporters}/InMemoryDBMetricsExporter.cjs +5 -40
  4. package/dist/cjs/exporters/InMemoryDbExporter.cjs +87 -0
  5. package/dist/cjs/exporters/InMemoryLogRecordExporter.cjs +110 -0
  6. package/dist/{exporters → cjs/exporters}/consoleExporter.cjs +2 -7
  7. package/dist/{exporters → cjs/exporters}/dynamicExporter.cjs +12 -19
  8. package/dist/cjs/index.cjs +43 -0
  9. package/dist/cjs/instrumentation/index.cjs +28 -0
  10. package/dist/cjs/instrumentation/logs.cjs +46 -0
  11. package/dist/cjs/instrumentation/metrics.cjs +27 -0
  12. package/dist/cjs/instrumentation/traces.cjs +19 -0
  13. package/dist/{openTelemetry.cjs → cjs/openTelemetry.cjs} +6 -8
  14. package/dist/{systemMetrics.cjs → cjs/systemMetrics.cjs} +7 -7
  15. package/dist/cjs/tlm-ai/agent.cjs +79 -0
  16. package/dist/cjs/tlm-ai/aiController.cjs +69 -0
  17. package/dist/cjs/tlm-ai/aiRoutes.cjs +13 -0
  18. package/dist/cjs/tlm-ai/knownMicroservices.cjs +13 -0
  19. package/dist/cjs/tlm-ai/tools.cjs +504 -0
  20. package/dist/{routes/authRoutes.cjs → cjs/tlm-auth/authController.cjs} +21 -28
  21. package/dist/{middleware → cjs/tlm-auth}/authMiddleware.cjs +1 -1
  22. package/dist/cjs/tlm-auth/authRoutes.cjs +14 -0
  23. package/dist/cjs/tlm-log/logController.cjs +55 -0
  24. package/dist/cjs/tlm-log/logRoutes.cjs +13 -0
  25. package/dist/{routes → cjs/tlm-metric}/metricsRoutes.cjs +1 -2
  26. package/dist/{controllers → cjs/tlm-plugin}/pluginController.cjs +31 -41
  27. package/dist/cjs/tlm-plugin/pluginRoutes.cjs +13 -0
  28. package/dist/{controllers/telemetryController.cjs → cjs/tlm-trace/traceController.cjs} +8 -19
  29. package/dist/cjs/tlm-trace/traceRoutes.cjs +17 -0
  30. package/dist/cjs/tlm-ui/uiController.cjs +27 -0
  31. package/dist/cjs/tlm-ui/uiRoutes.cjs +31 -0
  32. package/dist/cjs/tlm-util/utilController.cjs +63 -0
  33. package/dist/cjs/tlm-util/utilRoutes.cjs +12 -0
  34. package/dist/cjs/tlmRoutes.cjs +79 -0
  35. package/dist/cjs/types/index.cjs +8 -0
  36. package/dist/cjs/utils/circular.cjs +90 -0
  37. package/dist/cjs/utils/logger.cjs +28 -0
  38. package/{src → dist/esm}/config.js +20 -23
  39. package/{src → dist/esm}/exporters/InMemoryDBMetricsExporter.js +57 -111
  40. package/dist/esm/exporters/InMemoryDbExporter.js +87 -0
  41. package/dist/esm/exporters/InMemoryLogRecordExporter.js +95 -0
  42. package/{src → dist/esm}/exporters/consoleExporter.js +38 -47
  43. package/{src → dist/esm}/exporters/dynamicExporter.js +50 -62
  44. package/dist/esm/index.js +39 -0
  45. package/dist/esm/instrumentation/index.js +26 -0
  46. package/dist/esm/instrumentation/logs.js +34 -0
  47. package/dist/esm/instrumentation/metrics.js +18 -0
  48. package/dist/esm/instrumentation/traces.js +12 -0
  49. package/{src → dist/esm}/openTelemetry.js +50 -58
  50. package/dist/esm/systemMetrics.js +82 -0
  51. package/dist/esm/tlm-ai/agent.js +68 -0
  52. package/dist/esm/tlm-ai/aiController.js +45 -0
  53. package/dist/esm/tlm-ai/aiRoutes.js +7 -0
  54. package/dist/esm/tlm-ai/knownMicroservices.js +5 -0
  55. package/dist/esm/tlm-ai/tools.js +490 -0
  56. package/dist/esm/tlm-auth/authController.js +41 -0
  57. package/{src/middleware → dist/esm/tlm-auth}/authMiddleware.js +12 -14
  58. package/dist/esm/tlm-auth/authRoutes.js +7 -0
  59. package/dist/esm/tlm-log/logController.js +36 -0
  60. package/dist/esm/tlm-log/logRoutes.js +7 -0
  61. package/{src/controllers → dist/esm/tlm-metric}/metricsController.js +28 -30
  62. package/{src/routes → dist/esm/tlm-metric}/metricsRoutes.js +8 -15
  63. package/{src/controllers → dist/esm/tlm-plugin}/pluginController.js +103 -115
  64. package/dist/esm/tlm-plugin/pluginRoutes.js +7 -0
  65. package/dist/esm/tlm-trace/traceController.js +54 -0
  66. package/dist/esm/tlm-trace/traceRoutes.js +11 -0
  67. package/dist/esm/tlm-ui/uiController.js +20 -0
  68. package/dist/esm/tlm-ui/uiRoutes.js +23 -0
  69. package/dist/esm/tlm-util/utilController.js +57 -0
  70. package/dist/esm/tlm-util/utilRoutes.js +6 -0
  71. package/dist/esm/tlmRoutes.js +72 -0
  72. package/dist/esm/types/index.js +4 -0
  73. package/dist/esm/utils/circular.js +84 -0
  74. package/dist/esm/utils/logger.js +19 -0
  75. package/dist/types/config.d.ts +6 -0
  76. package/dist/types/exporters/InMemoryDBMetricsExporter.d.ts +15 -0
  77. package/dist/types/exporters/InMemoryDbExporter.d.ts +24 -0
  78. package/dist/types/exporters/InMemoryLogRecordExporter.d.ts +27 -0
  79. package/dist/types/exporters/consoleExporter.d.ts +13 -0
  80. package/dist/types/exporters/dynamicExporter.d.ts +25 -0
  81. package/dist/types/index.d.ts +8 -0
  82. package/dist/types/instrumentation/index.d.ts +1 -0
  83. package/dist/types/instrumentation/logs.d.ts +1 -0
  84. package/dist/types/instrumentation/metrics.d.ts +1 -0
  85. package/dist/types/instrumentation/traces.d.ts +1 -0
  86. package/dist/types/openTelemetry.d.ts +1 -0
  87. package/dist/types/systemMetrics.d.ts +26 -0
  88. package/dist/types/tlm-ai/agent.d.ts +1 -0
  89. package/dist/types/tlm-ai/aiController.d.ts +4 -0
  90. package/dist/types/tlm-ai/aiRoutes.d.ts +2 -0
  91. package/dist/types/tlm-ai/knownMicroservices.d.ts +6 -0
  92. package/dist/types/tlm-ai/tools.d.ts +45 -0
  93. package/dist/types/tlm-auth/authController.d.ts +4 -0
  94. package/dist/types/tlm-auth/authMiddleware.d.ts +2 -0
  95. package/dist/types/tlm-auth/authRoutes.d.ts +2 -0
  96. package/dist/types/tlm-log/logController.d.ts +4 -0
  97. package/dist/types/tlm-log/logRoutes.d.ts +2 -0
  98. package/dist/types/tlm-metric/metricsController.d.ts +4 -0
  99. package/dist/types/tlm-metric/metricsRoutes.d.ts +2 -0
  100. package/dist/types/tlm-plugin/pluginController.d.ts +3 -0
  101. package/dist/types/tlm-plugin/pluginRoutes.d.ts +2 -0
  102. package/dist/types/tlm-trace/traceController.d.ts +7 -0
  103. package/dist/types/tlm-trace/traceRoutes.d.ts +2 -0
  104. package/dist/types/tlm-ui/uiController.d.ts +8 -0
  105. package/dist/types/tlm-ui/uiRoutes.d.ts +2 -0
  106. package/dist/types/tlm-util/utilController.d.ts +3 -0
  107. package/dist/types/tlm-util/utilRoutes.d.ts +2 -0
  108. package/dist/types/tlmRoutes.d.ts +2 -0
  109. package/dist/types/types/index.d.ts +56 -0
  110. package/dist/types/utils/circular.d.ts +31 -0
  111. package/dist/types/utils/logger.d.ts +9 -0
  112. package/dist/ui/assets/index-BNhZBPi2.css +1 -0
  113. package/dist/ui/assets/index-DxGAMrAl.js +401 -0
  114. package/dist/ui/index.html +14 -0
  115. package/dist/ui/vite.svg +1 -0
  116. package/package.json +80 -77
  117. package/dist/controllers/uiController.cjs +0 -78
  118. package/dist/exporters/InMemoryDbExporter.cjs +0 -178
  119. package/dist/index.cjs +0 -110
  120. package/dist/routes/telemetryRoutes.cjs +0 -31
  121. package/dist/services/uiService.cjs +0 -1520
  122. package/src/controllers/telemetryController.js +0 -69
  123. package/src/controllers/uiController.js +0 -69
  124. package/src/dev/ui/login.html +0 -32
  125. package/src/exporters/InMemoryDbExporter.js +0 -181
  126. package/src/index.js +0 -121
  127. package/src/routes/authRoutes.js +0 -53
  128. package/src/routes/telemetryRoutes.js +0 -38
  129. package/src/services/uiService.js +0 -1520
  130. package/src/systemMetrics.js +0 -102
  131. /package/dist/{controllers → cjs/tlm-metric}/metricsController.cjs +0 -0
@@ -1,69 +0,0 @@
1
- import v8 from 'v8';
2
- import { globalOasTlmConfig } from '../config.js';
3
-
4
-
5
- export const startTelemetry = (req, res) => {
6
- globalOasTlmConfig.dynamicExporter.exporter.start();
7
- res.send('Telemetry started');
8
- }
9
-
10
- export const stopTelemetry = (req, res) => {
11
- globalOasTlmConfig.dynamicExporter.exporter.stop();
12
- res.send('Telemetry stopped');
13
- }
14
-
15
- export const statusTelemetry = (req, res) => {
16
- const isRunning = globalOasTlmConfig.dynamicExporter.exporter.isRunning() || false;
17
- res.send({ active: isRunning });
18
- }
19
-
20
- export const resetTelemetry = (req, res) => {
21
- globalOasTlmConfig.dynamicExporter.exporter.reset();
22
- res.send('Telemetry reset');
23
- }
24
-
25
- export const listTelemetry = async (req, res) => {
26
- try {
27
- const spans = await globalOasTlmConfig.dynamicExporter.exporter.getFinishedSpans();
28
- res.send({ spansCount: spans.length, spans: spans });
29
- } catch (err) {
30
- console.error(err);
31
- res.status(500).send({ error: 'Failed to list telemetry data' });
32
- }
33
- }
34
-
35
- export const heapStats = (req, res) => {
36
- var heapStats = v8.getHeapStatistics();
37
- var roundedHeapStats = Object.getOwnPropertyNames(heapStats).reduce(function (map, stat) {
38
- map[stat] = Math.round((heapStats[stat] / 1024 / 1024) * 1000) / 1000;
39
- return map;
40
- }, {});
41
- roundedHeapStats['units'] = 'MB';
42
- res.send(roundedHeapStats);
43
- }
44
-
45
- export const findTelemetry = (req, res) => {
46
- const body = req.body;
47
- const search = body?.search ? body.search : {};
48
- if (body?.flags?.containsRegex) {
49
- try {
50
- body.config?.regexIds?.forEach(regexId => {
51
- if(search[regexId]) search[regexId] = new RegExp(search[regexId]);
52
- });
53
- } catch (e) {
54
- console.error(e);
55
- res.status(404).send({ spansCount: 0, spans: [], error: e });
56
- return;
57
- }
58
- }
59
- globalOasTlmConfig.dynamicExporter.exporter.find(search,(err, docs) => {
60
- if (err) {
61
- console.error(err);
62
- res.status(404).send({ spansCount: 0, spans: [], error: err });
63
- return;
64
- }
65
- const spans = docs;
66
- res.send({ spansCount: spans.length, spans: spans });
67
- });
68
-
69
- }
@@ -1,69 +0,0 @@
1
- import { globalOasTlmConfig } from '../config.js';
2
- import { readFileSync } from 'fs';
3
- import path from 'path';
4
- import yaml from 'js-yaml';
5
- import ui from '../services/uiService.js';
6
-
7
- export const apiPage = (req, res) => {
8
- const baseURL = globalOasTlmConfig.baseURL;
9
- let text = `
10
- <h1>Telemetry API routes:</h1>
11
- <ul>
12
- <li><a href="${baseURL}/start">${baseURL}/start</a></li>
13
- <li><a href="${baseURL}/stop">${baseURL}/stop</a></li>
14
- <li><a href="${baseURL}/status">${baseURL}/status</a></li>
15
- <li><a href="${baseURL}/reset">${baseURL}/reset</a></li>
16
- <li><a href="${baseURL}/list">${baseURL}/list</a></li>
17
- <li><a href="${baseURL}/heapStats">${baseURL}/heapStats</a></li>
18
- <li>${baseURL}/find [POST]</li>
19
- </ul>
20
- `;
21
- res.send(text);
22
- }
23
-
24
- export const mainPage = (req, res) => {
25
- const baseURL = globalOasTlmConfig.baseURL;
26
- res.set('Content-Type', 'text/html');
27
- res.send(ui(baseURL).main);
28
- }
29
-
30
- export const detailPage = (req, res) => {
31
- const baseURL = globalOasTlmConfig.baseURL;
32
- res.set('Content-Type', 'text/html');
33
- res.send(ui(baseURL).detail);
34
- }
35
-
36
- export const specLoader = (req, res) => {
37
- if (globalOasTlmConfig.specFileName) {
38
- try {
39
- const data = readFileSync(globalOasTlmConfig.specFileName, { encoding: 'utf8', flag: 'r' });
40
- const extension = path.extname(globalOasTlmConfig.specFileName);
41
- let json = data;
42
- if (extension == yaml)
43
- json = JSON.stringify(yaml.SafeLoad(data), null, 2);
44
- res.setHeader('Content-Type', 'application/json');
45
- res.send(json);
46
- } catch (e) {
47
- console.error(`ERROR loading spec file ${globalOasTlmConfig.specFileName}: ${e}`);
48
- }
49
- } else if (globalOasTlmConfig.spec) {
50
- let spec = false;
51
- try {
52
- spec = JSON.parse(globalOasTlmConfig.spec);
53
- } catch (ej) {
54
- try {
55
- spec = JSON.stringify(yaml.load(globalOasTlmConfig.spec), null, 2);
56
- } catch (ey) {
57
- console.error(`Error parsing spec: ${ej} - ${ey}`);
58
- }
59
- }
60
- if (!spec) {
61
- res.status(404);
62
- } else {
63
- res.setHeader('Content-Type', 'application/json');
64
- res.send(spec);
65
- }
66
- } else {
67
- res.status(404);
68
- }
69
- }
@@ -1,32 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Login</title>
7
- </head>
8
- <body>
9
- <form id="loginForm">
10
- <label for="apiKey">API Key:</label>
11
- <input type="text" id="apiKey" name="apiKey" required>
12
- <button type="submit">Login</button>
13
- </form>
14
-
15
- <script>
16
- document.getElementById('loginForm').addEventListener('submit', function(event) {
17
- event.preventDefault();
18
- const apiKey = document.getElementById('apiKey').value;
19
- fetch('/login', {
20
- method: 'POST',
21
- headers: {
22
- 'Content-Type': 'application/json'
23
- },
24
- body: JSON.stringify({ apiKey })
25
- })
26
- .then(response => response.text())
27
- .then(data => alert(data))
28
- .catch(error => console.error('Error:', error));
29
- });
30
- </script>
31
- </body>
32
- </html>
@@ -1,181 +0,0 @@
1
- import { ExportResultCode } from '@opentelemetry/core';
2
-
3
- let dbglog = () => { };
4
-
5
- if (process.env.OTDEBUG == "true")
6
- dbglog = console.log;
7
-
8
- //import in memory database
9
- import dataStore from '@seald-io/nedb';
10
-
11
- export class InMemoryExporter {
12
- constructor() {
13
- this._spans = new dataStore();
14
- this._stopped = true;
15
- };
16
-
17
- // Overrided by dynamic exporter
18
- plugins = [];
19
-
20
- export(readableSpans, resultCallback) {
21
- try {
22
- if (!this._stopped) {
23
- // Prepare spans to be inserted into the in-memory database (remove circular references and convert to nested objects)
24
- const cleanSpans = readableSpans
25
- .map(nestedSpan => removeCircularRefs(nestedSpan))// to avoid JSON parsing error
26
- .map(span => applyNesting(span))// to avoid dot notation in keys (neDB does not support dot notation in keys)
27
- .filter(span => !span.attributes?.http?.target?.includes("/telemetry"));// to avoid telemetry spans
28
- // Insert spans into the in-memory database
29
- this._spans.insert(cleanSpans, (err, newDoc) => {
30
- // p = {name, plugin
31
- this.plugins.forEach((pluginResource, i) => {
32
- cleanSpans.forEach((t) => {
33
- dbglog(`Sending trace <${t._id}> to plugin (Plugin #${i}) <${pluginResource.name}>`);
34
- dbglog(`Trace: \n<${JSON.stringify(t, null, 2)}`);
35
- //TODO: This should be called newSpan instead of newTrace
36
- pluginResource.plugin.newTrace(t);
37
- });
38
- });
39
- if (err) {
40
- console.error(err);
41
- return;
42
- }
43
- });
44
-
45
- }
46
- setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);
47
- } catch (error) {
48
- console.error('Error exporting spans\n' + error.message + '\n' + error.stack);
49
- return resultCallback({
50
- code: ExportResultCode.FAILED,
51
- error: new Error('Error exporting spans\n' + error.message + '\n' + error.stack),
52
- })
53
- }
54
- };
55
- start() {
56
- this._stopped = false;
57
- };
58
- stop() {
59
- this._stopped = true;
60
- };
61
-
62
- isRunning() {
63
- return !this._stopped;
64
- };
65
- shutdown() {
66
- this._stopped = true;
67
- this._spans = new dataStore();
68
- return this.forceFlush();
69
- };
70
- /**
71
- * Exports any pending spans in the exporter
72
- */
73
- forceFlush() {
74
- return Promise.resolve();
75
- };
76
- //err,docs
77
- find(search, callback) {
78
- this._spans.find(search, callback);
79
- }
80
- reset() {
81
- this._spans = new dataStore();
82
- };
83
- getFinishedSpans() {
84
- return this._spans.getAllData();
85
- };
86
-
87
- }
88
-
89
- function removeCircularRefs(obj) {
90
- const seen = new WeakMap(); // Used to keep track of visited objects
91
-
92
-
93
- // Replacer function to handle circular references
94
- function replacer(key, value) {
95
- if (key === "_spanProcessor") {
96
- return "oas-telemetry skips this field to avoid circular reference";
97
- }
98
- // GENERIC CIRCULAR REFERENCE HANDLING
99
- // if (typeof value === "object" && value !== null) {
100
- // // If the object has been visited before, return the name prefixed with "CIRCULAR+"
101
- // if (seen.has(value)) {
102
- // return `CIRCULAR${key}`;
103
- // }
104
- // seen.set(value, key); // Mark the object as visited with its name
105
- // }
106
- return value;
107
- }
108
-
109
- // Convert the object to a string and then parse it back
110
- // This will trigger the replacer function to handle circular references
111
- const jsonString = JSON.stringify(obj, replacer);
112
- return JSON.parse(jsonString);
113
- }
114
-
115
- /**
116
- * Recursively converts dot-separated keys in an object to nested objects.
117
- *
118
- * @param {Object} obj - The object to process.
119
- * @returns {Object} - The object with all dot-separated keys converted to nested objects.
120
- * @example
121
- * // Input:
122
- * // {
123
- * // "http.method": "GET",
124
- * // "http.url": "http://example.com",
125
- * // "nested.obj.key": "value"
126
- * // }
127
- * // Output:
128
- * // {
129
- * // "http": {
130
- * // "method": "GET",
131
- * // "url": "http://example.com"
132
- * // },
133
- * // "nested": {
134
- * // "obj": {
135
- * // "key": "value"
136
- * // }
137
- * // }
138
- * // }
139
- */
140
- function convertToNestedObject(obj) {
141
- const result = {};
142
-
143
- for (const key in obj) {
144
- const keys = key.split('.');
145
- let temp = result;
146
-
147
- for (let i = 0; i < keys.length; i++) {
148
- const currentKey = keys[i];
149
-
150
- if (i === keys.length - 1) {
151
- // Last key, set the value
152
- temp[currentKey] = obj[key];
153
- } else {
154
- // Intermediate key, ensure the object exists
155
- if (!temp[currentKey]) {
156
- temp[currentKey] = {};
157
- }
158
- temp = temp[currentKey];
159
- }
160
- }
161
- }
162
-
163
- return result;
164
- }
165
-
166
- /**
167
- * Applies nesting to all dot-separated keys within an object.
168
- *
169
- * @param {Object} obj - The object to apply nesting to.
170
- * @returns {Object} - The transformed object with nested structures.
171
- */
172
- function applyNesting(obj) {
173
- // Recursively apply convertToNestedObject to each level of the object
174
- for (const key in obj) {
175
- if (typeof obj[key] === 'object' && obj[key] !== null) {
176
- obj[key] = applyNesting(obj[key]);
177
- }
178
- }
179
-
180
- return convertToNestedObject(obj);
181
- }
package/src/index.js DELETED
@@ -1,121 +0,0 @@
1
- import './openTelemetry.js';
2
- import { globalOasTlmConfig } from './config.js';
3
- import cookieParser from 'cookie-parser';
4
- import { Router, json } from 'express';
5
- import { authMiddleware } from './middleware/authMiddleware.js';
6
- import authRoutes from './routes/authRoutes.js';
7
- import { telemetryRoutes } from './routes/telemetryRoutes.js';
8
- import { InMemoryExporter } from './exporters/InMemoryDbExporter.js';
9
- import metricsRoutes from './routes/metricsRoutes.js';
10
-
11
-
12
- let dbglog = () => { };
13
-
14
- if (process.env.OTDEBUG == "true")
15
- dbglog = console.log;
16
-
17
- /**
18
- * Returns the Oas Telemetry middleware. The parameters are the same as `globalOasTlmConfig`.
19
- * All parameters are optional. However, either `spec` or `specFileName` must be provided to enable endpoint filtering.
20
- *
21
- * @param {Object} OasTlmConfig Configuration object.
22
- * @param {string} [OasTlmConfig.baseURL="/telemetry"] The base URL for the telemetry routes.
23
- * @param {Object} [OasTlmConfig.spec] The OpenAPI spec object.
24
- * @param {string} [OasTlmConfig.specFileName] Alternative to `spec`: the path to the OpenAPI spec file.
25
- * @param {boolean} [OasTlmConfig.autoActivate=true] Whether to start telemetry automatically on load.
26
- * @param {boolean} [OasTlmConfig.authEnabled=true] Whether to enable authentication middleware.
27
- * @param {number} [OasTlmConfig.apiKeyMaxAge=1800000] The maximum age of the API key in milliseconds.
28
- * @param {string} [OasTlmConfig.defaultApiKey] The default API key to use.
29
- * @param {OasTlmExporter} [OasTlmConfig.exporter=InMemoryExporter] The exporter to use. Must implement the `OasTlmExporter` interface.
30
- * @returns {Router} The middleware router for Oas Telemetry.
31
- */
32
- export default function oasTelemetry(OasTlmConfig) {
33
- const router = Router();
34
- router.use((req, res, next) => {
35
- if (req.body !== undefined) {
36
- return next(); // Ya parseado, evitar json()
37
- }
38
-
39
- return json()(req, res, next);
40
- });
41
-
42
- if (process.env.OASTLM_MODULE_DISABLED === 'true') {
43
- return router;
44
- };
45
- if (OasTlmConfig) {
46
- console.log("User provided config");
47
- // Global = user-provided || default, for each key
48
- for (const key in globalOasTlmConfig) {
49
- globalOasTlmConfig[key] = OasTlmConfig[key] ?? globalOasTlmConfig[key];
50
- }
51
- }
52
- console.log("baseURL: ", globalOasTlmConfig.baseURL);
53
- globalOasTlmConfig.dynamicExporter.changeExporter(globalOasTlmConfig.exporter ?? new InMemoryExporter());
54
-
55
- if (globalOasTlmConfig.spec)
56
- dbglog(`Spec content provided`);
57
- else {
58
- if (globalOasTlmConfig.specFileName != "")
59
- dbglog(`Spec file used for telemetry: ${globalOasTlmConfig.specFileName}`);
60
- else {
61
- console.error("No spec available !");
62
- }
63
- }
64
- let allAuthMiddlewares = getWrappedMiddlewares(() => globalOasTlmConfig.authEnabled, [cookieParser(), authRoutes, authMiddleware]);
65
- const baseURL = globalOasTlmConfig.baseURL;
66
- router.use(baseURL, allAuthMiddlewares);
67
- router.use(baseURL, telemetryRoutes);
68
- router.use(baseURL + "/metrics", metricsRoutes);
69
-
70
- if (globalOasTlmConfig.autoActivate) {
71
- globalOasTlmConfig.dynamicExporter.exporter?.start();
72
- }
73
-
74
- return router;
75
- }
76
-
77
-
78
- /**
79
- * @typedef OasTlmExporter
80
- * Represents an exporter that processes and manages telemetry data.
81
- * Any custom exporter must implement these methods.
82
- *
83
- * @method {void} start() Starts the exporter, allowing it to process data.
84
- * @method {void} stop() Stops the exporter and halts data processing.
85
- * @method {void} reset() Resets the internal state of the exporter (e.g., clears buffers or data stores).
86
- * @method {boolean} isRunning() Returns whether the exporter is actively processing data.
87
- * @method {Array} getFinishedSpans() Retrieves the collected spans from the exporter.
88
- * @method {any} export(ReadableSpan, SpanExporterResultCallback) Exports spans.
89
- * @method {Promise<void>} shutdown() Gracefully shuts down the exporter, flushing data if necessary.
90
- * @method {Promise<void>} forceFlush() Exports any pending data that has not yet been processed.
91
- * @property {Array} plugins An array of plugins that can be activated by the exporter.
92
- */
93
-
94
- /**
95
- * This function wraps the provided middleware functions with a condition callback.
96
- * If the condition callback returns true, the middleware/router will be executed.
97
- * If the condition callback returns false, the middleware/router will be skipped.
98
- *
99
- * @callback {function} conditionCallback A callback function that returns a boolean to determine if the middleware should be used.
100
- * @param {Array} middlewares An array of middleware or routers to be wrapped.
101
- * @returns {Array} An array of wrapped middleware functions.
102
- */
103
- function getWrappedMiddlewares(conditionCallback, middlewares) {
104
- return middlewares.map(middleware => {
105
- return function (req, res, next) {
106
- if (conditionCallback()) {
107
- if (typeof middleware === 'function') {
108
- // look for handle property, if it exists, it's a router. If not call middleware
109
- if (middleware.handle) {
110
- middleware.handle(req, res, next);
111
- } else {
112
- middleware(req, res, next);
113
- }
114
- }
115
- } else {
116
- next();
117
- }
118
- };
119
- }
120
- );
121
- }
@@ -1,53 +0,0 @@
1
- import { globalOasTlmConfig } from '../config.js';
2
- import { Router } from 'express';
3
- import { serialize } from 'cookie';
4
- import ui from '../services/uiService.js';
5
- import jwt from 'jsonwebtoken';
6
-
7
- const router = Router();
8
-
9
- router.post('/login', (req, res) => {
10
- try {
11
- const { password } = req.body;
12
- if (password === globalOasTlmConfig.password) {
13
- let options = {
14
- maxAge: globalOasTlmConfig.apiKeyMaxAge,
15
- httpOnly: true, // The cookie only accessible by the web server
16
- secure: true, // Only sends cookie over https
17
- signed: false // Indicates if the cookie should be signed
18
- }
19
- const apiKey = jwt.sign({ password: globalOasTlmConfig.password }, globalOasTlmConfig.jwtSecret);
20
- res.cookie('apiKey', apiKey, options);
21
- return res.status(200).json({ valid: true, message: 'API Key is valid' });
22
- }
23
- res.status(400).json({ valid: false, message: 'Invalid API Key' });
24
-
25
- } catch (error) {
26
- console.log("Error: ", error);
27
- res.status(500).json({ valid: false, message: 'Internal server error' });
28
- }
29
- });
30
-
31
- router.get('/logout', (req, res) => {
32
- res.clearCookie('apiKey');
33
- res.redirect(globalOasTlmConfig.baseURL + '/login');
34
- });
35
-
36
- //check is used in the UI (http polling) to validate the Cookies to redirect to the login page if needed
37
- router.get('/check', (req, res) => {
38
- if (!req.cookies.apiKey) {
39
- return res.status(200).json({ valid: false, message: 'API Key is invalid' });
40
- }
41
- const decoded = jwt.verify(req.cookies.apiKey, globalOasTlmConfig.jwtSecret);
42
- if (decoded.password === globalOasTlmConfig.password) {
43
- return res.status(200).json({ valid: true, message: 'API Key is valid' });
44
- }
45
- res.status(200).json({ valid: false, message: 'Invalid API Key' });
46
- });
47
-
48
- router.get('/login', (req, res) => {
49
- const baseURL = globalOasTlmConfig.baseURL;
50
- res.send(ui(baseURL).login);
51
- });
52
-
53
- export default router;
@@ -1,38 +0,0 @@
1
- import { Router } from 'express';
2
- import { mainPage, detailPage , specLoader, apiPage} from '../controllers/uiController.js';
3
- import {
4
- startTelemetry,
5
- stopTelemetry,
6
- statusTelemetry,
7
- resetTelemetry,
8
- listTelemetry,
9
- heapStats,
10
- findTelemetry
11
- } from '../controllers/telemetryController.js';
12
- import { listPlugins, registerPlugin } from '../controllers/pluginController.js';
13
-
14
- export const telemetryRoutes = Router();
15
-
16
-
17
-
18
-
19
- // Main Pages
20
- telemetryRoutes.get('/', mainPage);
21
- telemetryRoutes.get('/detail/*', detailPage);
22
- telemetryRoutes.get('/spec', specLoader);
23
- telemetryRoutes.get('/api', apiPage);
24
-
25
- // Telemetry Control
26
- telemetryRoutes.get('/start', startTelemetry);
27
- telemetryRoutes.get('/stop', stopTelemetry);
28
- telemetryRoutes.get('/status', statusTelemetry);
29
- telemetryRoutes.get('/reset', resetTelemetry);
30
- telemetryRoutes.get('/list', listTelemetry);
31
- telemetryRoutes.post('/find', findTelemetry);
32
- telemetryRoutes.get('/heapStats', heapStats);
33
-
34
- // Plugins
35
- telemetryRoutes.get('/plugins', listPlugins);
36
- telemetryRoutes.post('/plugins', registerPlugin);
37
-
38
- export default telemetryRoutes;