@oas-tools/oas-telemetry 0.2.2 → 0.3.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/README.md CHANGED
@@ -1,133 +1,133 @@
1
- # OAS TELEMETRY
2
-
3
- OAS Telemetry offers an express middleware designed for collecting telemetry data using Open Telemetry in applications built using the OpenAPI Specification (OAS). This middleware allows developers to easily incorporate telemetry functionality into their APIs.
4
-
5
- OAS Telemetry provides a set of endpoints that can be accessed to perform various actions related to telemetry data, such as starting and stopping data collection, resetting telemetry data, listing collected data, and searching for specific telemetry records. These endpoints can be easily integrated into an Express.js application, providing developers with a convenient way to manage and analyze telemetry data.
6
-
7
- Additionally, OAS Telemetry offers customization options, allowing developers to configure the telemetry middleware according to their specific requirements.
8
-
9
- Overall, OAS Telemetry will serve as a valuable tool for developers looking to gain insights into the operation and performance of their OAS-based APIs, enabling them to monitor, debug, and optimize their applications effectively.
10
-
11
-
12
-
13
-
14
-
15
- ## Usage
16
- To use the middelware add this two lines in your index.js (ESM):
17
- ```js
18
- import oasTelemetry from 'oas-telemetry';
19
- import {readFileSync} from 'fs';
20
-
21
- app.use(oasTelemetry({
22
- spec : readFileSync('./spec/oas.yaml',{ encoding: 'utf8', flag: 'r' })
23
- }))
24
-
25
- ```
26
-
27
- ## Custom Configuration
28
-
29
- You can also customize the telemetry configuration by passing options to the middleware function. For example:
30
- ```js
31
- const customTelemetryConfig = {
32
- exporter: myCustomExporter,
33
- spec: /* OAS content in json or yaml */
34
- };
35
-
36
- app.use(oasTelemetry(customTelemetryConfig));
37
- ```
38
-
39
- ## Telemetry UI
40
-
41
- You can access the telemetry UI in the endpoint ``/telemetry``
42
-
43
-
44
- ## API Telemetry Endpoints
45
-
46
- OAS Telemetry middleware adds the following endpoints to your Express application:
47
-
48
-
49
- - /telemetry/start: Start telemetry data collection.
50
- - /telemetry/stop: Stop telemetry data collection.
51
- - /telemetry/status: Get status of telemetry.
52
- - /telemetry/reset: Reset telemetry data.
53
- - /telemetry/list: List all telemetry data.
54
- - /telemetry/find (POST): Search telemetry data.
55
- - /telemetry/heapStats: Shows v8 heapStats.
56
-
57
-
58
- ## Simple Example [ES Module](https://nodejs.org/docs/latest/api/esm.html) (*.mjs)
59
- ```js index.mjs
60
- import oasTelemetry from '@oas-tools/oas-telemetry';
61
- import express from 'express';
62
-
63
- const app = express();
64
- const port = 3000;
65
-
66
- const spec = { "paths": {
67
- "/api/v1/pets": {
68
- "get": {
69
- "summary": "Get pets",
70
- "responses":{
71
- "200": {
72
- "description": "Success"
73
- }
74
- }
75
- }
76
- }
77
- }
78
- }
79
-
80
- app.use(oasTelemetry({
81
- spec : JSON.stringify(spec)
82
- }))
83
-
84
- app.use(express.json());
85
-
86
- app.get("/api/v1/pets", (req, res) => {
87
- res.send([{ name: "rocky"},{ name: "pikachu"}]);
88
- });
89
-
90
- app.listen(port, () => {
91
- console.log(`Example app listening at http://localhost:${port}`);
92
- console.log(`Telemetry portal available at http://localhost:${port}/telemetry`);
93
- });
94
- ```
95
-
96
- ## Simple Example [Common.js Module](https://nodejs.org/docs/latest/api/modules.html) (*.cjs)
97
- ```js index.cjs
98
- let oasTelemetry = require('@oas-tools/oas-telemetry');
99
- let express = require('express');
100
-
101
- const app = express();
102
- const port = 3000;
103
-
104
- const spec = { "paths": {
105
- "/api/v1/pets": {
106
- "get": {
107
- "summary": "Get pets",
108
- "responses":{
109
- "200": {
110
- "description": "Success"
111
- }
112
- }
113
- }
114
- }
115
- }
116
- }
117
-
118
- app.use(oasTelemetry({
119
- spec : JSON.stringify(spec)
120
- }))
121
-
122
- app.use(express.json());
123
-
124
- app.get("/api/v1/pets", (req, res) => {
125
- res.send([{ name: "rocky"},{ name: "pikachu"}]);
126
- });
127
-
128
- app.listen(port, () => {
129
- console.log(`Example app listening at http://localhost:${port}`);
130
- console.log(`Telemetry portal available at http://localhost:${port}/telemetry`);
131
- });
132
- ```
133
-
1
+ # OAS TELEMETRY
2
+
3
+ OAS Telemetry offers an express middleware designed for collecting telemetry data using Open Telemetry in applications built using the OpenAPI Specification (OAS). This middleware allows developers to easily incorporate telemetry functionality into their APIs.
4
+
5
+ OAS Telemetry provides a set of endpoints that can be accessed to perform various actions related to telemetry data, such as starting and stopping data collection, resetting telemetry data, listing collected data, and searching for specific telemetry records. These endpoints can be easily integrated into an Express.js application, providing developers with a convenient way to manage and analyze telemetry data.
6
+
7
+ Additionally, OAS Telemetry offers customization options, allowing developers to configure the telemetry middleware according to their specific requirements.
8
+
9
+ Overall, OAS Telemetry will serve as a valuable tool for developers looking to gain insights into the operation and performance of their OAS-based APIs, enabling them to monitor, debug, and optimize their applications effectively.
10
+
11
+
12
+
13
+
14
+
15
+ ## Usage
16
+ To use the middelware add this two lines in your index.js (ESM):
17
+ ```js
18
+ import oasTelemetry from 'oas-telemetry';
19
+ import {readFileSync} from 'fs';
20
+
21
+ app.use(oasTelemetry({
22
+ spec : readFileSync('./spec/oas.yaml',{ encoding: 'utf8', flag: 'r' })
23
+ }))
24
+
25
+ ```
26
+
27
+ ## Custom Configuration
28
+
29
+ You can also customize the telemetry configuration by passing options to the middleware function. For example:
30
+ ```js
31
+ const customTelemetryConfig = {
32
+ exporter: myCustomExporter,
33
+ spec: /* OAS content in json or yaml */
34
+ };
35
+
36
+ app.use(oasTelemetry(customTelemetryConfig));
37
+ ```
38
+
39
+ ## Telemetry UI
40
+
41
+ You can access the telemetry UI in the endpoint ``/telemetry``
42
+
43
+
44
+ ## API Telemetry Endpoints
45
+
46
+ OAS Telemetry middleware adds the following endpoints to your Express application:
47
+
48
+
49
+ - /telemetry/start: Start telemetry data collection.
50
+ - /telemetry/stop: Stop telemetry data collection.
51
+ - /telemetry/status: Get status of telemetry.
52
+ - /telemetry/reset: Reset telemetry data.
53
+ - /telemetry/list: List all telemetry data.
54
+ - /telemetry/find (POST): Search telemetry data.
55
+ - /telemetry/heapStats: Shows v8 heapStats.
56
+
57
+
58
+ ## Simple Example [ES Module](https://nodejs.org/docs/latest/api/esm.html) (*.mjs)
59
+ ```js index.mjs
60
+ import oasTelemetry from '@oas-tools/oas-telemetry';
61
+ import express from 'express';
62
+
63
+ const app = express();
64
+ const port = 3000;
65
+
66
+ const spec = { "paths": {
67
+ "/api/v1/pets": {
68
+ "get": {
69
+ "summary": "Get pets",
70
+ "responses":{
71
+ "200": {
72
+ "description": "Success"
73
+ }
74
+ }
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ app.use(oasTelemetry({
81
+ spec : JSON.stringify(spec)
82
+ }))
83
+
84
+ app.use(express.json());
85
+
86
+ app.get("/api/v1/pets", (req, res) => {
87
+ res.send([{ name: "rocky"},{ name: "pikachu"}]);
88
+ });
89
+
90
+ app.listen(port, () => {
91
+ console.log(`Example app listening at http://localhost:${port}`);
92
+ console.log(`Telemetry portal available at http://localhost:${port}/telemetry`);
93
+ });
94
+ ```
95
+
96
+ ## Simple Example [Common.js Module](https://nodejs.org/docs/latest/api/modules.html) (*.cjs)
97
+ ```js index.cjs
98
+ let oasTelemetry = require('@oas-tools/oas-telemetry');
99
+ let express = require('express');
100
+
101
+ const app = express();
102
+ const port = 3000;
103
+
104
+ const spec = { "paths": {
105
+ "/api/v1/pets": {
106
+ "get": {
107
+ "summary": "Get pets",
108
+ "responses":{
109
+ "200": {
110
+ "description": "Success"
111
+ }
112
+ }
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ app.use(oasTelemetry({
119
+ spec : JSON.stringify(spec)
120
+ }))
121
+
122
+ app.use(express.json());
123
+
124
+ app.get("/api/v1/pets", (req, res) => {
125
+ res.send([{ name: "rocky"},{ name: "pikachu"}]);
126
+ });
127
+
128
+ app.listen(port, () => {
129
+ console.log(`Example app listening at http://localhost:${port}`);
130
+ console.log(`Telemetry portal available at http://localhost:${port}/telemetry`);
131
+ });
132
+ ```
133
+
@@ -34,6 +34,7 @@ class InMemoryExporter {
34
34
  cleanSpans.forEach(t => {
35
35
  dbglog(`Sending trace <${t._id}> to plugin (Plugin #${i}) <${p.name}>`);
36
36
  dbglog(`Trace: \n<${JSON.stringify(t, null, 2)}`);
37
+ //TODO: This should be called newSpan instead of newTrace
37
38
  p.newTrace(t);
38
39
  });
39
40
  });
@@ -65,8 +66,8 @@ class InMemoryExporter {
65
66
  this._spans = new _nedb.default();
66
67
  return this.forceFlush();
67
68
  }
68
- /**
69
- * Exports any pending spans in the exporter
69
+ /**
70
+ * Exports any pending spans in the exporter
70
71
  */
71
72
  forceFlush() {
72
73
  return Promise.resolve();
@@ -110,30 +111,30 @@ function removeCircularRefs(obj) {
110
111
  return JSON.parse(jsonString);
111
112
  }
112
113
 
113
- /**
114
- * Recursively converts dot-separated keys in an object to nested objects.
115
- *
116
- * @param {Object} obj - The object to process.
117
- * @returns {Object} - The object with all dot-separated keys converted to nested objects.
118
- * @example
119
- * // Input:
120
- * // {
121
- * // "http.method": "GET",
122
- * // "http.url": "http://example.com",
123
- * // "nested.obj.key": "value"
124
- * // }
125
- * // Output:
126
- * // {
127
- * // "http": {
128
- * // "method": "GET",
129
- * // "url": "http://example.com"
130
- * // },
131
- * // "nested": {
132
- * // "obj": {
133
- * // "key": "value"
134
- * // }
135
- * // }
136
- * // }
114
+ /**
115
+ * Recursively converts dot-separated keys in an object to nested objects.
116
+ *
117
+ * @param {Object} obj - The object to process.
118
+ * @returns {Object} - The object with all dot-separated keys converted to nested objects.
119
+ * @example
120
+ * // Input:
121
+ * // {
122
+ * // "http.method": "GET",
123
+ * // "http.url": "http://example.com",
124
+ * // "nested.obj.key": "value"
125
+ * // }
126
+ * // Output:
127
+ * // {
128
+ * // "http": {
129
+ * // "method": "GET",
130
+ * // "url": "http://example.com"
131
+ * // },
132
+ * // "nested": {
133
+ * // "obj": {
134
+ * // "key": "value"
135
+ * // }
136
+ * // }
137
+ * // }
137
138
  */
138
139
  function convertToNestedObject(obj) {
139
140
  const result = {};
@@ -157,11 +158,11 @@ function convertToNestedObject(obj) {
157
158
  return result;
158
159
  }
159
160
 
160
- /**
161
- * Applies nesting to all dot-separated keys within an object.
162
- *
163
- * @param {Object} obj - The object to apply nesting to.
164
- * @returns {Object} - The transformed object with nested structures.
161
+ /**
162
+ * Applies nesting to all dot-separated keys within an object.
163
+ *
164
+ * @param {Object} obj - The object to apply nesting to.
165
+ * @returns {Object} - The transformed object with nested structures.
165
166
  */
166
167
  function applyNesting(obj) {
167
168
  // Recursively apply convertToNestedObject to each level of the object
package/dist/index.cjs CHANGED
@@ -12,6 +12,7 @@ var _path = _interopRequireDefault(require("path"));
12
12
  var _jsYaml = _interopRequireDefault(require("js-yaml"));
13
13
  var _ui = _interopRequireDefault(require("./ui.cjs"));
14
14
  var _axios = _interopRequireDefault(require("axios"));
15
+ var _importFromString = require("import-from-string");
15
16
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
17
  // telemetryMiddleware.js
17
18
 
@@ -202,29 +203,65 @@ const listPlugins = (req, res) => {
202
203
  };
203
204
  }));
204
205
  };
205
- const registerPlugin = (req, res) => {
206
+ const registerPlugin = async (req, res) => {
206
207
  let pluginResource = req.body;
207
208
  dbglog(`Plugin Registration Request: = ${JSON.stringify(req.body, null, 2)}...`);
208
209
  dbglog(`Getting plugin at ${pluginResource.url}...`);
209
- _axios.default.get(pluginResource.url).then(response => {
210
- dbglog(`Plugin fetched.`);
211
- const pluginCode = response.data;
212
- dbglog("Plugin size: " + pluginCode.length);
213
- var plugin;
214
- eval(pluginCode);
215
- plugin.load(pluginResource.config);
216
- if (plugin.isConfigured()) {
217
- dbglog(`Loaded plugin <${plugin.getName()}>`);
218
- pluginResource.plugin = plugin;
219
- pluginResource.name = plugin.getName();
220
- pluginResource.active = true;
221
- plugins.push(pluginResource);
222
- _telemetry.inMemoryExporter.activatePlugin(pluginResource.plugin);
223
- res.status(201).send(`Plugin registered`);
210
+ let pluginCode;
211
+ if (!pluginResource.url && !pluginResource.code) {
212
+ res.status(400).send(`Plugin code or URL must be provided`);
213
+ return;
214
+ }
215
+ let module;
216
+ try {
217
+ if (pluginResource.code) {
218
+ pluginCode = pluginResource.code;
219
+ } else {
220
+ const response = await _axios.default.get(pluginResource.url);
221
+ pluginCode = response.data;
222
+ }
223
+ if (!pluginCode) {
224
+ res.status(400).send(`Plugin code could not be loaded`);
225
+ return;
226
+ }
227
+ dbglog("Plugin size: " + pluginCode?.length);
228
+ if (pluginResource?.moduleFormat && pluginResource.moduleFormat.toUpperCase() == "ESM") {
229
+ console.log("ESM detected");
230
+ module = await (0, _importFromString.importFromString)(pluginCode);
224
231
  } else {
225
- console.error(`Plugin <${plugin.getName()}> can not be configured`);
226
- res.status(400).send(`Plugin configuration problem`);
232
+ console.log("CJS detected (default)");
233
+ module = await (0, _importFromString.requireFromString)(pluginCode);
234
+ console.log(module);
235
+ }
236
+ } catch (error) {
237
+ console.error(`Error loading plugin: ${error}`);
238
+ res.status(400).send(`Error loading plugin: ${error}`);
239
+ return;
240
+ }
241
+ if (module.plugin == undefined) {
242
+ res.status(400).send(`Plugin code should export a "plugin" object`);
243
+ console.log("Error in plugin code: no plugin object exported");
244
+ return;
245
+ }
246
+ for (let requiredFunction of ["load", "getName", "isConfigured"]) {
247
+ if (module.plugin[requiredFunction] == undefined) {
248
+ res.status(400).send(`The plugin code exports a "plugin" object, however it should have a "${requiredFunction}" method`);
249
+ console.log("Error in plugin code: some required functions are missing");
250
+ return;
227
251
  }
228
- }).catch(err => console.error("registerPlugin:" + err));
252
+ }
253
+ let plugin = module.plugin;
254
+ if (plugin.isConfigured()) {
255
+ dbglog(`Loaded plugin <${plugin.getName()}>`);
256
+ pluginResource.plugin = plugin;
257
+ pluginResource.name = plugin.getName();
258
+ pluginResource.active = true;
259
+ plugins.push(pluginResource);
260
+ _telemetry.inMemoryExporter.activatePlugin(pluginResource.plugin);
261
+ res.status(201).send(`Plugin registered`);
262
+ } else {
263
+ console.error(`Plugin <${plugin.getName()}> can not be configured`);
264
+ res.status(400).send(`Plugin configuration problem`);
265
+ }
229
266
  };
230
267
  module.exports = exports.default;
File without changes