generated from cap-js-community/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcds-plugin.js
More file actions
239 lines (207 loc) · 10.4 KB
/
cds-plugin.js
File metadata and controls
239 lines (207 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
const { increaseCounter, createObservableGauge} = require('./lib/metrics/entity-metrics')
const events = ["READ", "CREATE", "DELETE", "UPDATE"];
const userAttributes = ["tenant"];
let _startup = true
const cds = require('@sap/cds')
const logger = cds.log('telemetry')
/* istanbul ignore next */
if (!(cds.cli?.command in { '': 1, serve: 1, run: 1 })) _startup = false
// cds add XXX currently also has cli.command === ''
/* istanbul ignore next */
const i = process.argv.indexOf('add')
/* istanbul ignore next */
if (i > 1 && process.argv[i - 1].match(/cds(\.js)?$/)) _startup = false
/* istanbul ignore next */
if (!!process.env.NO_TELEMETRY && process.env.NO_TELEMETRY !== 'false') _startup = false
if(_startup && cds?.requires?.telemetry?.metrics?.enableBusinessMetrics) {
//business metrics handling
cds.once("served", async () => {
try {
// Go through all services
for (let srv of cds.services) {
try {
// Go through all entities of that service
for (let entity of srv.entities) {
await handleGaugeAnnotation(entity);
await handleCounterAnnotationOnEntity(entity, srv);
if (entity.actions) {
for (let boundAction of entity.actions) {
await handleCounterAnnotationOnBoundAction(entity, boundAction, srv)
}
}
}
for (let action of srv.actions) {
await handleCounterAnnotationOnUnboundAction(action, srv);
}
} catch (serviceError) {
logger.error(`Error processing service ${srv.name}:`, serviceError.message);
}
}
} catch (error) {
logger.error('Error in served event handler:', error.message);
}
});
}
function getLabels(attributes, req) {
let labels = {};
try {
if (attributes) {
attributes.forEach((attribute) => {
try {
const attributeName = attribute['='] || attribute;
// Validate if the attribute is in the list of valid attributes
if (!userAttributes.includes(attributeName)) {
const errorMsg = `Invalid attribute '${attributeName}'. Valid attributes are: ${userAttributes.join(', ')}`;
throw new Error(errorMsg);
}
switch (attributeName) {
case 'tenant':
labels.tenant = req?.authInfo?.getSubdomain() || 'unknown';
break;
default: {
// This should not happen due to validation above, but keeping as fallback
/* istanbul ignore next */
const fallbackErrorMsg = `Unsupported attribute: ${attributeName}`;
throw new Error(fallbackErrorMsg);
}
}
} catch (attributeError) {
logger.error(`Error processing attribute ${attribute['='] || attribute}:`, attributeError.message);
throw attributeError; // Re-throw to stop processing
}
});
}
} catch (error) {
logger.error('Error getting labels:', error.message);
throw error; // Re-throw to propagate the error
}
return labels;
}
function validateAttributes(attributes, context) {
if (!attributes || !Array.isArray(attributes)) {
return; // No attributes to validate
}
logger.debug(`Checking attributes for ${context}:`, attributes.map(attr => attr['='] || attr));
attributes.forEach((attribute) => {
const attributeName = attribute['='] || attribute;
if (!userAttributes.includes(attributeName)) {
const errorMsg = `Invalid attribute '${attributeName}' in ${context}. Valid attributes are: ${userAttributes.join(', ')}`;
logger.error(errorMsg);
throw new Error(errorMsg);
}
});
logger.debug(`All attributes valid for ${context}`);
}
async function handleCounterAnnotationOnEntity(entity, srv) {
try {
if (entity['@Counter.attributes']) {
// Validate attributes before setting up handlers
validateAttributes(entity['@Counter.attributes'], `entity ${entity.name} @Counter.attributes`);
// Register after handler for all events and create counter with given attributes
for (let event of events) {
srv.after(event, entity, async (req) => {
try {
increaseCounter(`${entity.name}_${event}_total`, getLabels(entity['@Counter.attributes'], req));
// createCounterMetrics({entity: entity.name, event: event, labels: getLabels(event, req)})
} catch (error) {
logger.error(`Error handling counter for entity ${entity.name}, event ${event}:`, error.message);
}
});
}
}
else if (entity['@Counter']) {
// User annotated with only events, may or may not have specified attributes
if (entity['@Counter'].length > 0) {
// Register after handler for only those events as annotated by user
for (let event of entity['@Counter']) {
// Validate attributes if they exist
if (event.attributes) {
validateAttributes(event.attributes, `entity ${entity.name} @Counter event ${event.event}`);
}
srv.after(event.event, entity, async (_, req) => {
try {
let attributes = event.attributes ? event.attributes : userAttributes;
increaseCounter(`${entity.name}_${event.event}_total`, getLabels(attributes, req));
// createCounterMetrics({entity: entity.name, event: event['='], labels: getLabels(event, req)})
} catch (error) {
logger.error(`Error handling counter for entity ${entity.name}, event ${event.event}:`, error.message);
}
});
}
} else {
// User annotated without specifying the event and attributes
for (let event of events) {
srv.after(event, entity, async (req) => {
try {
increaseCounter(`${entity.name}_${event}_total`, getLabels(userAttributes, req));
// createCounterMetrics({entity: entity.name, event: event, labels: getLabels([], req)})
} catch (error) {
logger.error(`Error handling counter for entity ${entity.name}, event ${event}:`, error.message);
}
});
}
}
}
} catch (error) {
logger.error(`Error setting up counter annotation for entity ${entity.name}:`, error.message);
throw error; // Re-throw validation errors to stop service initialization
}
}
async function handleCounterAnnotationOnBoundAction(entity, boundAction, srv) {
try {
if (boundAction['@Counter'] || boundAction['@Counter.attributes']) {
let attributes = boundAction['@Counter'] ? userAttributes : boundAction['@Counter.attributes'];
// Validate attributes
if (boundAction['@Counter.attributes']) {
validateAttributes(boundAction['@Counter.attributes'], `bound action ${boundAction.name} @Counter.attributes`);
}
// Extract name from action.name => CatalogService.purchaseBook -> purchaseBook
const actionName = boundAction.name.split('.').pop();
srv.after(actionName, entity, async (_, req) => {
try {
increaseCounter(`${boundAction.parent}_${boundAction.name}_total`, getLabels(attributes, req));
// createCounterMetrics({isAction: true, action: `${boundAction.parent}-${boundAction.name}`, actionResponse: res})
} catch (error) {
logger.error(`Error handling counter for bound action ${boundAction.name}:`, error.message);
}
});
}
} catch (error) {
logger.error(`Error setting up counter annotation for bound action ${boundAction.name}:`, error.message);
throw error; // Re-throw validation errors to stop service initialization
}
}
async function handleCounterAnnotationOnUnboundAction(action, srv) {
try {
if (action['@Counter'] || action['@Counter.attributes']) {
let attributes = action['@Counter'] ? userAttributes : action['@Counter.attributes'];
// Validate attributes
if (action['@Counter.attributes']) {
validateAttributes(action['@Counter.attributes'], `unbound action ${action.name} @Counter.attributes`);
}
// Extract name from action.name => CatalogService.purchaseBook -> purchaseBook
const actionName = action.name.split('.').pop();
srv.after(actionName, async (_, req) => {
try {
increaseCounter(`${action.name}_total`, getLabels(attributes, req));
// createCounterMetrics({isAction: true, action: action.name, actionReq: req})
} catch (error) {
logger.error(`Error handling counter for unbound action ${action.name}:`, error.message);
}
});
}
} catch (error) {
logger.error(`Error setting up counter annotation for unbound action ${action.name}:`, error.message);
throw error; // Re-throw validation errors to stop service initialization
}
}
async function handleGaugeAnnotation(entity) {
try {
if (entity['@Gauge.observe'] && entity['@Gauge.key']) {
await createObservableGauge(entity, entity['@Gauge.observe'], entity['@Gauge.key']);
}
} catch (error) {
logger.error(`Error setting up gauge annotation for entity ${entity.name}:`, error.message);
}
}
// if (_startup) require('./lib')()