-
Notifications
You must be signed in to change notification settings - Fork 544
/
Copy pathinstrumentation.ts
400 lines (379 loc) · 13.4 KB
/
instrumentation.ts
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Span, SpanKind, SpanStatusCode } from '@opentelemetry/api';
import {
InstrumentationBase,
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
isWrapped,
} from '@opentelemetry/instrumentation';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import type * as cucumber from '@cucumber/cucumber';
import type * as messages from '@cucumber/messages';
import type TestCaseRunner from '@cucumber/cucumber/lib/runtime/test_case_runner';
import type {
DefineStepPattern,
IDefineStepOptions,
IDefineTestRunHookOptions,
} from '@cucumber/cucumber/lib/support_code_library_builder/types';
import { AttributeNames, CucumberInstrumentationConfig } from './types';
import { VERSION } from './version';
const hooks = ['Before', 'BeforeStep', 'AfterStep', 'After'] as const;
const steps = ['Given', 'When', 'Then'] as const;
type Cucumber = typeof cucumber;
type Hook = (typeof hooks)[number];
type Step = (typeof steps)[number];
export class CucumberInstrumentation extends InstrumentationBase {
private module: Cucumber | undefined;
constructor(config: CucumberInstrumentationConfig = {}) {
super('@opentelemetry/instrumentation-cucumber', VERSION, config);
}
init(): InstrumentationNodeModuleDefinition<any>[] {
return [
new InstrumentationNodeModuleDefinition<Cucumber>(
'@cucumber/cucumber',
['^8.0.0', '^9.0.0'],
(moduleExports, moduleVersion) => {
this._diag.debug(
`Applying patch for @cucumber/cucumber@${moduleVersion}`
);
this.module = moduleExports;
steps.forEach(step => {
if (isWrapped(moduleExports[step])) {
this._unwrap(moduleExports, step);
}
this._wrap(moduleExports, step, this._getStepPatch(step));
});
hooks.forEach(hook => {
if (isWrapped(moduleExports[hook])) {
this._unwrap(moduleExports, hook);
}
this._wrap(moduleExports, hook, this._getHookPatch(hook));
});
return moduleExports;
},
(moduleExports, moduleVersion) => {
if (moduleExports === undefined) return;
this._diag.debug(
`Removing patch for @cucumber/cucumber@${moduleVersion}`
);
[...hooks, ...steps].forEach(method => {
this._unwrap(moduleExports, method);
});
},
[
new InstrumentationNodeModuleFile<{
default: { new (): TestCaseRunner; prototype: TestCaseRunner };
}>(
'@cucumber/cucumber/lib/runtime/test_case_runner.js',
['^8.0.0', '^9.0.0'],
(moduleExports, moduleVersion) => {
this._diag.debug(
`Applying patch for @cucumber/cucumber/lib/runtime/test_case_runner.js@${moduleVersion}`
);
if (isWrapped(moduleExports.default.prototype.run)) {
this._unwrap(moduleExports.default.prototype, 'run');
this._unwrap(moduleExports.default.prototype, 'runStep');
if ('runAttempt' in moduleExports.default.prototype) {
this._unwrap(moduleExports.default.prototype, 'runAttempt');
}
}
this._wrap(
moduleExports.default.prototype,
'run',
this._getTestCaseRunPatch()
);
this._wrap(
moduleExports.default.prototype,
'runStep',
this._getTestCaseRunStepPatch()
);
if ('runAttempt' in moduleExports.default.prototype) {
this._wrap(
moduleExports.default.prototype,
'runAttempt',
this._getTestCaseRunAttemptPatch()
);
}
return moduleExports;
},
(moduleExports, moduleVersion) => {
if (moduleExports === undefined) return;
this._diag.debug(
`Removing patch for @cucumber/cucumber/lib/runtime/test_case_runner.js@${moduleVersion}`
);
this._unwrap(moduleExports.default.prototype, 'run');
this._unwrap(moduleExports.default.prototype, 'runStep');
if ('runAttempt' in moduleExports.default.prototype) {
this._unwrap(moduleExports.default.prototype, 'runAttempt');
}
}
),
]
),
];
}
private static mapTags(tags: readonly messages.Tag[]): string[] {
return tags.map(tag => tag.name);
}
private static setSpanToError(span: Span, error: any) {
span.recordException(error);
span.setStatus({
code: SpanStatusCode.ERROR,
message: error?.message ?? error,
});
}
private setSpanToStepStatus(
span: Span,
status: messages.TestStepResultStatus,
context?: string
) {
// if the telemetry is enabled, the module should be defined
if (!this.module) return;
span.setAttribute(AttributeNames.STEP_STATUS, status);
if (
[
this.module.Status.UNDEFINED,
this.module.Status.AMBIGUOUS,
this.module.Status.FAILED,
].includes(status)
) {
span.recordException(status);
span.setStatus({
code: SpanStatusCode.ERROR,
message: context || status,
});
}
}
private _getTestCaseRunPatch() {
const instrumentation = this;
return function (original: TestCaseRunner['run']): TestCaseRunner['run'] {
return async function (this: TestCaseRunner, ...args) {
const gherkinDocument = this[
'gherkinDocument'
] as Required<messages.GherkinDocument>;
const { feature } = gherkinDocument;
const pickle = this['pickle'] as messages.Pickle;
const scenario = feature.children.find(
node => node?.scenario?.id === pickle.astNodeIds[0]
)?.scenario as messages.Scenario;
return instrumentation.tracer.startActiveSpan(
`Feature: ${feature.name}. Scenario: ${pickle.name}`,
{
kind: SpanKind.CLIENT,
attributes: {
[SemanticAttributes.CODE_FILEPATH]: gherkinDocument.uri,
[SemanticAttributes.CODE_LINENO]: scenario.location.line,
[SemanticAttributes.CODE_FUNCTION]: scenario.name,
[SemanticAttributes.CODE_NAMESPACE]: feature.name,
[AttributeNames.FEATURE_TAGS]: CucumberInstrumentation.mapTags(
feature.tags
),
[AttributeNames.FEATURE_LANGUAGE]: feature.language,
[AttributeNames.FEATURE_DESCRIPTION]: feature.description,
[AttributeNames.SCENARIO_TAGS]: CucumberInstrumentation.mapTags(
scenario.tags
),
[AttributeNames.SCENARIO_DESCRIPTION]: scenario.description,
},
},
async span => {
try {
const status = await original.apply(this, args);
instrumentation.setSpanToStepStatus(span, status);
return status;
} catch (error: any) {
CucumberInstrumentation.setSpanToError(span, error);
throw error;
} finally {
span.end();
}
}
);
};
};
}
private _getTestCaseRunStepPatch() {
const instrumentation = this;
return function (
original: TestCaseRunner['runStep']
): TestCaseRunner['runStep'] {
return async function (
this: TestCaseRunner,
...args
): Promise<messages.TestStepResult> {
const [pickleStep] = args;
return instrumentation.tracer.startActiveSpan(
pickleStep.text,
{
kind: SpanKind.CLIENT,
attributes: {
[AttributeNames.STEP_TYPE]: pickleStep.type,
},
},
async span => {
try {
const result = await original.apply(this, args);
instrumentation.setSpanToStepStatus(
span,
result.status,
result.message
);
return result;
} catch (error) {
CucumberInstrumentation.setSpanToError(span, error);
throw error;
} finally {
span.end();
}
}
);
};
};
}
private _getTestCaseRunAttemptPatch() {
const instrumentation = this;
return function (
original: TestCaseRunner['runAttempt']
): TestCaseRunner['runAttempt'] {
return async function (this: TestCaseRunner, ...args): Promise<boolean> {
const [attempt] = args;
return instrumentation.tracer.startActiveSpan(
`Attempt #${attempt}`,
{
kind: SpanKind.CLIENT,
attributes: {},
},
async span => {
try {
const result = await original.apply(this, args);
const worstResult = this.getWorstStepResult();
instrumentation.setSpanToStepStatus(
span,
worstResult.status,
worstResult.message
);
return result;
} catch (error) {
CucumberInstrumentation.setSpanToError(span, error);
throw error;
} finally {
span.end();
}
}
);
};
};
}
private _getHookPatch<H extends Hook>(name: H) {
const instrumentation = this;
return function (original: Cucumber[H]): Cucumber[H] {
return function (
this: {},
tagsOrOptions: string | IDefineTestRunHookOptions | Function,
code?: Function
) {
if (typeof tagsOrOptions === 'function') {
code = tagsOrOptions;
tagsOrOptions = {};
}
function traceableCode(
this: cucumber.IWorld,
arg: cucumber.ITestCaseHookParameter
) {
// because we're wrapping the function that was passed to the hook,
// it will stay wrapped in cucumber's internal state
// even if we disable the instrumentation
if (!instrumentation.isEnabled()) return code?.call(this, arg);
return instrumentation.tracer.startActiveSpan(
name,
{
kind: SpanKind.CLIENT,
},
async span => {
try {
return await code?.call(this, arg);
} catch (error: any) {
this.attach?.(JSON.stringify(span.spanContext()));
CucumberInstrumentation.setSpanToError(span, error);
throw error;
} finally {
span.end();
}
}
);
}
return original.call(this, tagsOrOptions as any, traceableCode as any);
};
};
}
private _getStepPatch<S extends Step>(name: S) {
const instrumentation = this;
return function (original: Cucumber[S]): Cucumber[S] {
return function (
this: {},
pattern: DefineStepPattern,
options: IDefineStepOptions | Function,
code?: Function
): void {
if (typeof options === 'function') {
code = options;
options = {};
}
function traceableCode(this: cucumber.IWorld, ...args: any[]) {
// because we're wrapping the function that was passed to the hook,
// it will stay wrapped in cucumber's internal state
// even if we disable the instrumentation
if (!instrumentation.isEnabled()) return code?.apply(this, args);
return instrumentation.tracer.startActiveSpan(
`${name}(${pattern.toString()})`,
{
kind: SpanKind.CLIENT,
// ignore the last argument because it's a callback
attributes: args.slice(0, -1).reduce(
(attrs, arg, index) => ({
...attrs,
[`${AttributeNames.STEP_ARGS}[${index}]`]:
arg?.raw instanceof Function
? JSON.stringify(arg.raw())
: arg,
}),
{}
),
},
async span => {
try {
return await code?.apply(this, args);
} catch (error: any) {
this.attach?.(JSON.stringify(span.spanContext()));
CucumberInstrumentation.setSpanToError(span, error);
throw error;
} finally {
span.end();
}
}
);
}
// cucumber asks for the number of arguments to match the specified pattern
// copy the value from the original function
Object.defineProperty(traceableCode, 'length', {
value: code?.length,
});
return original.call(this, pattern, options, traceableCode as any);
};
};
}
}