@midwayjs/otel 3.0.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 ADDED
@@ -0,0 +1,105 @@
1
+ # midwayjs open-telemetry module
2
+
3
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/midwayjs/midway/pulls)
4
+
5
+ this is a sub package for midway.
6
+
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ $ npm install --save @opentelemetry/api
12
+ $ npm install --save @opentelemetry/sdk-node
13
+ $ npm install --save @opentelemetry/auto-instrumentations-node
14
+ ```
15
+
16
+ Install component if you want decorator support.
17
+
18
+ ```bash
19
+ $ npm i @midwayjs/otel@3 --save
20
+ ```
21
+
22
+ ## Enable open-telemetry
23
+
24
+ open-telemetry must be loaded at the first of user code.
25
+
26
+ you can add at `bootstrap.js`.
27
+
28
+ ```typescript
29
+ const process = require('process');
30
+ const opentelemetry = require('@opentelemetry/sdk-node');
31
+ const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
32
+ const { ConsoleSpanExporter } = require('@opentelemetry/sdk-trace-base');
33
+ const { Resource } = require('@opentelemetry/resources');
34
+ const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');
35
+ const { Bootstrap } = require('@midwayjs/bootstrap');
36
+
37
+ // configure the SDK to export telemetry data to the console
38
+ // enable all auto-instrumentations from the meta package
39
+ const traceExporter = new ConsoleSpanExporter();
40
+ const sdk = new opentelemetry.NodeSDK({
41
+ resource: new Resource({
42
+ [SemanticResourceAttributes.SERVICE_NAME]: 'my-service',
43
+ }),
44
+ traceExporter,
45
+ instrumentations: [getNodeAutoInstrumentations()]
46
+ });
47
+
48
+ // initialize the SDK and register with the OpenTelemetry API
49
+ // this enables the API to record telemetry
50
+ sdk.start()
51
+ .then(() => {
52
+ return Bootstrap
53
+ .configure(/**/)
54
+ .run();
55
+ });
56
+
57
+ // gracefully shut down the SDK on process exit
58
+ process.on('SIGTERM', () => {
59
+ sdk.shutdown()
60
+ .then(() => console.log('Tracing terminated'))
61
+ .catch((error) => console.log('Error terminating tracing', error))
62
+ .finally(() => process.exit(0));
63
+ });
64
+ ```
65
+
66
+ You can find more information at [opentelemetry-js](https://github.com/open-telemetry/opentelemetry-js)
67
+
68
+
69
+ ## Decorator Support
70
+
71
+ Enable component first.
72
+
73
+ ```typescript
74
+ import { Configuration } from '@midwayjs/decorator';
75
+ import * as koa from '@midwayjs/koa';
76
+ import * as otel from '@midwayjs/otel';
77
+
78
+ @Configuration({
79
+ imports: [
80
+ koa,
81
+ otel
82
+ ]
83
+ })
84
+ export class MainConfiguration {
85
+ }
86
+ ```
87
+
88
+ Otel component add a @Trace decorator for method.
89
+
90
+ ```typescript
91
+ export class UserService {
92
+
93
+ @Trace('user.get')
94
+ async getUser() {
95
+ // ...
96
+ }
97
+ }
98
+ ```
99
+
100
+ it will create a new span in current trace.
101
+
102
+
103
+ ## License
104
+
105
+ [MIT]((http://github.com/midwayjs/midway/blob/master/LICENSE))
@@ -0,0 +1,8 @@
1
+ import { MidwayDecoratorService } from '@midwayjs/core';
2
+ import { TraceService } from './service';
3
+ export declare class OtelConfiguration {
4
+ decoratorService: MidwayDecoratorService;
5
+ traceService: TraceService;
6
+ onReady(): Promise<void>;
7
+ }
8
+ //# sourceMappingURL=configuration.d.ts.map
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.OtelConfiguration = void 0;
13
+ const decorator_1 = require("@midwayjs/decorator");
14
+ const core_1 = require("@midwayjs/core");
15
+ const tracer_decorator_1 = require("./decorator/tracer.decorator");
16
+ const service_1 = require("./service");
17
+ const api_1 = require("@opentelemetry/api");
18
+ let OtelConfiguration = class OtelConfiguration {
19
+ async onReady() {
20
+ this.decoratorService.registerMethodHandler(tracer_decorator_1.TRACE_KEY, options => {
21
+ return {
22
+ around: async (joinPoint) => {
23
+ // 记录开始时间
24
+ return this.traceService.createSpan(options.metadata['spanName'], async (span) => {
25
+ try {
26
+ // 执行原方法
27
+ const result = await joinPoint.proceed(...joinPoint.args);
28
+ span.setStatus({
29
+ code: api_1.SpanStatusCode.OK,
30
+ });
31
+ span.end();
32
+ // 返回执行结果
33
+ return result;
34
+ }
35
+ catch (err) {
36
+ span.setStatus({
37
+ code: api_1.SpanStatusCode.ERROR,
38
+ });
39
+ span.recordException(err);
40
+ span.end();
41
+ throw err;
42
+ }
43
+ });
44
+ },
45
+ };
46
+ });
47
+ }
48
+ };
49
+ __decorate([
50
+ (0, decorator_1.Inject)(),
51
+ __metadata("design:type", core_1.MidwayDecoratorService)
52
+ ], OtelConfiguration.prototype, "decoratorService", void 0);
53
+ __decorate([
54
+ (0, decorator_1.Inject)(),
55
+ __metadata("design:type", service_1.TraceService)
56
+ ], OtelConfiguration.prototype, "traceService", void 0);
57
+ OtelConfiguration = __decorate([
58
+ (0, decorator_1.Configuration)({
59
+ namespace: 'otel',
60
+ })
61
+ ], OtelConfiguration);
62
+ exports.OtelConfiguration = OtelConfiguration;
63
+ //# sourceMappingURL=configuration.js.map
@@ -0,0 +1,3 @@
1
+ export declare const TRACE_KEY = "decorator:open_telemetry_key";
2
+ export declare function Trace(spanName: string): MethodDecorator;
3
+ //# sourceMappingURL=tracer.decorator.d.ts.map
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Trace = exports.TRACE_KEY = void 0;
4
+ const decorator_1 = require("@midwayjs/decorator");
5
+ exports.TRACE_KEY = 'decorator:open_telemetry_key';
6
+ function Trace(spanName) {
7
+ return (0, decorator_1.createCustomMethodDecorator)(exports.TRACE_KEY, {
8
+ spanName,
9
+ });
10
+ }
11
+ exports.Trace = Trace;
12
+ //# sourceMappingURL=tracer.decorator.js.map
@@ -0,0 +1,4 @@
1
+ export { OtelConfiguration as Configuration } from './configuration';
2
+ export * from './decorator/tracer.decorator';
3
+ export * from './service';
4
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.Configuration = void 0;
18
+ var configuration_1 = require("./configuration");
19
+ Object.defineProperty(exports, "Configuration", { enumerable: true, get: function () { return configuration_1.OtelConfiguration; } });
20
+ __exportStar(require("./decorator/tracer.decorator"), exports);
21
+ __exportStar(require("./service"), exports);
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ import { Span } from '@opentelemetry/api';
2
+ import { IMidwayApplication } from '@midwayjs/core';
3
+ export declare class TraceService {
4
+ private currentTracerName;
5
+ protected app: IMidwayApplication;
6
+ protected init(): Promise<void>;
7
+ private getCurrentSpan;
8
+ getTraceId(): string;
9
+ createSpan(name: string, callback: (span: Span) => unknown): unknown;
10
+ }
11
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.TraceService = void 0;
13
+ const decorator_1 = require("@midwayjs/decorator");
14
+ const api_1 = require("@opentelemetry/api");
15
+ let TraceService = class TraceService {
16
+ async init() {
17
+ var _a;
18
+ this.currentTracerName = (_a = this.app.getProjectName()) !== null && _a !== void 0 ? _a : 'unknown_project';
19
+ }
20
+ getCurrentSpan() {
21
+ return api_1.trace.getSpan(api_1.context.active());
22
+ }
23
+ getTraceId() {
24
+ return this.getCurrentSpan().spanContext().traceId;
25
+ }
26
+ createSpan(name, callback) {
27
+ return api_1.trace.getTracer(this.currentTracerName).startActiveSpan(name, {
28
+ kind: api_1.SpanKind.CLIENT,
29
+ }, callback);
30
+ }
31
+ };
32
+ __decorate([
33
+ (0, decorator_1.App)(),
34
+ __metadata("design:type", Object)
35
+ ], TraceService.prototype, "app", void 0);
36
+ __decorate([
37
+ (0, decorator_1.Init)(),
38
+ __metadata("design:type", Function),
39
+ __metadata("design:paramtypes", []),
40
+ __metadata("design:returntype", Promise)
41
+ ], TraceService.prototype, "init", null);
42
+ TraceService = __decorate([
43
+ (0, decorator_1.Provide)(),
44
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton)
45
+ ], TraceService);
46
+ exports.TraceService = TraceService;
47
+ //# sourceMappingURL=service.js.map
package/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from './dist/index';
2
+
3
+ declare module '@midwayjs/core/dist/interface' {
4
+ interface MidwayConfig {
5
+ otel?: Record<string, any>;
6
+ }
7
+ }
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@midwayjs/otel",
3
+ "description": "midway open telemetry component",
4
+ "version": "3.0.0",
5
+ "main": "dist/index",
6
+ "typings": "index.d.ts",
7
+ "files": [
8
+ "dist/**/*.js",
9
+ "dist/**/*.d.ts",
10
+ "index.d.ts"
11
+ ],
12
+ "devDependencies": {
13
+ "@midwayjs/core": "^3.1.1",
14
+ "@midwayjs/decorator": "^3.0.10",
15
+ "@midwayjs/mock": "^3.1.1",
16
+ "@midwayjs/koa": "^3.1.1",
17
+ "@opentelemetry/core": "^1.0.1",
18
+ "@opentelemetry/sdk-trace-node": "^1.0.1",
19
+ "@opentelemetry/sdk-trace-base": "^1.0.1"
20
+ },
21
+ "dependencies": {
22
+ "@opentelemetry/api": "^1.0.3"
23
+ },
24
+ "keywords": [
25
+ "tracing",
26
+ "open-tracing",
27
+ "open-telemetry"
28
+ ],
29
+ "author": "czy88840616 <czy88840616@gmail.com>",
30
+ "license": "MIT",
31
+ "scripts": {
32
+ "build": "tsc",
33
+ "test": "node --require=ts-node/register ../../node_modules/.bin/jest --runInBand",
34
+ "cov": "node --require=ts-node/register ../../node_modules/.bin/jest --runInBand --coverage --forceExit",
35
+ "ci": "npm run test",
36
+ "lint": "mwts check"
37
+ },
38
+ "engines": {
39
+ "node": ">=12"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/midwayjs/midway.git"
44
+ }
45
+ }