From a7bf53976ee4218c3d9fe9b6e727303f909b2d24 Mon Sep 17 00:00:00 2001 From: waiting <1661926154@qq.com> Date: Fri, 24 Jan 2025 13:21:44 +0800 Subject: [PATCH] ci: remove for debug --- .scripts/ci/ci-init-db.sh | 6 +- packages/ali-oss/.editorconfig | 16 - packages/ali-oss/CHANGELOG.md | 2279 ----------------- packages/ali-oss/LICENSE | 9 - packages/ali-oss/README.md | 123 - packages/ali-oss/bootstrap.js | 2 - packages/ali-oss/package.json | 85 - .../ali-oss/src/app/default.controller.ts | 29 - packages/ali-oss/src/app/default.types.ts | 9 - packages/ali-oss/src/app/index.controller.ts | 3 - packages/ali-oss/src/config/config.default.ts | 16 - packages/ali-oss/src/config/config.local.ts | 7 - .../ali-oss/src/config/config.unittest.ts | 24 - packages/ali-oss/src/configuration.ts | 67 - packages/ali-oss/src/imports.ts | 27 - packages/ali-oss/src/index.ts | 27 - packages/ali-oss/src/lib/component.ts | 522 ---- packages/ali-oss/src/lib/config.ts | 21 - packages/ali-oss/src/lib/index.ts | 33 - packages/ali-oss/src/lib/manager.ts | 72 - packages/ali-oss/src/lib/source-manager.ts | 97 - packages/ali-oss/src/lib/types.ts | 88 - packages/ali-oss/test/00.dummy.test.ts | 17 - packages/ali-oss/test/01.index.test.ts | 32 - packages/ali-oss/test/02.home.test.ts | 52 - packages/ali-oss/test/api-test.ts | 17 - .../ali-oss/test/component/11.mkdir.test.ts | 60 - .../ali-oss/test/component/12.upload.test.ts | 25 - .../test/component/14.createSymlink.test.ts | 27 - packages/ali-oss/test/component/18.mv.test.ts | 84 - .../test/component/19.syncRemote.test.ts | 61 - .../test/component/20.syncLocal.test.ts | 66 - .../ali-oss/test/component/22.sign.test.ts | 67 - .../test/component/23.download.test.ts | 34 - packages/ali-oss/test/component/30.rm.test.ts | 24 - packages/ali-oss/test/files/.nycrc.json | 26 - packages/ali-oss/test/files/1.txt | 0 packages/ali-oss/test/files/2.txt | 0 .../ali-oss/test/files/subdir/.nycrc.json | 26 - packages/ali-oss/test/files/subdir/1.txt | 0 packages/ali-oss/test/files/subdir/2.txt | 0 .../ali-oss/test/files/subdir/tsconfig.json | 28 - packages/ali-oss/test/files/tsconfig.json | 3 - ...\224\351\200\232\342\202\254-&a'b^c=.json" | 22 - .../test/fixtures/base-app/package.json | 12 - .../fixtures/base-app/src/configuration.ts | 19 - .../test/fixtures/base-app/src/home.ts | 37 - .../fixtures/base-app/src/oss.controller.ts | 56 - .../fixtures/base-app/src/types/api-test.ts | 3 - .../test/fixtures/base-app/src/types/index.ts | 3 - .../fixtures/base-app/src/types/lib-index.ts | 3 - .../fixtures/base-app/src/types/lib-types.ts | 3 - .../base-app/src/types/root.config.ts | 3 - .../test/fixtures/base-app/tsconfig.json | 19 - packages/ali-oss/test/helper.ts | 43 - packages/ali-oss/test/root.config.ts | 70 - packages/ali-oss/test/setup.ts | 95 - .../test/source-manager/111.mkdir.test.ts | 53 - .../test/source-manager/115.stat.test.ts | 45 - packages/ali-oss/test/tsconfig.json | 15 - packages/ali-oss/tsconfig.json | 6 - .../demo/database/default/ddl/ci-config.sql | 5 - .../demo/database/default/ddl/tb_user.sql | 11 - .../database/default/ddl/tb_user_insert.sql | 5 - packages/demo/database/default/init.sh | 14 - packages/demo/database/init-db.sh | 10 - packages/jwt/.editorconfig | 16 - packages/jwt/CHANGELOG.md | 993 ------- packages/jwt/LICENSE | 9 - packages/jwt/README.md | 102 - packages/jwt/bootstrap.js | 2 - packages/jwt/package.json | 87 - packages/jwt/src/app/default.controller.ts | 30 - packages/jwt/src/app/default.types.ts | 9 - packages/jwt/src/app/index.controller.ts | 3 - packages/jwt/src/config/config.default.ts | 28 - packages/jwt/src/config/config.local.ts | 31 - packages/jwt/src/config/config.unittest.ts | 35 - packages/jwt/src/configuration.ts | 95 - packages/jwt/src/imports.ts | 28 - packages/jwt/src/index.ts | 38 - packages/jwt/src/lib/component.ts | 215 -- packages/jwt/src/lib/config.ts | 36 - .../lib/decorator.public/index.decorator.ts | 3 - .../public.decorator-handler.ts | 102 - .../lib/decorator.public/public.decorator.ts | 22 - packages/jwt/src/lib/index.ts | 24 - packages/jwt/src/lib/resolvers.ts | 124 - packages/jwt/src/lib/types.ts | 96 - packages/jwt/src/lib/util.ts | 74 - .../jwt/src/middleware/index.middleware.ts | 3 - packages/jwt/src/middleware/jwt.middleware.ts | 149 -- packages/jwt/test/00.dummy.test.ts | 17 - packages/jwt/test/01.index.test.ts | 32 - packages/jwt/test/02.home.test.ts | 52 - packages/jwt/test/api-test.ts | 17 - packages/jwt/test/decorator/100.test.ts | 26 - .../jwt/test/fixtures/base-app/package.json | 12 - .../fixtures/base-app/src/100.controller.ts | 33 - .../fixtures/base-app/src/configuration.ts | 19 - .../jwt/test/fixtures/base-app/src/home.ts | 37 - .../jwt/test/fixtures/base-app/src/home2.ts | 68 - .../fixtures/base-app/src/types/api-test.ts | 3 - .../test/fixtures/base-app/src/types/index.ts | 3 - .../fixtures/base-app/src/types/lib-index.ts | 3 - .../fixtures/base-app/src/types/lib-types.ts | 3 - .../base-app/src/types/root.config.ts | 3 - .../jwt/test/fixtures/base-app/tsconfig.json | 19 - .../jwt/test/jwt-component/decode.test.ts | 81 - packages/jwt/test/jwt-component/sign.test.ts | 47 - .../jwt/test/jwt-component/verify.test.ts | 87 - packages/jwt/test/middleware/helper.ts | 158 -- .../jwt.middleware.passthough-func.test.ts | 115 - .../jwt.middleware.passthough-string.test.ts | 57 - .../jwt.middleware.passthough-true.test.ts | 78 - .../jwt.middleware.verifyToken-cookie.test.ts | 96 - .../jwt.middleware.verifyToken-header.test.ts | 80 - ...wt.middleware.verifyToken-jwtState.test.ts | 64 - .../jwt.middleware.debug.test.ts | 53 - .../jwt.middleware.ignore-func.test.ts | 58 - .../jwt.middleware.ignore-regex.test.ts | 36 - .../jwt.middleware.ignore-string.test.ts | 81 - packages/jwt/test/mock-data.ts | 34 - packages/jwt/test/root.config.ts | 60 - packages/jwt/test/setup.ts | 68 - packages/jwt/test/tsconfig.json | 15 - packages/jwt/test/util/resolver.test.ts | 85 - .../jwt/test/util/validatePayload.test.ts | 45 - .../jwt/test/util/validateSignSecret.test.ts | 47 - .../jwt/test/util/validateTokenString.test.ts | 28 - .../test/util/validateVerifySecret.test.ts | 45 - packages/jwt/tsconfig.json | 6 - packages/otel/.editorconfig | 16 - packages/otel/.eslintrc.yml | 21 - packages/otel/CHANGELOG.md | 1302 ---------- packages/otel/LICENSE | 9 - packages/otel/README.md | 308 --- packages/otel/README.zh-CN.md | 312 --- packages/otel/bootstrap.js | 2 - packages/otel/img/trace-scope.png | Bin 33633 -> 0 bytes packages/otel/package.json | 94 - packages/otel/src/app/default.controller.ts | 50 - packages/otel/src/app/default.service.ts | 22 - packages/otel/src/app/index.controller.ts | 4 - packages/otel/src/config/config.default.ts | 36 - packages/otel/src/config/config.local.ts | 31 - packages/otel/src/config/config.unittest.ts | 67 - packages/otel/src/configuration.ts | 139 - .../otel/src/helper/index.opentelemetry.ts | 3 - packages/otel/src/helper/resource.detector.ts | 27 - packages/otel/src/helper/trace.telemetry.ts | 137 - packages/otel/src/imports.ts | 30 - packages/otel/src/index.ts | 37 - packages/otel/src/lib/attrnames.types.ts | 105 - packages/otel/src/lib/component.ts | 624 ----- packages/otel/src/lib/config.ts | 92 - .../src/lib/decorator-handler-trace-base.ts | 81 - .../otel/src/lib/decorator.helper.async.ts | 83 - .../otel/src/lib/decorator.helper.base.ts | 70 - .../otel/src/lib/decorator.helper.sync.ts | 91 - .../trace-init.decorator-handler.ts | 85 - .../trace-init.helper.async.ts | 90 - .../lib/decorator.trace-init/trace-init.ts | 43 - .../trace-log.decorator-handler.ts | 73 - .../trace-log.helper.async.ts | 75 - .../trace-log.helper.sync.ts | 88 - .../src/lib/decorator.trace-log/trace-log.ts | 41 - .../trace.decorator-handler.ts | 75 - .../lib/decorator.trace/trace.helper.async.ts | 80 - .../lib/decorator.trace/trace.helper.sync.ts | 87 - .../otel/src/lib/decorator.trace/trace.ts | 28 - packages/otel/src/lib/http.types.ts | 112 - packages/otel/src/lib/index.ts | 59 - packages/otel/src/lib/reg-decorator.ts | 30 - packages/otel/src/lib/trace.helper.ts | 244 -- packages/otel/src/lib/trace.logger.ts | 211 -- .../lib/trace.service/index.trace.service.ts | 5 - .../lib/trace.service/trace.service.base.ts | 163 -- .../lib/trace.service/trace.service.span.ts | 220 -- .../src/lib/trace.service/trace.service.ts | 329 --- .../lib/trace.service/trace.service.types.ts | 58 - packages/otel/src/lib/types.ts | 280 -- packages/otel/src/lib/util.ts | 491 ---- .../middleware/grpc/helper.middleware.grpc.ts | 129 - .../middleware/grpc/index.middleware.grpc.ts | 5 - .../otel/src/middleware/grpc/status.grpc.ts | 152 -- .../grpc/trace-inner.middleware.grpc.ts | 57 - .../grpc/trace-outer.middleware.grpc.ts | 123 - .../middleware/http/helper.middleware.http.ts | 87 - .../middleware/http/index.middleware.http.ts | 4 - .../http/trace-inner.middleware.http.ts | 58 - .../http/trace-outer.middleware.http.ts | 95 - .../otel/src/middleware/index.middleware.ts | 4 - packages/otel/src/util/common.ts | 415 --- packages/otel/test/00.dummy.test.ts | 17 - packages/otel/test/01.index.test.ts | 32 - packages/otel/test/02.home.test.ts | 52 - packages/otel/test/15.error.test.ts | 38 - packages/otel/test/16.log.test.ts | 38 - packages/otel/test/17.route.test.ts | 36 - packages/otel/test/18.trace-service.test.ts | 125 - packages/otel/test/99.disable-trace.test.ts | 40 - packages/otel/test/api-test.ts | 50 - .../decorator/100.decorator.types.ts.test.ts | 22 - .../otel/test/decorator/11.traceid.test.ts | 82 - .../test/decorator/110.docorator-data.test.ts | 180 -- .../decorator/111.docorator-scope.test.ts | 106 - .../decorator/112.docorator-scope.test.ts | 130 - packages/otel/test/decorator/112.json | 638 ----- .../113.docorator-scope-auto.test.ts | 139 - .../otel/test/decorator/12.traceid2.test.ts | 107 - .../decorator/120.docorator-data-mix.test.ts | 183 -- .../otel/test/decorator/120.trace-log.test.ts | 84 - .../decorator/121.trace-log.error.test.ts | 93 - .../decorator/122.trace-singleton.test.ts | 93 - .../test/decorator/123.trace-cb-this.test.ts | 93 - .../124.trace-log.afterThrow.test.ts | 86 - .../test/decorator/125.trace-log-mix.test.ts | 84 - .../test/decorator/13.decorator_arg.test.ts | 121 - .../test/decorator/14.decorator_arg2.test.ts | 102 - .../otel/test/decorator/19.singleton.test.ts | 88 - packages/otel/test/domain/helloworld.ts | 36 - .../otel/test/fixtures/base-app/package.json | 12 - .../fixtures/base-app/src/configuration.ts | 94 - .../otel/test/fixtures/base-app/src/home.ts | 37 - .../src/provider/200.grpc.provider.ts | 57 - .../src/provider/200s.grpc.service.ts | 41 - .../src/trace.decorator/11.controller.ts | 34 - .../110a.decorator-data.controller.ts | 112 - .../111c.decorator-scope.controller.ts | 44 - .../112a.decorator-scope.controller.ts | 63 - .../113a.decorator-scope-auto.controller.ts | 115 - .../src/trace.decorator/12.controller.ts | 42 - .../120a.trace-log.controller.ts | 91 - .../120c.decorator-data-mix.controller.ts | 85 - .../121a.trace-log.error.controller.ts | 125 - .../122a.trace-singleton.controller.ts | 38 - .../122b.trace-singleton.service.ts | 94 - .../123a.trace-cb-this.controller.ts | 38 - .../123b.trace-cb-this.service.ts | 97 - .../124a.trace-log.afterThrow.controller.ts | 140 - .../125a.trace-log-mix.controller.ts | 136 - .../src/trace.decorator/13.controller.ts | 41 - .../src/trace.decorator/14.controller.ts | 39 - .../trace.decorator/17.route.controller.ts | 35 - .../src/trace.decorator/19.controller.ts | 31 - .../trace.decorator/19b.singleton.service.ts | 37 - .../src/trace.decorator/trace.controller.ts | 122 - .../src/trace.decorator/trace.service.ts | 79 - .../fixtures/base-app/src/types/api-test.ts | 3 - .../fixtures/base-app/src/types/domain.ts | 3 - .../test/fixtures/base-app/src/types/index.ts | 3 - .../fixtures/base-app/src/types/lib-index.ts | 3 - .../fixtures/base-app/src/types/lib-types.ts | 3 - .../base-app/src/types/root.config.ts | 3 - .../test/fixtures/base-app/src/types/util.ts | 3 - .../base-app/src/util/20a.util.controller.ts | 57 - .../base-app/src/util/21a.controller.ts | 69 - .../otel/test/fixtures/base-app/tsconfig.json | 19 - packages/otel/test/grpc/200.grpc.test.ts | 192 -- packages/otel/test/grpc/helloworld.proto | 22 - .../test/lib/31.isTraceScopeParamType.test.ts | 49 - packages/otel/test/prepare.mts | 33 - packages/otel/test/root.config.ts | 61 - packages/otel/test/setup.ts | 69 - packages/otel/test/tracing.js.example | 42 - packages/otel/test/tsconfig.json | 15 - packages/otel/test/util/20.util.test.ts | 39 - ...ddSpanEventWithIncomingRequestData.test.ts | 101 - .../22.retrieveTraceparentFromHeader.test.ts | 48 - .../23.retrieveTraceInfoFromRemote.test.ts | 30 - packages/otel/test/z/903.share.test.ts | 20 - packages/otel/tsconfig.json | 6 - 273 files changed, 3 insertions(+), 22541 deletions(-) delete mode 100644 packages/ali-oss/.editorconfig delete mode 100644 packages/ali-oss/CHANGELOG.md delete mode 100644 packages/ali-oss/LICENSE delete mode 100644 packages/ali-oss/README.md delete mode 100644 packages/ali-oss/bootstrap.js delete mode 100644 packages/ali-oss/package.json delete mode 100644 packages/ali-oss/src/app/default.controller.ts delete mode 100644 packages/ali-oss/src/app/default.types.ts delete mode 100644 packages/ali-oss/src/app/index.controller.ts delete mode 100644 packages/ali-oss/src/config/config.default.ts delete mode 100644 packages/ali-oss/src/config/config.local.ts delete mode 100644 packages/ali-oss/src/config/config.unittest.ts delete mode 100644 packages/ali-oss/src/configuration.ts delete mode 100644 packages/ali-oss/src/imports.ts delete mode 100644 packages/ali-oss/src/index.ts delete mode 100644 packages/ali-oss/src/lib/component.ts delete mode 100644 packages/ali-oss/src/lib/config.ts delete mode 100644 packages/ali-oss/src/lib/index.ts delete mode 100644 packages/ali-oss/src/lib/manager.ts delete mode 100644 packages/ali-oss/src/lib/source-manager.ts delete mode 100644 packages/ali-oss/src/lib/types.ts delete mode 100644 packages/ali-oss/test/00.dummy.test.ts delete mode 100644 packages/ali-oss/test/01.index.test.ts delete mode 100644 packages/ali-oss/test/02.home.test.ts delete mode 100644 packages/ali-oss/test/api-test.ts delete mode 100644 packages/ali-oss/test/component/11.mkdir.test.ts delete mode 100644 packages/ali-oss/test/component/12.upload.test.ts delete mode 100644 packages/ali-oss/test/component/14.createSymlink.test.ts delete mode 100644 packages/ali-oss/test/component/18.mv.test.ts delete mode 100644 packages/ali-oss/test/component/19.syncRemote.test.ts delete mode 100644 packages/ali-oss/test/component/20.syncLocal.test.ts delete mode 100644 packages/ali-oss/test/component/22.sign.test.ts delete mode 100644 packages/ali-oss/test/component/23.download.test.ts delete mode 100644 packages/ali-oss/test/component/30.rm.test.ts delete mode 100644 packages/ali-oss/test/files/.nycrc.json delete mode 100644 packages/ali-oss/test/files/1.txt delete mode 100644 packages/ali-oss/test/files/2.txt delete mode 100644 packages/ali-oss/test/files/subdir/.nycrc.json delete mode 100644 packages/ali-oss/test/files/subdir/1.txt delete mode 100644 packages/ali-oss/test/files/subdir/2.txt delete mode 100644 packages/ali-oss/test/files/subdir/tsconfig.json delete mode 100644 packages/ali-oss/test/files/tsconfig.json delete mode 100644 "packages/ali-oss/test/files/\350\201\224\351\200\232\342\202\254-&a'b^c=.json" delete mode 100644 packages/ali-oss/test/fixtures/base-app/package.json delete mode 100644 packages/ali-oss/test/fixtures/base-app/src/configuration.ts delete mode 100644 packages/ali-oss/test/fixtures/base-app/src/home.ts delete mode 100644 packages/ali-oss/test/fixtures/base-app/src/oss.controller.ts delete mode 100644 packages/ali-oss/test/fixtures/base-app/src/types/api-test.ts delete mode 100644 packages/ali-oss/test/fixtures/base-app/src/types/index.ts delete mode 100644 packages/ali-oss/test/fixtures/base-app/src/types/lib-index.ts delete mode 100644 packages/ali-oss/test/fixtures/base-app/src/types/lib-types.ts delete mode 100644 packages/ali-oss/test/fixtures/base-app/src/types/root.config.ts delete mode 100644 packages/ali-oss/test/fixtures/base-app/tsconfig.json delete mode 100644 packages/ali-oss/test/helper.ts delete mode 100644 packages/ali-oss/test/root.config.ts delete mode 100644 packages/ali-oss/test/setup.ts delete mode 100644 packages/ali-oss/test/source-manager/111.mkdir.test.ts delete mode 100644 packages/ali-oss/test/source-manager/115.stat.test.ts delete mode 100644 packages/ali-oss/test/tsconfig.json delete mode 100644 packages/ali-oss/tsconfig.json delete mode 100644 packages/demo/database/default/ddl/ci-config.sql delete mode 100644 packages/demo/database/default/ddl/tb_user.sql delete mode 100644 packages/demo/database/default/ddl/tb_user_insert.sql delete mode 100644 packages/demo/database/default/init.sh delete mode 100644 packages/demo/database/init-db.sh delete mode 100644 packages/jwt/.editorconfig delete mode 100644 packages/jwt/CHANGELOG.md delete mode 100644 packages/jwt/LICENSE delete mode 100644 packages/jwt/README.md delete mode 100644 packages/jwt/bootstrap.js delete mode 100644 packages/jwt/package.json delete mode 100644 packages/jwt/src/app/default.controller.ts delete mode 100644 packages/jwt/src/app/default.types.ts delete mode 100644 packages/jwt/src/app/index.controller.ts delete mode 100644 packages/jwt/src/config/config.default.ts delete mode 100644 packages/jwt/src/config/config.local.ts delete mode 100644 packages/jwt/src/config/config.unittest.ts delete mode 100644 packages/jwt/src/configuration.ts delete mode 100644 packages/jwt/src/imports.ts delete mode 100644 packages/jwt/src/index.ts delete mode 100644 packages/jwt/src/lib/component.ts delete mode 100644 packages/jwt/src/lib/config.ts delete mode 100644 packages/jwt/src/lib/decorator.public/index.decorator.ts delete mode 100644 packages/jwt/src/lib/decorator.public/public.decorator-handler.ts delete mode 100644 packages/jwt/src/lib/decorator.public/public.decorator.ts delete mode 100644 packages/jwt/src/lib/index.ts delete mode 100644 packages/jwt/src/lib/resolvers.ts delete mode 100644 packages/jwt/src/lib/types.ts delete mode 100644 packages/jwt/src/lib/util.ts delete mode 100644 packages/jwt/src/middleware/index.middleware.ts delete mode 100644 packages/jwt/src/middleware/jwt.middleware.ts delete mode 100644 packages/jwt/test/00.dummy.test.ts delete mode 100644 packages/jwt/test/01.index.test.ts delete mode 100644 packages/jwt/test/02.home.test.ts delete mode 100644 packages/jwt/test/api-test.ts delete mode 100644 packages/jwt/test/decorator/100.test.ts delete mode 100644 packages/jwt/test/fixtures/base-app/package.json delete mode 100644 packages/jwt/test/fixtures/base-app/src/100.controller.ts delete mode 100644 packages/jwt/test/fixtures/base-app/src/configuration.ts delete mode 100644 packages/jwt/test/fixtures/base-app/src/home.ts delete mode 100644 packages/jwt/test/fixtures/base-app/src/home2.ts delete mode 100644 packages/jwt/test/fixtures/base-app/src/types/api-test.ts delete mode 100644 packages/jwt/test/fixtures/base-app/src/types/index.ts delete mode 100644 packages/jwt/test/fixtures/base-app/src/types/lib-index.ts delete mode 100644 packages/jwt/test/fixtures/base-app/src/types/lib-types.ts delete mode 100644 packages/jwt/test/fixtures/base-app/src/types/root.config.ts delete mode 100644 packages/jwt/test/fixtures/base-app/tsconfig.json delete mode 100644 packages/jwt/test/jwt-component/decode.test.ts delete mode 100644 packages/jwt/test/jwt-component/sign.test.ts delete mode 100644 packages/jwt/test/jwt-component/verify.test.ts delete mode 100644 packages/jwt/test/middleware/helper.ts delete mode 100644 packages/jwt/test/middleware/with-token/jwt.middleware.passthough-func.test.ts delete mode 100644 packages/jwt/test/middleware/with-token/jwt.middleware.passthough-string.test.ts delete mode 100644 packages/jwt/test/middleware/with-token/jwt.middleware.passthough-true.test.ts delete mode 100644 packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-cookie.test.ts delete mode 100644 packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-header.test.ts delete mode 100644 packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-jwtState.test.ts delete mode 100644 packages/jwt/test/middleware/without-token/jwt.middleware.debug.test.ts delete mode 100644 packages/jwt/test/middleware/without-token/jwt.middleware.ignore-func.test.ts delete mode 100644 packages/jwt/test/middleware/without-token/jwt.middleware.ignore-regex.test.ts delete mode 100644 packages/jwt/test/middleware/without-token/jwt.middleware.ignore-string.test.ts delete mode 100644 packages/jwt/test/mock-data.ts delete mode 100644 packages/jwt/test/root.config.ts delete mode 100644 packages/jwt/test/setup.ts delete mode 100644 packages/jwt/test/tsconfig.json delete mode 100644 packages/jwt/test/util/resolver.test.ts delete mode 100644 packages/jwt/test/util/validatePayload.test.ts delete mode 100644 packages/jwt/test/util/validateSignSecret.test.ts delete mode 100644 packages/jwt/test/util/validateTokenString.test.ts delete mode 100644 packages/jwt/test/util/validateVerifySecret.test.ts delete mode 100644 packages/jwt/tsconfig.json delete mode 100644 packages/otel/.editorconfig delete mode 100644 packages/otel/.eslintrc.yml delete mode 100644 packages/otel/CHANGELOG.md delete mode 100644 packages/otel/LICENSE delete mode 100644 packages/otel/README.md delete mode 100644 packages/otel/README.zh-CN.md delete mode 100644 packages/otel/bootstrap.js delete mode 100644 packages/otel/img/trace-scope.png delete mode 100644 packages/otel/package.json delete mode 100644 packages/otel/src/app/default.controller.ts delete mode 100644 packages/otel/src/app/default.service.ts delete mode 100644 packages/otel/src/app/index.controller.ts delete mode 100644 packages/otel/src/config/config.default.ts delete mode 100644 packages/otel/src/config/config.local.ts delete mode 100644 packages/otel/src/config/config.unittest.ts delete mode 100644 packages/otel/src/configuration.ts delete mode 100644 packages/otel/src/helper/index.opentelemetry.ts delete mode 100644 packages/otel/src/helper/resource.detector.ts delete mode 100644 packages/otel/src/helper/trace.telemetry.ts delete mode 100644 packages/otel/src/imports.ts delete mode 100644 packages/otel/src/index.ts delete mode 100644 packages/otel/src/lib/attrnames.types.ts delete mode 100644 packages/otel/src/lib/component.ts delete mode 100644 packages/otel/src/lib/config.ts delete mode 100644 packages/otel/src/lib/decorator-handler-trace-base.ts delete mode 100644 packages/otel/src/lib/decorator.helper.async.ts delete mode 100644 packages/otel/src/lib/decorator.helper.base.ts delete mode 100644 packages/otel/src/lib/decorator.helper.sync.ts delete mode 100644 packages/otel/src/lib/decorator.trace-init/trace-init.decorator-handler.ts delete mode 100644 packages/otel/src/lib/decorator.trace-init/trace-init.helper.async.ts delete mode 100644 packages/otel/src/lib/decorator.trace-init/trace-init.ts delete mode 100644 packages/otel/src/lib/decorator.trace-log/trace-log.decorator-handler.ts delete mode 100644 packages/otel/src/lib/decorator.trace-log/trace-log.helper.async.ts delete mode 100644 packages/otel/src/lib/decorator.trace-log/trace-log.helper.sync.ts delete mode 100644 packages/otel/src/lib/decorator.trace-log/trace-log.ts delete mode 100644 packages/otel/src/lib/decorator.trace/trace.decorator-handler.ts delete mode 100644 packages/otel/src/lib/decorator.trace/trace.helper.async.ts delete mode 100644 packages/otel/src/lib/decorator.trace/trace.helper.sync.ts delete mode 100644 packages/otel/src/lib/decorator.trace/trace.ts delete mode 100644 packages/otel/src/lib/http.types.ts delete mode 100644 packages/otel/src/lib/index.ts delete mode 100644 packages/otel/src/lib/reg-decorator.ts delete mode 100644 packages/otel/src/lib/trace.helper.ts delete mode 100644 packages/otel/src/lib/trace.logger.ts delete mode 100644 packages/otel/src/lib/trace.service/index.trace.service.ts delete mode 100644 packages/otel/src/lib/trace.service/trace.service.base.ts delete mode 100644 packages/otel/src/lib/trace.service/trace.service.span.ts delete mode 100644 packages/otel/src/lib/trace.service/trace.service.ts delete mode 100644 packages/otel/src/lib/trace.service/trace.service.types.ts delete mode 100644 packages/otel/src/lib/types.ts delete mode 100644 packages/otel/src/lib/util.ts delete mode 100644 packages/otel/src/middleware/grpc/helper.middleware.grpc.ts delete mode 100644 packages/otel/src/middleware/grpc/index.middleware.grpc.ts delete mode 100644 packages/otel/src/middleware/grpc/status.grpc.ts delete mode 100644 packages/otel/src/middleware/grpc/trace-inner.middleware.grpc.ts delete mode 100644 packages/otel/src/middleware/grpc/trace-outer.middleware.grpc.ts delete mode 100644 packages/otel/src/middleware/http/helper.middleware.http.ts delete mode 100644 packages/otel/src/middleware/http/index.middleware.http.ts delete mode 100644 packages/otel/src/middleware/http/trace-inner.middleware.http.ts delete mode 100644 packages/otel/src/middleware/http/trace-outer.middleware.http.ts delete mode 100644 packages/otel/src/middleware/index.middleware.ts delete mode 100644 packages/otel/src/util/common.ts delete mode 100644 packages/otel/test/00.dummy.test.ts delete mode 100644 packages/otel/test/01.index.test.ts delete mode 100644 packages/otel/test/02.home.test.ts delete mode 100644 packages/otel/test/15.error.test.ts delete mode 100644 packages/otel/test/16.log.test.ts delete mode 100644 packages/otel/test/17.route.test.ts delete mode 100644 packages/otel/test/18.trace-service.test.ts delete mode 100644 packages/otel/test/99.disable-trace.test.ts delete mode 100644 packages/otel/test/api-test.ts delete mode 100644 packages/otel/test/decorator/100.decorator.types.ts.test.ts delete mode 100644 packages/otel/test/decorator/11.traceid.test.ts delete mode 100644 packages/otel/test/decorator/110.docorator-data.test.ts delete mode 100644 packages/otel/test/decorator/111.docorator-scope.test.ts delete mode 100644 packages/otel/test/decorator/112.docorator-scope.test.ts delete mode 100644 packages/otel/test/decorator/112.json delete mode 100644 packages/otel/test/decorator/113.docorator-scope-auto.test.ts delete mode 100644 packages/otel/test/decorator/12.traceid2.test.ts delete mode 100644 packages/otel/test/decorator/120.docorator-data-mix.test.ts delete mode 100644 packages/otel/test/decorator/120.trace-log.test.ts delete mode 100644 packages/otel/test/decorator/121.trace-log.error.test.ts delete mode 100644 packages/otel/test/decorator/122.trace-singleton.test.ts delete mode 100644 packages/otel/test/decorator/123.trace-cb-this.test.ts delete mode 100644 packages/otel/test/decorator/124.trace-log.afterThrow.test.ts delete mode 100644 packages/otel/test/decorator/125.trace-log-mix.test.ts delete mode 100644 packages/otel/test/decorator/13.decorator_arg.test.ts delete mode 100644 packages/otel/test/decorator/14.decorator_arg2.test.ts delete mode 100644 packages/otel/test/decorator/19.singleton.test.ts delete mode 100644 packages/otel/test/domain/helloworld.ts delete mode 100644 packages/otel/test/fixtures/base-app/package.json delete mode 100644 packages/otel/test/fixtures/base-app/src/configuration.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/home.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/provider/200.grpc.provider.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/provider/200s.grpc.service.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/11.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/110a.decorator-data.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/111c.decorator-scope.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/112a.decorator-scope.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/113a.decorator-scope-auto.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/12.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/120a.trace-log.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/120c.decorator-data-mix.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/121a.trace-log.error.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/122a.trace-singleton.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/122b.trace-singleton.service.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/123a.trace-cb-this.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/123b.trace-cb-this.service.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/124a.trace-log.afterThrow.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/125a.trace-log-mix.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/13.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/14.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/17.route.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/19.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/19b.singleton.service.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/trace.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/trace.decorator/trace.service.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/types/api-test.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/types/domain.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/types/index.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/types/lib-index.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/types/lib-types.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/types/root.config.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/types/util.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/util/20a.util.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/src/util/21a.controller.ts delete mode 100644 packages/otel/test/fixtures/base-app/tsconfig.json delete mode 100644 packages/otel/test/grpc/200.grpc.test.ts delete mode 100644 packages/otel/test/grpc/helloworld.proto delete mode 100644 packages/otel/test/lib/31.isTraceScopeParamType.test.ts delete mode 100644 packages/otel/test/prepare.mts delete mode 100644 packages/otel/test/root.config.ts delete mode 100644 packages/otel/test/setup.ts delete mode 100644 packages/otel/test/tracing.js.example delete mode 100644 packages/otel/test/tsconfig.json delete mode 100644 packages/otel/test/util/20.util.test.ts delete mode 100644 packages/otel/test/util/21.addSpanEventWithIncomingRequestData.test.ts delete mode 100644 packages/otel/test/util/22.retrieveTraceparentFromHeader.test.ts delete mode 100644 packages/otel/test/util/23.retrieveTraceInfoFromRemote.test.ts delete mode 100644 packages/otel/test/z/903.share.test.ts delete mode 100644 packages/otel/tsconfig.json diff --git a/.scripts/ci/ci-init-db.sh b/.scripts/ci/ci-init-db.sh index ceaec3b13..c65a585c5 100755 --- a/.scripts/ci/ci-init-db.sh +++ b/.scripts/ci/ci-init-db.sh @@ -9,9 +9,9 @@ export PGPASSWORD="$POSTGRES_PWD" psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U$POSTGRES_USER -d $POSTGRES_DB -bq -f $cwd/.scripts/ci/init-pre.sql echo -e "\n" -SQL_DIR="$cwd/packages/demo/database/" -cd "$SQL_DIR" -. ./init-db.sh +# SQL_DIR="$cwd/packages/demo/database/" +# cd "$SQL_DIR" +# . ./init-db.sh echo -e "\nInit post" export PGPASSWORD="$POSTGRES_PWD" diff --git a/packages/ali-oss/.editorconfig b/packages/ali-oss/.editorconfig deleted file mode 100644 index 731bcab2c..000000000 --- a/packages/ali-oss/.editorconfig +++ /dev/null @@ -1,16 +0,0 @@ -# EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs -# Editor configuration, see http://editorconfig.org - -root = true - -[*] -charset = utf-8 -end_of_line = lf -indent_style = space -indent_size = 2 -insert_final_newline = true -trim_trailing_whitespace = true - -[*.md] -max_line_length = off -trim_trailing_whitespace = false diff --git a/packages/ali-oss/CHANGELOG.md b/packages/ali-oss/CHANGELOG.md deleted file mode 100644 index 7b2b7a519..000000000 --- a/packages/ali-oss/CHANGELOG.md +++ /dev/null @@ -1,2279 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. -See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. - -# [41.0.0](https://github.com/waitingsong/midway-components/compare/v40.1.1...v41.0.0) (2024-11-21) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [40.1.1](https://github.com/waitingsong/midway-components/compare/v40.1.0...v40.1.1) (2024-11-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [40.1.0](https://github.com/waitingsong/midway-components/compare/v40.0.0...v40.1.0) (2024-11-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [40.0.0](https://github.com/waitingsong/midway-components/compare/v39.3.0...v40.0.0) (2024-11-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [39.3.0](https://github.com/waitingsong/midway-components/compare/v39.2.0...v39.3.0) (2024-11-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [39.2.0](https://github.com/waitingsong/midway-components/compare/v39.1.2...v39.2.0) (2024-11-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [39.1.2](https://github.com/waitingsong/midway-components/compare/v39.1.1...v39.1.2) (2024-10-31) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [39.1.1](https://github.com/waitingsong/midway-components/compare/v39.1.0...v39.1.1) (2024-10-30) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [39.1.0](https://github.com/waitingsong/midway-components/compare/v39.0.2...v39.1.0) (2024-10-30) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [39.0.2](https://github.com/waitingsong/midway-components/compare/v39.0.1...v39.0.2) (2024-10-29) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [39.0.1](https://github.com/waitingsong/midway-components/compare/v39.0.0...v39.0.1) (2024-10-29) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [39.0.0](https://github.com/waitingsong/midway-components/compare/v38.4.0...v39.0.0) (2024-10-29) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [38.4.0](https://github.com/waitingsong/midway-components/compare/v38.3.0...v38.4.0) (2024-10-28) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [38.3.0](https://github.com/waitingsong/midway-components/compare/v38.2.3...v38.3.0) (2024-10-28) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [38.2.3](https://github.com/waitingsong/midway-components/compare/v38.2.2...v38.2.3) (2024-10-25) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [38.2.2](https://github.com/waitingsong/midway-components/compare/v38.2.1...v38.2.2) (2024-10-05) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [38.2.1](https://github.com/waitingsong/midway-components/compare/v38.2.0...v38.2.1) (2024-09-15) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [38.2.0](https://github.com/waitingsong/midway-components/compare/v38.1.0...v38.2.0) (2024-09-15) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [38.1.0](https://github.com/waitingsong/midway-components/compare/v38.0.0...v38.1.0) (2024-09-15) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [38.0.0](https://github.com/waitingsong/midway-components/compare/v37.4.1...v38.0.0) (2024-09-14) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [37.4.1](https://github.com/waitingsong/midway-components/compare/v37.4.0...v37.4.1) (2024-09-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [37.4.0](https://github.com/waitingsong/midway-components/compare/v37.3.0...v37.4.0) (2024-09-07) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [37.3.0](https://github.com/waitingsong/midway-components/compare/v37.2.4...v37.3.0) (2024-09-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [37.2.4](https://github.com/waitingsong/midway-components/compare/v37.2.3...v37.2.4) (2024-09-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [37.2.3](https://github.com/waitingsong/midway-components/compare/v37.2.2...v37.2.3) (2024-09-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [37.2.2](https://github.com/waitingsong/midway-components/compare/v37.2.1...v37.2.2) (2024-09-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [37.2.1](https://github.com/waitingsong/midway-components/compare/v37.2.0...v37.2.1) (2024-08-29) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [37.2.0](https://github.com/waitingsong/midway-components/compare/v37.1.0...v37.2.0) (2024-08-17) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [37.1.0](https://github.com/waitingsong/midway-components/compare/v37.0.0...v37.1.0) (2024-08-16) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [37.0.0](https://github.com/waitingsong/midway-components/compare/v36.1.3...v37.0.0) (2024-08-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [36.1.3](https://github.com/waitingsong/midway-components/compare/v36.1.2...v36.1.3) (2024-08-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [36.1.2](https://github.com/waitingsong/midway-components/compare/v36.1.1...v36.1.2) (2024-08-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [36.1.1](https://github.com/waitingsong/midway-components/compare/v36.1.0...v36.1.1) (2024-08-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [36.1.0](https://github.com/waitingsong/midway-components/compare/v36.0.0...v36.1.0) (2024-08-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [36.0.0](https://github.com/waitingsong/midway-components/compare/v35.2.1...v36.0.0) (2024-08-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [35.2.1](https://github.com/waitingsong/midway-components/compare/v35.2.0...v35.2.1) (2024-08-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [35.2.0](https://github.com/waitingsong/midway-components/compare/v35.1.0...v35.2.0) (2024-08-01) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [35.1.0](https://github.com/waitingsong/midway-components/compare/v35.0.1...v35.1.0) (2024-08-01) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [35.0.1](https://github.com/waitingsong/midway-components/compare/v35.0.0...v35.0.1) (2024-07-30) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [35.0.0](https://github.com/waitingsong/midway-components/compare/v34.0.1...v35.0.0) (2024-07-30) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [34.0.1](https://github.com/waitingsong/midway-components/compare/v34.0.0...v34.0.1) (2024-07-30) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [34.0.0](https://github.com/waitingsong/midway-components/compare/v33.0.0...v34.0.0) (2024-07-30) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [33.0.0](https://github.com/waitingsong/midway-components/compare/v32.0.0...v33.0.0) (2024-07-28) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [32.0.0](https://github.com/waitingsong/midway-components/compare/v31.0.0...v32.0.0) (2024-07-24) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [31.0.0](https://github.com/waitingsong/midway-components/compare/v30.21.0...v31.0.0) (2024-07-22) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.21.0](https://github.com/waitingsong/midway-components/compare/v30.20.0...v30.21.0) (2024-07-22) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.20.0](https://github.com/waitingsong/midway-components/compare/v30.19.0...v30.20.0) (2024-07-15) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.19.0](https://github.com/waitingsong/midway-components/compare/v30.18.0...v30.19.0) (2024-07-14) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.18.0](https://github.com/waitingsong/midway-components/compare/v30.17.1...v30.18.0) (2024-07-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.17.1](https://github.com/waitingsong/midway-components/compare/v30.17.0...v30.17.1) (2024-07-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.17.0](https://github.com/waitingsong/midway-components/compare/v30.16.1...v30.17.0) (2024-07-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.16.1](https://github.com/waitingsong/midway-components/compare/v30.16.0...v30.16.1) (2024-07-05) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.16.0](https://github.com/waitingsong/midway-components/compare/v30.15.2...v30.16.0) (2024-07-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.15.2](https://github.com/waitingsong/midway-components/compare/v30.15.1...v30.15.2) (2024-07-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.15.1](https://github.com/waitingsong/midway-components/compare/v30.15.0...v30.15.1) (2024-07-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.15.0](https://github.com/waitingsong/midway-components/compare/v30.14.0...v30.15.0) (2024-07-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.14.0](https://github.com/waitingsong/midway-components/compare/v30.13.0...v30.14.0) (2024-06-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.13.0](https://github.com/waitingsong/midway-components/compare/v30.12.1...v30.13.0) (2024-06-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.12.1](https://github.com/waitingsong/midway-components/compare/v30.12.0...v30.12.1) (2024-06-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.12.0](https://github.com/waitingsong/midway-components/compare/v30.11.2...v30.12.0) (2024-06-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.11.2](https://github.com/waitingsong/midway-components/compare/v30.11.1...v30.11.2) (2024-06-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.11.1](https://github.com/waitingsong/midway-components/compare/v30.11.0...v30.11.1) (2024-06-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.11.0](https://github.com/waitingsong/midway-components/compare/v30.10.2...v30.11.0) (2024-06-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.10.2](https://github.com/waitingsong/midway-components/compare/v30.10.1...v30.10.2) (2024-06-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.10.1](https://github.com/waitingsong/midway-components/compare/v30.10.0...v30.10.1) (2024-06-09) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.10.0](https://github.com/waitingsong/midway-components/compare/v30.9.1...v30.10.0) (2024-06-09) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.9.1](https://github.com/waitingsong/midway-components/compare/v30.9.0...v30.9.1) (2024-06-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.9.0](https://github.com/waitingsong/midway-components/compare/v30.8.0...v30.9.0) (2024-06-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.8.0](https://github.com/waitingsong/midway-components/compare/v30.7.2...v30.8.0) (2024-06-07) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.7.2](https://github.com/waitingsong/midway-components/compare/v30.7.1...v30.7.2) (2024-06-07) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.7.1](https://github.com/waitingsong/midway-components/compare/v30.7.0...v30.7.1) (2024-06-07) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.7.0](https://github.com/waitingsong/midway-components/compare/v30.6.1...v30.7.0) (2024-06-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.6.1](https://github.com/waitingsong/midway-components/compare/v30.6.0...v30.6.1) (2024-06-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.6.0](https://github.com/waitingsong/midway-components/compare/v30.5.0...v30.6.0) (2024-06-05) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.5.0](https://github.com/waitingsong/midway-components/compare/v30.4.0...v30.5.0) (2024-06-05) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.4.0](https://github.com/waitingsong/midway-components/compare/v30.3.0...v30.4.0) (2024-06-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.3.0](https://github.com/waitingsong/midway-components/compare/v30.2.0...v30.3.0) (2024-06-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.2.0](https://github.com/waitingsong/midway-components/compare/v30.1.1...v30.2.0) (2024-06-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [30.1.1](https://github.com/waitingsong/midway-components/compare/v30.1.0...v30.1.1) (2024-06-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.1.0](https://github.com/waitingsong/midway-components/compare/v30.0.0...v30.1.0) (2024-06-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [30.0.0](https://github.com/waitingsong/midway-components/compare/v29.3.1...v30.0.0) (2024-06-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [29.3.1](https://github.com/waitingsong/midway-components/compare/v29.3.0...v29.3.1) (2024-05-31) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [29.3.0](https://github.com/waitingsong/midway-components/compare/v29.2.0...v29.3.0) (2024-05-31) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [29.2.0](https://github.com/waitingsong/midway-components/compare/v29.1.0...v29.2.0) (2024-05-30) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [29.1.0](https://github.com/waitingsong/midway-components/compare/v29.0.1...v29.1.0) (2024-05-29) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [29.0.1](https://github.com/waitingsong/midway-components/compare/v29.0.0...v29.0.1) (2024-05-28) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [29.0.0](https://github.com/waitingsong/midway-components/compare/v28.2.0...v29.0.0) (2024-05-27) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [28.2.0](https://github.com/waitingsong/midway-components/compare/v28.1.1...v28.2.0) (2024-05-24) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [28.1.1](https://github.com/waitingsong/midway-components/compare/v28.1.0...v28.1.1) (2024-05-24) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [28.1.0](https://github.com/waitingsong/midway-components/compare/v28.0.0...v28.1.0) (2024-05-23) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [28.0.0](https://github.com/waitingsong/midway-components/compare/v27.0.1...v28.0.0) (2024-05-23) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [27.0.1](https://github.com/waitingsong/midway-components/compare/v27.0.0...v27.0.1) (2024-05-22) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [27.0.0](https://github.com/waitingsong/midway-components/compare/v26.5.3...v27.0.0) (2024-05-21) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [26.5.3](https://github.com/waitingsong/midway-components/compare/v26.5.2...v26.5.3) (2024-05-21) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [26.5.2](https://github.com/waitingsong/midway-components/compare/v26.5.1...v26.5.2) (2024-05-09) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [26.5.1](https://github.com/waitingsong/midway-components/compare/v26.5.0...v26.5.1) (2024-04-25) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [26.5.0](https://github.com/waitingsong/midway-components/compare/v26.4.0...v26.5.0) (2024-04-24) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [26.4.0](https://github.com/waitingsong/midway-components/compare/v26.3.2...v26.4.0) (2024-04-24) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [26.3.2](https://github.com/waitingsong/midway-components/compare/v26.3.1...v26.3.2) (2024-04-24) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [26.3.1](https://github.com/waitingsong/midway-components/compare/v26.3.0...v26.3.1) (2024-04-23) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [26.3.0](https://github.com/waitingsong/midway-components/compare/v26.2.1...v26.3.0) (2024-04-23) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [26.2.0](https://github.com/waitingsong/midway-components/compare/v26.1.0...v26.2.0) (2024-04-22) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [26.1.0](https://github.com/waitingsong/midway-components/compare/v26.0.2...v26.1.0) (2024-04-22) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [26.0.2](https://github.com/waitingsong/midway-components/compare/v26.0.1...v26.0.2) (2024-04-22) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [26.0.0](https://github.com/waitingsong/midway-components/compare/v25.2.3...v26.0.0) (2024-04-21) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [25.2.3](https://github.com/waitingsong/midway-components/compare/v25.2.2...v25.2.3) (2024-04-14) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [25.2.2](https://github.com/waitingsong/midway-components/compare/v25.2.1...v25.2.2) (2024-04-09) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [25.2.1](https://github.com/waitingsong/midway-components/compare/v25.2.0...v25.2.1) (2024-04-09) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [25.2.0](https://github.com/waitingsong/midway-components/compare/v25.1.0...v25.2.0) (2024-04-09) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [25.1.0](https://github.com/waitingsong/midway-components/compare/v25.0.2...v25.1.0) (2024-04-09) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [25.0.2](https://github.com/waitingsong/midway-components/compare/v25.0.1...v25.0.2) (2024-04-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [25.0.1](https://github.com/waitingsong/midway-components/compare/v25.0.0...v25.0.1) (2024-04-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [25.0.0](https://github.com/waitingsong/midway-components/compare/v24.2.4...v25.0.0) (2024-04-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [24.2.4](https://github.com/waitingsong/midway-components/compare/v24.2.3...v24.2.4) (2024-04-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [24.2.3](https://github.com/waitingsong/midway-components/compare/v24.2.2...v24.2.3) (2024-04-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [24.2.2](https://github.com/waitingsong/midway-components/compare/v24.2.1...v24.2.2) (2024-04-07) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [24.2.1](https://github.com/waitingsong/midway-components/compare/v24.2.0...v24.2.1) (2024-04-05) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [24.2.0](https://github.com/waitingsong/midway-components/compare/v24.1.0...v24.2.0) (2024-04-05) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [24.1.0](https://github.com/waitingsong/midway-components/compare/v24.0.0...v24.1.0) (2024-04-05) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [24.0.0](https://github.com/waitingsong/midway-components/compare/v23.2.0...v24.0.0) (2024-04-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [23.1.0](https://github.com/waitingsong/midway-components/compare/v23.0.0...v23.1.0) (2024-04-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [23.0.0](https://github.com/waitingsong/midway-components/compare/v22.1.2...v23.0.0) (2024-03-27) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [22.1.2](https://github.com/waitingsong/midway-components/compare/v22.1.1...v22.1.2) (2024-03-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [22.1.0](https://github.com/waitingsong/midway-components/compare/v22.0.1...v22.1.0) (2024-03-05) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [22.0.1](https://github.com/waitingsong/midway-components/compare/v22.0.0...v22.0.1) (2024-02-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [22.0.0](https://github.com/waitingsong/midway-components/compare/v21.1.0...v22.0.0) (2024-02-25) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [21.0.0](https://github.com/waitingsong/midway-components/compare/v20.12.0...v21.0.0) (2024-02-25) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [20.12.0](https://github.com/waitingsong/midway-components/compare/v20.11.1...v20.12.0) (2024-02-25) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [20.11.1](https://github.com/waitingsong/midway-components/compare/v20.11.0...v20.11.1) (2024-02-22) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [20.11.0](https://github.com/waitingsong/midway-components/compare/v20.10.1...v20.11.0) (2024-02-22) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [20.10.1](https://github.com/waitingsong/midway-components/compare/v20.10.0...v20.10.1) (2024-02-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [20.10.0](https://github.com/waitingsong/midway-components/compare/v20.9.0...v20.10.0) (2024-02-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [20.9.0](https://github.com/waitingsong/midway-components/compare/v20.8.1...v20.9.0) (2024-01-27) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [20.8.0](https://github.com/waitingsong/midway-components/compare/v20.7.0...v20.8.0) (2024-01-26) - - -### Features - -* deleteRouter if enableDefaultRoute false ([bc4027e](https://github.com/waitingsong/midway-components/commit/bc4027ed6c4233ee906dee9bae97986ff9f5e1c2)) - - - - - -# [20.7.0](https://github.com/waitingsong/midway-components/compare/v20.6.0...v20.7.0) (2024-01-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [20.6.0](https://github.com/waitingsong/midway-components/compare/v20.5.0...v20.6.0) (2024-01-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [20.5.0](https://github.com/waitingsong/midway-components/compare/v20.4.0...v20.5.0) (2024-01-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [20.3.0](https://github.com/waitingsong/midway-components/compare/v20.2.0...v20.3.0) (2024-01-25) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [20.0.0](https://github.com/waitingsong/midway-components/compare/v19.2.5...v20.0.0) (2024-01-21) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [19.2.1](https://github.com/waitingsong/midway-components/compare/v19.2.0...v19.2.1) (2023-09-19) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [19.2.0](https://github.com/waitingsong/midway-components/compare/v19.1.1...v19.2.0) (2023-09-18) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [19.1.1](https://github.com/waitingsong/midway-components/compare/v19.1.0...v19.1.1) (2023-09-18) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [19.1.0](https://github.com/waitingsong/midway-components/compare/v19.0.3...v19.1.0) (2023-09-13) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [19.0.3](https://github.com/waitingsong/midway-components/compare/v19.0.2...v19.0.3) (2023-09-13) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [19.0.0](https://github.com/waitingsong/midway-components/compare/v15.0.0...v19.0.0) (2023-09-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# 15.0.0 (2023-09-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.3.5](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.3.4...@mwcp/ali-oss@14.3.5) (2023-09-06) - - -### Bug Fixes - -* MidwayConfig extension optional ([1ec4c58](https://github.com/waitingsong/midway-components/commit/1ec4c5885f5d59a750d7658c1cc902fa56624705)) - - - - - -## [14.3.4](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.3.3...@mwcp/ali-oss@14.3.4) (2023-08-29) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.3.3](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.3.2...@mwcp/ali-oss@14.3.3) (2023-08-25) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.3.2](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.3.1...@mwcp/ali-oss@14.3.2) (2023-08-21) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.3.1](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.3.0...@mwcp/ali-oss@14.3.1) (2023-08-18) - - -### Bug Fixes - -* bump deps version ([0623719](https://github.com/waitingsong/midway-components/commit/0623719223c7ea7cd801ef4b86e3b51af96a5f94)) - - - - - -# [14.3.0](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.2.0...@mwcp/ali-oss@14.3.0) (2023-08-16) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [14.2.0](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.1.0...@mwcp/ali-oss@14.2.0) (2023-08-01) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# 14.1.0 (2023-07-07) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 14.0.19 (2023-06-16) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 14.0.18 (2023-05-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.17](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.16...@mwcp/ali-oss@14.0.17) (2023-05-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.16](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.15...@mwcp/ali-oss@14.0.16) (2023-05-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 14.0.15 (2023-05-25) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.14](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.13...@mwcp/ali-oss@14.0.14) (2023-05-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.13](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.12...@mwcp/ali-oss@14.0.13) (2023-05-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.12](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.11...@mwcp/ali-oss@14.0.12) (2023-05-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.11](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.10...@mwcp/ali-oss@14.0.11) (2023-05-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.10](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.9...@mwcp/ali-oss@14.0.10) (2023-05-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 14.0.9 (2023-05-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 14.0.8 (2023-04-27) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.7](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.6...@mwcp/ali-oss@14.0.7) (2023-04-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.6](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.5...@mwcp/ali-oss@14.0.6) (2023-04-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.5](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.4...@mwcp/ali-oss@14.0.5) (2023-04-26) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 14.0.4 (2023-04-25) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 14.0.3 (2023-04-23) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 14.0.2 (2023-04-23) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [14.0.1](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@14.0.0...@mwcp/ali-oss@14.0.1) (2023-04-23) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [14.0.0](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@13.0.1...@mwcp/ali-oss@14.0.0) (2023-04-23) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 13.0.1 (2023-04-14) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [13.0.0](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@12.0.1...@mwcp/ali-oss@13.0.0) (2023-04-13) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 12.0.1 (2023-04-13) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [12.0.0](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@11.0.9...@mwcp/ali-oss@12.0.0) (2023-04-13) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [11.0.9](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@11.0.8...@mwcp/ali-oss@11.0.9) (2023-04-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [11.0.8](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@11.0.7...@mwcp/ali-oss@11.0.8) (2023-04-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [11.0.7](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@11.0.6...@mwcp/ali-oss@11.0.7) (2023-04-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [11.0.6](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@11.0.5...@mwcp/ali-oss@11.0.6) (2023-04-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [11.0.5](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@11.0.4...@mwcp/ali-oss@11.0.5) (2023-04-04) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 11.0.4 (2023-04-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [11.0.3](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@11.0.2...@mwcp/ali-oss@11.0.3) (2023-04-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [11.0.2](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@11.0.1...@mwcp/ali-oss@11.0.2) (2023-03-31) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [11.0.1](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@11.0.0...@mwcp/ali-oss@11.0.1) (2023-03-31) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [11.0.0](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@10.0.0...@mwcp/ali-oss@11.0.0) (2023-03-30) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [10.0.0](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@9.0.3...@mwcp/ali-oss@10.0.0) (2023-03-29) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [9.0.3](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@9.0.2...@mwcp/ali-oss@9.0.3) (2023-03-28) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [9.0.2](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@9.0.1...@mwcp/ali-oss@9.0.2) (2023-03-27) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [9.0.1](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@9.0.0...@mwcp/ali-oss@9.0.1) (2023-03-27) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# 9.0.0 (2023-03-21) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [8.1.3](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.1.2...@mwcp/ali-oss@8.1.3) (2023-02-20) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 8.1.2 (2023-02-20) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [8.1.1](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.1.0...@mwcp/ali-oss@8.1.1) (2023-02-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# [8.1.0](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.0.8...@mwcp/ali-oss@8.1.0) (2023-02-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [8.0.8](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.0.7...@mwcp/ali-oss@8.0.8) (2023-01-31) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [8.0.7](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.0.6...@mwcp/ali-oss@8.0.7) (2023-01-18) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [8.0.6](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.0.5...@mwcp/ali-oss@8.0.6) (2023-01-18) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [8.0.5](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.0.4...@mwcp/ali-oss@8.0.5) (2023-01-18) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 8.0.4 (2023-01-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [8.0.3](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.0.2...@mwcp/ali-oss@8.0.3) (2023-01-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [8.0.2](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.0.1...@mwcp/ali-oss@8.0.2) (2023-01-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [8.0.1](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@8.0.0...@mwcp/ali-oss@8.0.1) (2023-01-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# 8.0.0 (2023-01-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.1.1 (2023-01-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# 7.1.0 (2022-12-27) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.35 (2022-12-14) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.34 (2022-12-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.33 (2022-12-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.32](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.31...@mwcp/ali-oss@7.0.32) (2022-12-06) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.31 (2022-12-05) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.30](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.29...@mwcp/ali-oss@7.0.30) (2022-12-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.29 (2022-11-24) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.28](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.27...@mwcp/ali-oss@7.0.28) (2022-11-14) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.27](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.26...@mwcp/ali-oss@7.0.27) (2022-11-14) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.26](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.25...@mwcp/ali-oss@7.0.26) (2022-11-13) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.25](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.24...@mwcp/ali-oss@7.0.25) (2022-11-13) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.24](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.23...@mwcp/ali-oss@7.0.24) (2022-11-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.23](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.22...@mwcp/ali-oss@7.0.23) (2022-11-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.22](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.21...@mwcp/ali-oss@7.0.22) (2022-11-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.21](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.20...@mwcp/ali-oss@7.0.21) (2022-11-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.20](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.19...@mwcp/ali-oss@7.0.20) (2022-11-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.19](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.18...@mwcp/ali-oss@7.0.19) (2022-11-09) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.18](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.17...@mwcp/ali-oss@7.0.18) (2022-11-09) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.17](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.16...@mwcp/ali-oss@7.0.17) (2022-11-08) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.16](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.15...@mwcp/ali-oss@7.0.16) (2022-11-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.15](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.14...@mwcp/ali-oss@7.0.15) (2022-11-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.14 (2022-11-03) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.13 (2022-11-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.12 (2022-11-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.11 (2022-11-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.10 (2022-10-18) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.9 (2022-10-17) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.8](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.7...@mwcp/ali-oss@7.0.8) (2022-10-15) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.7 (2022-10-14) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.6](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.5...@mwcp/ali-oss@7.0.6) (2022-10-14) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.5 (2022-10-13) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.4](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.3...@mwcp/ali-oss@7.0.4) (2022-10-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.3 (2022-10-12) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 7.0.2 (2022-10-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [7.0.1](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@7.0.0...@mwcp/ali-oss@7.0.1) (2022-10-11) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# 7.0.0 (2022-10-10) - - -### Features - -* **ali-oss:** use OpenTelemetry instead of jaeger client ([74ac7be](https://github.com/waitingsong/midway-components/commit/74ac7be10bd4707b6b0733ab93ee06558e76d242)) - - - - - -## 6.0.4 (2022-10-10) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 6.0.3 (2022-09-30) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## 6.0.2 (2022-09-29) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [6.0.1](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@6.0.0...@mwcp/ali-oss@6.0.1) (2022-09-19) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# 6.0.0 (2022-09-05) - - -### Features - -* **ali-oss:** sync upstream ([de6ca4d](https://github.com/waitingsong/midway-components/commit/de6ca4d786f7c78abfd508af26959b111ef48f10)) - - - - - -## [5.1.2](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@5.1.1...@mwcp/ali-oss@5.1.2) (2022-09-02) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -## [5.1.1](https://github.com/waitingsong/midway-components/compare/@mwcp/ali-oss@5.1.0...@mwcp/ali-oss@5.1.1) (2022-08-31) - -**Note:** Version bump only for package @mwcp/ali-oss - - - - - -# 5.1.0 (2022-08-31) - - -### Features - -* **ali-oss:** use new npm scope "[@mwcp](https://github.com/mwcp)" ([323943f](https://github.com/waitingsong/midway-components/commit/323943f05d6a32ab5e37fcc7e5eaa620f1b4ce8f)) - - - - - -## 5.0.4 (2022-08-30) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## [5.0.3](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@5.0.2...@mw-components/ali-oss@5.0.3) (2022-08-24) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## 5.0.2 (2022-08-24) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## 5.0.1 (2022-08-23) - - -### Bug Fixes - -* **ali-oss:** MidwayConfig mixin ([e910462](https://github.com/waitingsong/midway-components/commit/e910462f8b83ef3911ffddfbcd9e9c98249a9dc2)) - - - - - -# [5.0.0](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@4.2.1...@mw-components/ali-oss@5.0.0) (2022-08-21) - - -### Features - -* **ali-oss:** breaking changes variable name and type name ([e08af65](https://github.com/waitingsong/midway-components/commit/e08af65d0aac171117e5a60864de99313af4ee36)) - - - - - -## [4.2.1](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@4.2.0...@mw-components/ali-oss@4.2.1) (2022-08-21) - - -### Bug Fixes - -* **ali-oss:** type of param of download() ([9981b54](https://github.com/waitingsong/midway-components/commit/9981b541500cc9db7f9aa9986adf33d2126cc163)) - - - - - -# 4.2.0 (2022-08-21) - - -### Features - -* **ali-oss:** download() ([f19f7b9](https://github.com/waitingsong/midway-components/commit/f19f7b963ed0c5a47c0d63ad137bb0446cb3b0fe)) - - - - - -# [4.1.0](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@4.0.0...@mw-components/ali-oss@4.1.0) (2022-08-21) - - -### Features - -* **ali-oss:** bump deps version ([174f9b8](https://github.com/waitingsong/midway-components/commit/174f9b881d3265ad48dab01b7e268173884f2a1d)) - - - - - -# [4.0.0](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@3.0.0...@mw-components/ali-oss@4.0.0) (2022-08-19) - - -### Features - -* **oss:** refactor ([e41953b](https://github.com/waitingsong/midway-components/commit/e41953b105ff6a30d3167d4d008efa84ec41fc31)) - - - - - -# 3.0.0 (2022-08-19) - - -### Features - -* **oss:** refactor for midway.js data-source-manager ([450268c](https://github.com/waitingsong/midway-components/commit/450268c603fe17a85c2cc343a316fb12035cf324)) -* **oss:** tracer ([35bfb14](https://github.com/waitingsong/midway-components/commit/35bfb145679ef1aa37a190afae1c0147ec18ec0a)) - - - - - -## 2.3.7 (2022-08-12) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## [2.3.6](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@2.3.5...@mw-components/ali-oss@2.3.6) (2022-08-05) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## 2.3.5 (2022-08-05) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## [2.3.4](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@2.3.3...@mw-components/ali-oss@2.3.4) (2022-07-13) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## [2.3.3](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@2.3.2...@mw-components/ali-oss@2.3.3) (2022-07-09) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## [2.3.2](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@2.3.1...@mw-components/ali-oss@2.3.2) (2022-07-07) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## [2.3.1](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@2.3.0...@mw-components/ali-oss@2.3.1) (2022-07-05) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -# 2.3.0 (2022-06-10) - - -### Features - -* **ali-oss:** update options type of SyncLocal() and SyncRemote() ([3c4f29c](https://github.com/waitingsong/midway-components/commit/3c4f29c5aeb5c0fdd161c126eecf91ae290a9bb2)) - - - - - -## [2.2.2](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@2.2.1...@mw-components/ali-oss@2.2.2) (2022-06-08) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## [2.2.1](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@2.2.0...@mw-components/ali-oss@2.2.1) (2022-06-06) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -# [2.2.0](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@2.1.0...@mw-components/ali-oss@2.2.0) (2022-06-06) - - -### Features - -* **ali-oss:** syncLocal() ([12d015a](https://github.com/waitingsong/midway-components/commit/12d015a258546c3a2b4a2a9e7a9e65f3557437ad)) - - - - - -# [2.1.0](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@2.0.0...@mw-components/ali-oss@2.1.0) (2022-06-06) - - -### Features - -* **ali-oss:** syncRemote() ([c0aafde](https://github.com/waitingsong/midway-components/commit/c0aafde13c600aa6d7dc214b13d54ae8679d9570)) - - - - - -# [2.0.0](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@1.1.2...@mw-components/ali-oss@2.0.0) (2022-06-06) - - -### Features - -* **ali-oss:** change parameter options optional of rm(), sign() ([d6af271](https://github.com/waitingsong/midway-components/commit/d6af271deaa0f02e81702313d678c061b75728fd)) - - - - - -## [1.1.2](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@1.1.1...@mw-components/ali-oss@1.1.2) (2022-05-31) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -## [1.1.1](https://github.com/waitingsong/midway-components/compare/@mw-components/ali-oss@1.1.0...@mw-components/ali-oss@1.1.1) (2022-05-30) - -**Note:** Version bump only for package @mw-components/ali-oss - - - - - -# 1.1.0 (2022-05-30) - - -### Features - -* **ali-oss:** implementation ([d35c3cf](https://github.com/waitingsong/midway-components/commit/d35c3cf74b3f9ad44bd70fa877c63aa692ad5fd3)) diff --git a/packages/ali-oss/LICENSE b/packages/ali-oss/LICENSE deleted file mode 100644 index 050e16851..000000000 --- a/packages/ali-oss/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -The MIT License (MIT) - -Copyright (c) waiting - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/ali-oss/README.md b/packages/ali-oss/README.md deleted file mode 100644 index 3a004f638..000000000 --- a/packages/ali-oss/README.md +++ /dev/null @@ -1,123 +0,0 @@ -# [@mwcp/ali-oss](https://www.npmjs.com/package/@mwcp/ali-oss) - -Ali Oss ossutil client component for midway.js - -[![GitHub tag](https://img.shields.io/github/tag/waitingsong/midway-components)]() -[![Version](https://img.shields.io/npm/v/@mwcp/cache.svg)](https://www.npmjs.com/package/midway-components) -[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) -[![](https://img.shields.io/badge/lang-TypeScript-blue.svg)]() -[![ci](https://github.com/waitingsong/midway-components/actions/workflows/nodejs.yml/badge.svg -)](https://github.com/waitingsong/midway-components/actions) -[![codecov](https://codecov.io/gh/waitingsong/midway-components/branch/main/graph/badge.svg?token=lbfTIGwu6t)](https://codecov.io/gh/waitingsong/midway-components) -[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) -[![lerna](https://img.shields.io/badge/maintained%20with-lerna-cc00ff.svg)](https://lernajs.io/) - - -## Note - -ESM build only, requires `@midwayjs >= 3.16` and set `"type": "module"` in `packages.json` - -## Prepare - -[ossutil 下载页面](https://help.aliyun.com/document_detail/120075.html) - -Linux: -```sh -sudo wget https://gosspublic.alicdn.com/ossutil/1.7.11/ossutil64 -O /usr/bin/ossutil -sudo chmod a+x /usr/bin/ossutil -``` - -Windows: -```sh -https://gosspublic.alicdn.com/ossutil/1.7.19/ossutil-v1.7.19-windows-amd64.zip -``` - -## Installation -```sh -npm i @mwcp/ali-oss -``` - -## Configuration - -### Enable Plugin - -Edit `${app_root}/src/configuration.ts`: - -```ts -import { join } from 'path' -import { ILifeCycle } from '@midwayjs/core' -import { Configuration } from '@midwayjs/decorator' -import * as aliOss from '@mw-components/ali-oss' - -@Configuration({ - imports: [ - aliOss, - ], - importConfigs: [join(__dirname, 'config')], -}) -export class ContainerConfiguration implements ILifeCycle { } - -``` - -### Add Configurations - -Update project `src/config/config.prod.ts` -```ts -import { Config } from '@mw-components/ali-oss' - -export enum ClientKey { - ossmain = 'ossmain', -} - -const clientConfig = { - accessKeyId: process.env.ALI_OSS_AID || '', - accessKeySecret: process.env.ALI_OSS_ASECRET || '', - endpoint: process.env.ALI_OSS_ENDPOINT || 'https://oss-cn-hangzhou.aliyuncs.com', - bucket: process.env.ALI_OSS_BUCKET || '', - cmd: 'ossutil', - debug: false, -} - -export const aliOssConfig: Readonly> = { - ossmain: clientConfig, -} -``` - -## Usage - -### Inject and mkdir() - -```ts -import assert from 'node:assert/strict' -import { AliOssComponent } from '@mw-components/ali-oss' -import { App, Config, Inject } from '@midwayjs/decorator' - -export class RootClass { - @Inject() readonly ossClient: AliOssComponent - - async mkdir(path: string): Promise { - const mkdirRet = await ossClient.mkdir('ossmain', path) - assert(! mkdirRet.exitCode, 'mkdir failed') - assert(mkdirRet.data, 'mkdir failed') - } -} - -``` - -### Methods - -- `cp()` 在远程拷贝 -- `createSymlink()` 创建软连接 -- `mkdir()` 创建目录 -- `mv()` 在远程移动对象 -- `pathExists()` 检测远程文件是否存在 -- `rm()` 删除远程对象 -- `rmrf()` 删除远程对象及其下级所有对象 -- `stat()` 获取远程对象属性 -- `syncLocal()` (强制)同步远程对象到本地 -- `syncRemote()` (强制)同步本地目录到远程 -- `upload()` 上传本地文件到远程 - -## License -[MIT](LICENSE) - diff --git a/packages/ali-oss/bootstrap.js b/packages/ali-oss/bootstrap.js deleted file mode 100644 index 01b9c2c35..000000000 --- a/packages/ali-oss/bootstrap.js +++ /dev/null @@ -1,2 +0,0 @@ -import { Bootstrap } from '@midwayjs/bootstrap'; -await Bootstrap.run(); diff --git a/packages/ali-oss/package.json b/packages/ali-oss/package.json deleted file mode 100644 index 612d5155c..000000000 --- a/packages/ali-oss/package.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "name": "@mwcp/ali-oss", - "author": "waiting", - "version": "41.0.0", - "description": "Ali OSS Component for midway.js", - "keywords": [ - "midway", - "IoC", - "plugin", - "ali", - "aliyun", - "ali-sdk", - "oss", - "ossutil", - "ESM", - "ts" - ], - "type": "module", - "bin": {}, - "types": "dist/index.d.ts", - "imports": { - "#package.json": "./package.json", - "##/*": "./src/*", - "#@/*": "./test/*" - }, - "exports": { - ".": "./dist/index.js", - "./package.json": "./package.json" - }, - "bugs": { - "url": "https://github.com/waitingsong/midway-components/issues" - }, - "homepage": "https://github.com/waitingsong/midway-components/tree/main/packages/ali-oss#readme", - "repository": { - "type": "git", - "url": "https://github.com/waitingsong/midway-components" - }, - "license": "MIT", - "dependencies": { - "@midwayjs/info": "^3.19.0", - "@mwcp/otel": "^41.0.0", - "@mwcp/share": "^41.0.0", - "@yuntools/ali-oss": "^16.1.5" - }, - "engines": { - "node": ">=20.11.0", - "@midwayjs/core": ">=3.16.0" - }, - "files": [ - "README.*.md", - "Dockerfile", - "npm-shrinkwrap.json", - "tsconfig.json", - "tsconfig.base.json", - "asset", - "bin", - "database", - "dist", - "src", - "!**/*.spec.*" - ], - "publishConfig": { - "access": "public" - }, - "scripts": { - "build": "npm run tsc", - "build:unit": "tsc -p test/tsconfig.json", - "clean": "npm run clean:lock && npm run clean:dist && npm run clean:log", - "clean:cache": "rm -rf .eslintcache .tsbuildinfo", - "clean:dist": "npm run clean:cache && rm -rf dist/*", - "clean:lock": "rm -f package-lock.json", - "clean:log": "rm -rf ./logs ./run", - "cov": "c8 --all npm run test", - "dev": "cross-env MIDWAY_SERVER_ENV=local mwtsc --watch --run @midwayjs/mock/app", - "lint": "eslint --fix --cache src test", - "lint:nofix": "eslint --cache src test", - "postbuild": "tsc-alias", - "pretest": "npm run build:unit", - "start": "cross-env NODE_ENV=production node ./bootstrap.js", - "start:gc": "cross-env NODE_ENV=local node --trace_gc ./bootstrap.js", - "test": "cross-env MIDWAY_SERVER_ENV=unittest TS_NODE_PROJECT=test/tsconfig.json mocha --parallel=false", - "test:deb": "npm run test", - "tsc": "tsc -b" - } -} diff --git a/packages/ali-oss/src/app/default.controller.ts b/packages/ali-oss/src/app/default.controller.ts deleted file mode 100644 index da584504b..000000000 --- a/packages/ali-oss/src/app/default.controller.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { - Controller, - Get, -} from '@midwayjs/core' -import { ApiResponse } from '@midwayjs/swagger' -import { MConfig } from '@mwcp/share' - -import { Config, ConfigKey, Msg } from '##/lib/types.js' - -import { DefaultApi } from './default.types.js' - - -@Controller(DefaultApi.base) -export class DefaultAliOssController { - - @MConfig(ConfigKey.config) private readonly config: Config - - @Get(DefaultApi.hello) - @ApiResponse({ - type: 'string', - description: Msg.hello, - }) - async hello(): Promise { - void this.config - return Msg.hello - } - -} - diff --git a/packages/ali-oss/src/app/default.types.ts b/packages/ali-oss/src/app/default.types.ts deleted file mode 100644 index e65cc7bab..000000000 --- a/packages/ali-oss/src/app/default.types.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { ConfigKey } from '##/lib/types.js' - - -export class DefaultApi { - - static readonly base = `/_${ConfigKey.namespace}` - static readonly hello = '/hello' - -} diff --git a/packages/ali-oss/src/app/index.controller.ts b/packages/ali-oss/src/app/index.controller.ts deleted file mode 100644 index 4933eeacb..000000000 --- a/packages/ali-oss/src/app/index.controller.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from './default.controller.js' - diff --git a/packages/ali-oss/src/config/config.default.ts b/packages/ali-oss/src/config/config.default.ts deleted file mode 100644 index 4c4aab848..000000000 --- a/packages/ali-oss/src/config/config.default.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { initialConfig } from '../lib/config.js' -import type { Config } from '../lib/types.js' - - -export const koa = { - port: 7001, -} - -export const aliOssConfig: Readonly = { - enableDefaultRoute: false, - dataSource: {}, - default: { - ...initialConfig, - }, -} - diff --git a/packages/ali-oss/src/config/config.local.ts b/packages/ali-oss/src/config/config.local.ts deleted file mode 100644 index 5f9ac59c2..000000000 --- a/packages/ali-oss/src/config/config.local.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Config } from '../lib/types.js' - - -export const aliOssConfig: Partial = { - enableDefaultRoute: true, -} - diff --git a/packages/ali-oss/src/config/config.unittest.ts b/packages/ali-oss/src/config/config.unittest.ts deleted file mode 100644 index 9e263ef09..000000000 --- a/packages/ali-oss/src/config/config.unittest.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { initialConfig } from '../lib/config.js' -import type { ClientKey, Config } from '../lib/types.js' - - -export const keys = Date.now().toString() - -export const aliOssConfig: Readonly> = { - enableDefaultRoute: true, - dataSource: { - ossUnitTest: { - sampleThrottleMs: 100, - accessKeyId: process.env['ALI_OSS_AID'] ?? '', - accessKeySecret: process.env['ALI_OSS_ASECRET'] ?? '', - endpoint: process.env['ALI_OSS_ENDPOINT'] ?? '', - bucket: process.env['ALI_OSS_BUCKET'] ?? '', - }, - }, - default: { - ...initialConfig, - sampleThrottleMs: 100, - enableTrace: true, - }, -} - diff --git a/packages/ali-oss/src/configuration.ts b/packages/ali-oss/src/configuration.ts deleted file mode 100644 index 8ed935374..000000000 --- a/packages/ali-oss/src/configuration.ts +++ /dev/null @@ -1,67 +0,0 @@ - -import { - App, - Configuration, - ILifeCycle, - ILogger, - Inject, - Logger, - MidwayEnvironmentService, - MidwayInformationService, - MidwayWebRouterService, -} from '@midwayjs/core' -import { - Application, - MConfig, - deleteRouter, -} from '@mwcp/share' - -import * as DefaultConfig from './config/config.default.js' -import * as LocalConfig from './config/config.local.js' -import * as UnittestConfig from './config/config.unittest.js' -import { useComponents } from './imports.js' -import { - Config, - ConfigKey, -} from './lib/types.js' - - -@Configuration({ - namespace: ConfigKey.namespace, - importConfigs: [ - { - default: DefaultConfig, - local: LocalConfig, - unittest: UnittestConfig, - }, - ], - imports: useComponents, -}) -export class AutoConfiguration implements ILifeCycle { - - @App() readonly app: Application - - @Inject() protected readonly environmentService: MidwayEnvironmentService - @Inject() protected readonly informationService: MidwayInformationService - @Inject() protected readonly webRouterService: MidwayWebRouterService - - @Logger() protected readonly logger: ILogger - - @MConfig(ConfigKey.config) protected readonly config: Config - - async onConfigLoad(): Promise { - if (! this.config.enableDefaultRoute) { - await deleteRouter(`/_${ConfigKey.namespace}`, this.webRouterService) - } - // else if (this.mwConfig.ignore) { - // this.mwConfig.ignore.push(new RegExp(`/_${ConfigKey.namespace}/.+`, 'u')) - // } - } - - async onReady(): Promise { - this.logger.info(`[${ConfigKey.componentName}] onReady`) - } - -} - - diff --git a/packages/ali-oss/src/imports.ts b/packages/ali-oss/src/imports.ts deleted file mode 100644 index 096fe7342..000000000 --- a/packages/ali-oss/src/imports.ts +++ /dev/null @@ -1,27 +0,0 @@ -import * as info from '@midwayjs/info' -import * as koa from '@midwayjs/koa' -import * as swagger from '@midwayjs/swagger' -import * as otel from '@mwcp/otel' - - -/* c8 ignore next 4 */ -const CI = !! (process.env['MIDWAY_SERVER_ENV'] === 'unittest' - || process.env['MIDWAY_SERVER_ENV'] === 'local' - || process.env['NODE_ENV'] === 'unittest' - || process.env['NODE_ENV'] === 'local' -) - -export const useComponents: IComponentInfo[] = [] -if (CI) { - useComponents.push(koa) - useComponents.push(info) - useComponents.push(swagger) -} - -useComponents.push(otel) - -export interface IComponentInfo { - Configuration: unknown - [key: string]: unknown -} - diff --git a/packages/ali-oss/src/index.ts b/packages/ali-oss/src/index.ts deleted file mode 100644 index f1217e155..000000000 --- a/packages/ali-oss/src/index.ts +++ /dev/null @@ -1,27 +0,0 @@ - -import type { Config, ConfigKey } from './lib/types.js' - - -export { AutoConfiguration as Configuration } from './configuration.js' -export * from './app/index.controller.js' -export * from './lib/index.js' -export { - type BaseOptions, - type Config as OssConfig, - type DataBase, - type DataCp, - type DataSign, - type DataStat, - type ProcessRet, - FnKey, - OssClient, -} from '@yuntools/ali-oss' - - -declare module '@midwayjs/core/dist/interface.js' { - interface MidwayConfig { - [ConfigKey.config]?: Config - } -} - - diff --git a/packages/ali-oss/src/lib/component.ts b/packages/ali-oss/src/lib/component.ts deleted file mode 100644 index 36861cc57..000000000 --- a/packages/ali-oss/src/lib/component.ts +++ /dev/null @@ -1,522 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unnecessary-condition */ -/* eslint-disable max-lines-per-function */ -import { AttrNames, SpanStatusCode } from '@mwcp/otel' -import type { Attributes, TraceService } from '@mwcp/otel' -import { genError, genISO8601String } from '@waiting/shared-core' -import { FnKey, OssClient } from '@yuntools/ali-oss' -import type { - BaseOptions, - Config as OssConfig, - CpOptions as AliCpOptions, - DataBase, - DataCp, - DataDownload, - DataSign, - DataStat, - ProcessRet, -} from '@yuntools/ali-oss' - -import { ConfigKey } from './types.js' -import type { - CpOptions, - DownloadOptions, - InstanceConfig, - LinkOptions, - MkdirOptions, MvOptions, - PathExistsOptions, - QuerySpanInfo, - RmOptions, RmrfOptions, - SignOptions, StatOptions, SyncLocalOptions, SyncRemoteOptions, - UploadOptions, -} from './types.js' - - -/** 阿里云 OSS oss-utils 命令行封装组件 */ -export class AliOssComponent { - - traceService: TraceService - - private readonly client: OssClient - private readonly querySpanMap = new WeakMap() - - constructor(protected readonly config: InstanceConfig) { - const opts: OssConfig = { - accessKeyId: config.accessKeyId, - accessKeySecret: config.accessKeySecret, - endpoint: config.endpoint, - } - if (config.stsToken) { - opts.stsToken = config.stsToken - } - - const client = new OssClient(opts, config.cmd) - client.debug = !! config.debug - this.client = client - } - - /** - * 拷贝文件, - * - 拷贝本地文件/目录到远程建议使用 `upload()` 或者 `syncRemote()` 方法 - * - 拷贝远程文件/目录到本地建议使用 `download()` 或者 `syncLocal()` 方法 - * - * 若 force 为空或者 false,且目标文件存在时会卡在命令行提示输入阶段(无显示)最后导致超时异常 - * @link https://help.aliyun.com/document_detail/120057.html - */ - async cp( - /** 本地文件、目录或者远程 OSS 对象 */ - src: string, - /** OSS 对象,不包括 bucket */ - target: string, - options?: CpOptions, - ): Promise> { - - const opts: RunnerOptions = { - fnKey: FnKey.cp, - options, - target, - src, - } - const ret = await this.runner>(opts) - return ret - } - - /** - * 上传本地文件到 OSS - * 若 force 为空或 false,且目标文件存在时会卡在命令行提示输入阶段(无显示)最后导致超时异常 - * @link https://help.aliyun.com/document_detail/120057.html - */ - async upload( - /** 本地目录或文件 */ - src: string, - /** OSS 对象,不包括 bucket */ - target: string, - options?: UploadOptions, - ): Promise> { - - const opts: RunnerOptions = { - fnKey: FnKey.upload, - options, - target, - src, - } - const ret = await this.runner>(opts) - return ret - } - - /** - * 下载远程文件到本地 - * 若 force 为空或 false,且目标文件存在时会卡在命令行提示输入阶段(无显示)最后导致超时异常 - * @link https://help.aliyun.com/document_detail/120057.html - */ - async download( - /** OSS 对象,不包括 bucket */ - src: string, - /** 本地目录或文件 */ - target: string, - options?: DownloadOptions, - ): Promise> { - - const opts: RunnerOptions = { - fnKey: FnKey.download, - options, - target, - src, - } - const ret = await this.runner>(opts) - return ret - } - - /** - * 创建软链接 - * @link https://help.aliyun.com/document_detail/120059.html - */ - async createSymlink( - /** OSS 对象,不包括 bucket */ - src: string, - /** OSS 软连接对象,不包括 bucket */ - target: string, - options?: LinkOptions, - ): Promise { - - const opts: RunnerOptions = { - fnKey: FnKey.link, - options, - target, - src, - } - const ret = await this.runner(opts) - return ret - } - - /** - * 创建目录 - * @link https://help.aliyun.com/document_detail/120062.html - */ - async mkdir( - /** OSS 对象,不包括 bucket */ - target: string, - options?: MkdirOptions, - ): Promise { - - const opts: RunnerOptions = { - fnKey: FnKey.mkdir, - options, - target, - src: void 0, - } - const ret = await this.runner(opts) - return ret - } - - /** - * 移动云端的 OSS 对象 - * 流程为先 `cp()` 然后 `rm()` - */ - async mv( - /** OSS 源对象,不包括 bucket */ - src: string, - /** OSS 目的对象,不包括 bucket */ - target: string, - options?: MvOptions, - ): Promise> { - - const opts: RunnerOptions = { - fnKey: FnKey.mv, - options, - target, - src, - } - const ret = await this.runner>(opts) - return ret - } - - /** - * OSS 远程路径是否存在 - */ - async pathExists( - /** OSS 对象,不包括 bucket */ - target: string, - options?: StatOptions, - ): Promise { - - const opts: RunnerOptions = { - fnKey: FnKey.pathExists, - options, - target, - src: void 0, - } - const ret = await this.runner(opts) - return ret - } - - - /** - * 删除云对象,不支持删除 bucket 本身 - * 如果在 recursive 为 false 时删除目录,则目录参数值必须以 '/' 结尾,否则不会删除成功 - * @link https://help.aliyun.com/document_detail/120053.html - */ - async rm( - /** OSS 对象,不包括 bucket */ - target: string, - options?: RmOptions, - ): Promise { - - const opts: RunnerOptions = { - fnKey: FnKey.rm, - options, - target, - src: void 0, - } - const ret = await this.runner(opts) - return ret - } - - /** - * 递归删除,相当于 `rm -rf` - * @link https://help.aliyun.com/document_detail/120053.html - */ - async rmrf( - /** OSS 对象,不包括 bucket */ - target: string, - options?: RmrfOptions, - ): Promise { - - const opts: RunnerOptions = { - fnKey: FnKey.rmrf, - options, - target, - src: void 0, - } - const ret = await this.runner(opts) - return ret - } - - /** - * sign(生成签名URL) - * @link https://help.aliyun.com/document_detail/120064.html - */ - async sign( - /** OSS 对象,不包括 bucket */ - src: string, - options?: SignOptions, - ): Promise> { - - const opts: RunnerOptions = { - fnKey: FnKey.sign, - options, - target: void 0, - src, - } - const ret = await this.runner>(opts) - return ret - } - - /** - * 查看 Bucket 和 Object 信息 - * @link https://help.aliyun.com/document_detail/120054.html - */ - async stat( - /** OSS 对象,不包括 bucket */ - target: string, - options?: StatOptions, - ): Promise { - - const opts: RunnerOptions = { - fnKey: FnKey.stat, - options, - target, - src: void 0, - } - const ret = await this.runner(opts) - return ret - } - - /** - * 同步 OSS 文件到本地 - * - force 参数默认 true - * - 若 force 为 false,且目标文件存在时会卡在命令行提示输入阶段(无显示)最后导致超时异常 - * @link https://help.aliyun.com/document_detail/256352.html - */ - async syncLocal( - /** OSS 对象,不包括 bucket */ - src: string, - /** 本地目录 */ - target: string, - options?: SyncLocalOptions, - ): Promise> { - - const opts: RunnerOptions = { - fnKey: FnKey.syncLocal, - options, - target, - src, - } - const ret = await this.runner>(opts) - return ret - } - - /** - * 同步本地文件到 OSS - * - force 参数默认 true - * - 若 force 为 false,且目标文件存在时会卡在命令行提示输入阶段(无显示)最后导致超时异常 - * @link https://help.aliyun.com/document_detail/193394.html - */ - async syncRemote( - /** 本地目录 */ - src: string, - /** OSS 对象,不包括 bucket */ - target: string, - options?: SyncRemoteOptions, - ): Promise> { - - const opts: RunnerOptions = { - fnKey: FnKey.syncRemote, - options, - target, - src, - } - const ret = await this.runner>(opts) - return ret - } - - - protected async runner< - T extends BaseOptions, - R extends ProcessRet | boolean = ProcessRet, - >(options: RunnerOptions): Promise { - - const { fnKey } = options - const opts = this.genOptions(options) - - const id = { time: Symbol(Date.now()) } - try { - await this.tracer('start', id, opts) - // @ts-ignore - const ret = await this.client[fnKey](opts) as Promise - await this.tracer('finish', id, opts) - return await ret - } - catch (ex) { - const err = ex instanceof Error - ? ex - : typeof ex === 'string' ? new Error(ex) : new Error(JSON.stringify(ex)) - await this.tracer('error', id, opts, err) - throw err - } - } - - - protected genOptions(input: RunnerOptions): _RunnerOption { - const ret = { - ...this.config, - src: input.src, - target: input.target, - ...input.options, - } - return ret as unknown as _RunnerOption - } - - protected async tracer( - type: 'start' | 'finish' | 'error', - id: { time: symbol }, - options: _RunnerOption, - err?: Error, - ): Promise { - - if (! options.enableTrace) { return } - if (! this.traceService) { return } - - const end = Date.now() - - const tmp = options as unknown as AliCpOptions & InstanceConfig - const opts: Attributes = { - acl: tmp.acl ?? '', - src: tmp.src, - payer: tmp.payer ?? '', - recursive: tmp.recursive ?? false, - sampleThrottleMs: tmp.sampleThrottleMs ?? 10000, - target: tmp.target, - } - - switch (type) { - case 'start': { - const { span } = this.traceService.startScopeSpan({ - name: ConfigKey.componentName, - scope: id, - }) - const spanInfo: QuerySpanInfo = { - span, - timestamp: Date.now(), - } - this.querySpanMap.set(id, spanInfo) - - const attrs: Attributes = { - [AttrNames.QueryCostThrottleInMS]: opts['sampleThrottleMs'], - qid: id.time.toString(), - acl: opts['acl'], - payer: opts['payer'], - recursive: opts['recursive'], - src: opts['src'], - target: opts['target'], - } - this.traceService.setAttributes(span, attrs) - - const event: Attributes = { - event: AttrNames.QueryStart, - time: genISO8601String(), - } - this.traceService.addEvent(span, event) - break - } - - case 'finish': { - const spanInfo = this.querySpanMap.get(id) - if (! spanInfo) { - console.warn('Retrieve spanInfo undefined.', opts) - return - } - const { span } = spanInfo - - const start = spanInfo.timestamp - const cost = end - start - const tags: Attributes = { - [AttrNames.QueryCost]: cost, - } - this.traceService.setAttributes(span, tags) - - const event: Attributes = { - event: AttrNames.QueryFinish, - time: genISO8601String(), - [AttrNames.QueryCost]: cost, - } - - if (typeof opts['sampleThrottleMs'] === 'number' - && opts['sampleThrottleMs'] > 0 && cost > opts['sampleThrottleMs']) { - - const tags2: Attributes = { - // [AttrNames.SAMPLING_PRIORITY]: 50, - [AttrNames.LogLevel]: 'warn', - } - this.traceService.setAttributes(span, tags2) - this.traceService.addEvent(span, event) - } - else { - this.traceService.addEvent(span, event) - } - - this.traceService.endSpan({ span, scope: id }) - break - } - - case 'error': { - const spanInfo = this.querySpanMap.get(id) - if (! spanInfo) { - console.warn('Retrieve spanInfo undefined.', opts) - return - } - const { span } = spanInfo - - const start = spanInfo.timestamp - const cost = end - start - const attr: Attributes = { - [AttrNames.QueryCost]: cost, - } - this.traceService.setAttributes(span, attr) - - const input = { - event: AttrNames.QueryError, - time: genISO8601String(), - [AttrNames.LogLevel]: 'error', - [AttrNames.QueryCost]: cost, - // [AttrNames.Error]: err, - } - this.traceService.addEvent(span, input) - this.traceService.endSpan({ - span, - scope: id, - spanStatusOptions: { - code: SpanStatusCode.ERROR, - error: genError({ - error: err, - altMessage: 'Unknown error.', - }), - }, - }) - break - } - } - - return - } - -} - - -interface RunnerOptions { - fnKey: FnKey - options: T | undefined - src: string | undefined - target: string | undefined -} - -type _RunnerOption = InstanceConfig & T diff --git a/packages/ali-oss/src/lib/config.ts b/packages/ali-oss/src/lib/config.ts deleted file mode 100644 index a81d8d88a..000000000 --- a/packages/ali-oss/src/lib/config.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { InstanceConfig, MiddlewareConfig, MiddlewareOptions } from './types.js' - - -export const initialConfig: Readonly = { - accessKeyId: '', - accessKeySecret: '', - endpoint: '', - bucket: '', - cmd: 'ossutil', - debug: false, - enableTrace: false, - sampleThrottleMs: 10000, -} - -export const initMiddlewareOptions: MiddlewareOptions = { - debug: false, -} -export const initialMiddlewareConfig: Readonly> = { - enableMiddleware: true, -} - diff --git a/packages/ali-oss/src/lib/index.ts b/packages/ali-oss/src/lib/index.ts deleted file mode 100644 index cb17966b8..000000000 --- a/packages/ali-oss/src/lib/index.ts +++ /dev/null @@ -1,33 +0,0 @@ - -export * from './config.js' -export { AliOssComponent } from './component.js' -export { AliOssManager } from './manager.js' -export { AliOssSourceManager } from './source-manager.js' - -export { - - type ClientConfig, - type Config as AliOssConfig, - type CpOptions, - type DataSource as AliOssDataSource, - type DownloadOptions, - type InstanceConfig, - type LinkOptions, - type MiddlewareConfig as AliOssMiddlewareConfig, - type MiddlewareOptions as AliOssMiddlewareOptions, - - type MkdirOptions, - type MvOptions, - type PathExistsOptions, - type RmOptions, - type RmrfOptions, - type SignOptions, - type StatOptions, - type SyncLocalOptions, - type SyncOptions, - type SyncRemoteOptions, - type UploadOptions, - ConfigKey as AliOssConfigKey, - Msg as AliOssMsg, -} from './types.js' - diff --git a/packages/ali-oss/src/lib/manager.ts b/packages/ali-oss/src/lib/manager.ts deleted file mode 100644 index 71af2c2d7..000000000 --- a/packages/ali-oss/src/lib/manager.ts +++ /dev/null @@ -1,72 +0,0 @@ -import assert from 'node:assert' - -import { - CreateDataSourceInstanceOptions as CreateInstanceOptions, - Inject, - Singleton, -} from '@midwayjs/core' -import { TraceService } from '@mwcp/otel' - -import { AliOssComponent } from './component.js' -import { AliOssSourceManager } from './source-manager.js' -import { ConfigKey, InstanceConfig } from './types.js' - - -@Singleton() -export class AliOssManager { - - @Inject() readonly traceService: TraceService - - @Inject() protected readonly sourceManager: AliOssSourceManager - - getName(): string { return ConfigKey.managerName } - - instCacheMap = new Map() - - - async createInstance( - config: InstanceConfig, - clientName: SourceName, - options?: CreateInstanceOptions, - ): Promise { - - const opts: CreateInstanceOptions = { - validateConnection: true, - ...options, - } - await this.sourceManager.createInstance(config, clientName, opts) - return this.getDataSource(clientName) - } - - /** - * Check the data source is connected - */ - async isConnected(dataSourceName: SourceName): Promise { - return this.sourceManager.isConnected(dataSourceName) - } - - - getDataSource(dataSourceName: SourceName): AliOssComponent { - const cacheInst = this.instCacheMap.get(dataSourceName) - if (cacheInst) { - return cacheInst - } - - const inst = this.sourceManager.getDataSource(dataSourceName) - assert(inst) - - this.updateProperties(inst) - this.instCacheMap.set(dataSourceName, inst) - - return inst - } - - protected updateProperties(inst: AliOssComponent): void { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (! inst.traceService) { - inst.traceService = this.traceService - } - } - -} - diff --git a/packages/ali-oss/src/lib/source-manager.ts b/packages/ali-oss/src/lib/source-manager.ts deleted file mode 100644 index f9ccdf1df..000000000 --- a/packages/ali-oss/src/lib/source-manager.ts +++ /dev/null @@ -1,97 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unnecessary-condition */ -import assert from 'node:assert' - -import { - CreateDataSourceInstanceOptions as CreateInstanceOptions, - DataSourceManager, - Init, - Inject, - Singleton, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { AliOssComponent } from './component.js' -import { Config, ConfigKey, InstanceConfig } from './types.js' - - -@Singleton() -export class AliOssSourceManager - extends DataSourceManager { - - @MConfig(ConfigKey.config) private readonly sourceConfig: Config - - @Inject() baseDir: string - - // public queryUidSpanMap = new Map() - - declare dataSource: Map - - declare getDataSource: (dataSourceName: SourceName) - => string extends SourceName ? AliOssComponent | undefined : AliOssComponent - - declare createInstance: ( - config: InstanceConfig, - clientName: SourceName, - options?: CreateInstanceOptions, - ) => Promise - - @Init() - async init(): Promise { - assert(this.sourceConfig?.dataSource, 'dataSourceConfig is not defined') - // 需要注意的是,这里第二个参数需要传入一个实体类扫描地址 - await this.initDataSource(this.sourceConfig, this.baseDir) - } - - - /** - * 创建单个实例 - */ - protected async createDataSource( - config: InstanceConfig, - dataSourceName: SourceName, - cacheDataSource = true, - ): Promise { - - const cacheInst = cacheDataSource ? this.getDataSource(dataSourceName) : null - if (cacheDataSource && cacheInst) { - return cacheInst - } - - const inst = new AliOssComponent(config) - if (cacheDataSource && inst) { - if (! this.sourceConfig.dataSource[dataSourceName]) { - this.sourceConfig.dataSource[dataSourceName] = config - } - } - - if (! cacheDataSource) { - // saved in initDataSource - this.dataSource.delete(dataSourceName) - } - return inst - } - - getName(): string { return ConfigKey.sourceManagerName } - - protected async checkConnected(dataSource: AliOssComponent): Promise { - if (! dataSource) { - return false - } - // @TODO check connection - return true - } - - async destroyDataSource(): Promise { - return - } - - - // protected getConfigByDbId(clientId: SourceName): InstanceConfig | undefined { - // assert(clientId) - // const config = this.sourceConfig.dataSource[clientId] - // return config - // } - -} - - diff --git a/packages/ali-oss/src/lib/types.ts b/packages/ali-oss/src/lib/types.ts deleted file mode 100644 index 9e5f908f6..000000000 --- a/packages/ali-oss/src/lib/types.ts +++ /dev/null @@ -1,88 +0,0 @@ -import type { Span } from '@mwcp/otel' -import type { BaseConfig } from '@mwcp/share' -import type { MiddlewareConfig as MWConfig } from '@waiting/shared-types' -import type * as Ali from '@yuntools/ali-oss' -import { Msg as _Msg } from '@yuntools/ali-oss' - - -export enum ConfigKey { - namespace = 'aliOss', - config = 'aliOssConfig', - middlewareConfig = 'aliOssMiddlewareConfig', - aliOssInstanceKey = 'aliOssInstanceKey', - componentName = 'aliOssComponent', - managerName = 'aliOssManager', - sourceManagerName = 'aliOssSourceManager', -} - - -export enum Msg2 { - hello = 'hello aliOss', -} - -export const Msg = { ..._Msg, ...Msg2 } -export type Msg = _Msg | Msg2 - -export enum ClientKey { - master = 'ossMaster', - unitTest = 'ossUnitTest', -} - - -export interface ClientConfig { - accessKeyId: string - accessKeySecret: string - endpoint: string - stsToken?: string - cmd?: string - debug?: boolean - bucket: string -} - -export interface MiddlewareOptions { - debug: boolean -} -export type MiddlewareConfig = MWConfig - - -/** midway DataSource */ -export interface Config extends BaseConfig { - dataSource: DataSource - default?: InstanceConfig -} -export type DataSource = Record -export interface InstanceConfig extends ClientConfig { - /** - * Enable tracing via @mwcp/otel - * @default false - */ - enableTrace?: boolean - /** - * 强制采样请求处理时间(毫秒)阈值 - * 负数不采样 - * @default 10_000 - */ - sampleThrottleMs?: number -} - - -export type MkdirOptions = Omit -export type CpOptions = Omit -export type UploadOptions = Omit -export type DownloadOptions = Omit -export type LinkOptions = Omit -export type RmOptions = Omit -export type RmrfOptions = Omit -export type StatOptions = Omit -export type PathExistsOptions = Omit -export type MvOptions = Omit -export type SignOptions = Omit -export type SyncOptions = Omit -export type SyncLocalOptions = Omit -export type SyncRemoteOptions = Omit - -export interface QuerySpanInfo { - span: Span - timestamp: number -} - diff --git a/packages/ali-oss/test/00.dummy.test.ts b/packages/ali-oss/test/00.dummy.test.ts deleted file mode 100644 index 0dc314d66..000000000 --- a/packages/ali-oss/test/00.dummy.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('should work', () => { - it('always passed', () => { - assert(testConfig) - }) - }) - -}) - diff --git a/packages/ali-oss/test/01.index.test.ts b/packages/ali-oss/test/01.index.test.ts deleted file mode 100644 index 178dd01e3..000000000 --- a/packages/ali-oss/test/01.index.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { useComponents } from '##/imports.js' -import * as Foo from '##/index.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('should work', () => { - it('index', () => { - assert(Foo) - }) - - it('useComponents', () => { - assert(Array.isArray(useComponents)) - }) - - it('testAppDir eq testConfig.testAppDir', () => { - const { app } = testConfig - assert(app) - - const appDir = app.getAppDir() - assert(appDir) - assert(appDir === testConfig.testAppDir) - }) - }) - -}) - diff --git a/packages/ali-oss/test/02.home.test.ts b/packages/ali-oss/test/02.home.test.ts deleted file mode 100644 index 730f8b91e..000000000 --- a/packages/ali-oss/test/02.home.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { ConfigKey, Msg } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' -import type { RespData, TestRespBody } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - const helloPath = `${apiBase.prefix}/${apiMethod.hello}` - - it(`Should ${apiBase.root} work`, async () => { - const { app, httpRequest } = testConfig - - const resp = await httpRequest.get(apiBase.root) - assert(resp.ok, resp.text) - - const ret = resp.body as TestRespBody | RespData - assert(typeof ret === 'object', JSON.stringify(ret, null, 2)) - - if ('code' in ret && typeof ret.code === 'number') { - assert(ret.code === 0) - assert(typeof ret.data === 'object', JSON.stringify(ret, null, 2)) - - const { url, header } = ret.data - const { host } = header - assert(url === '/', JSON.stringify(ret, null, 2)) - assert(host && testConfig.host.includes(host), JSON.stringify(ret, null, 2)) - } - else { - const { url, header } = ret as RespData - const { host } = header - assert(url === '/', JSON.stringify(ret, null, 2)) - assert(host && testConfig.host.includes(host), JSON.stringify(ret, null, 2)) - } - }) - - it(`Should ${helloPath} work`, async () => { - const { app, httpRequest } = testConfig - - const resp = await httpRequest.get(helloPath) - assert(resp.ok, resp.text) - - const ret = resp.text - assert(ret.includes(Msg.hello), JSON.stringify(ret, null, 2)) - }) - -}) - diff --git a/packages/ali-oss/test/api-test.ts b/packages/ali-oss/test/api-test.ts deleted file mode 100644 index 2d37ddb41..000000000 --- a/packages/ali-oss/test/api-test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { ConfigKey } from '##/lib/types.js' - - -export const apiBase = { - root: '/', - prefix: `/_${ConfigKey.namespace}`, - demo: '/demo', - oss: '/oss', -} - -export const apiMethod = { - root: '/', - hello: 'hello', - component: 'component', - stat: 'stat', - mkdir: 'mkdir', -} diff --git a/packages/ali-oss/test/component/11.mkdir.test.ts b/packages/ali-oss/test/component/11.mkdir.test.ts deleted file mode 100644 index 04425124f..000000000 --- a/packages/ali-oss/test/component/11.mkdir.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import type { MkdirOptions } from '../../src/index.js' -import { TestRespBody, cloudUrlPrefix, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - describe('mkdir should work', () => { - it('normal', async () => { - const { CI, ossClient } = testConfig - - const target = `${cloudUrlPrefix}/1${Math.random().toString()}/` - const ret = await ossClient.mkdir(target) - - CI || console.log(ret) - assert(! ret.exitCode, `mkdir ${target} failed, ${ret.stderr}`) - assert(ret.data) - assert(typeof ret.data.elapsed === 'string') - }) - - it('mchar', async () => { - const { CI, ossClient } = testConfig - - const target = `${cloudUrlPrefix}/联通€-&a'b"ce^f?g*-${Math.random().toString()}/v2/v3/` - const ret = await ossClient.mkdir(target) - - CI || console.log(ret) - assert(! ret.exitCode, `mkdir ${target} failed, ${ret.stderr}`) - assert(ret.data) - assert(typeof ret.data.elapsed === 'string') - }) - - it('incorrect dir name when encodeTarget:false', async () => { - const { CI, ossClient } = testConfig - - const prefix = `${cloudUrlPrefix}/联通€-` - const target = `${prefix}&a'b"ce?f*-${Math.random().toString()}/v2/v3/` - - const opts: MkdirOptions = { - encodeTarget: false, - } - - try { - const ret = await ossClient.mkdir(target, opts) - CI || console.log(ret) - assert(! ret.exitCode, `mkdir ${target} failed, ${ret.stderr}`) - assert(ret.data) - } - catch (ex) { - assert(ex instanceof Error, 'ex is Error') - return - } - assert(false, 'should throw err but not') - }) - }) -}) - diff --git a/packages/ali-oss/test/component/12.upload.test.ts b/packages/ali-oss/test/component/12.upload.test.ts deleted file mode 100644 index 79cf7cbd2..000000000 --- a/packages/ali-oss/test/component/12.upload.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { TestRespBody, cloudUrlPrefix, src, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - describe('Should upload() work', () => { - it('normal string', async () => { - const { ossClient } = testConfig - - const target = `${cloudUrlPrefix}/${Date.now().toString()}-tsconfig.json` - - const ret = await ossClient.upload(src, target) - assert(! ret.exitCode, `upload ${src} ${target} failed, ${ret.stderr}`) - assert(ret.data) - assert(typeof ret.data.elapsed === 'string') - assert(typeof ret.data.averageSpeed === 'number') - }) - }) - -}) - diff --git a/packages/ali-oss/test/component/14.createSymlink.test.ts b/packages/ali-oss/test/component/14.createSymlink.test.ts deleted file mode 100644 index 917c4c31e..000000000 --- a/packages/ali-oss/test/component/14.createSymlink.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { TestRespBody, cloudUrlPrefix, src, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - describe('createSymlink should work', () => { - it('normal', async () => { - const { CI, ossClient } = testConfig - - const target = `${cloudUrlPrefix}/${Date.now().toString()}-tsconfig.json` - await ossClient.cp(src, target) - - const link = `${target}-link` - const ret = await ossClient.createSymlink(target, link) - CI || console.log(ret) - assert(ret.exitCode === 0) - assert(ret.data) - assert(typeof ret.data.elapsed === 'string') - }) - }) - -}) - - diff --git a/packages/ali-oss/test/component/18.mv.test.ts b/packages/ali-oss/test/component/18.mv.test.ts deleted file mode 100644 index c8d2cf9ee..000000000 --- a/packages/ali-oss/test/component/18.mv.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { Msg } from '../../src/lib/types.js' -import { TestRespBody, cloudUrlPrefix, src, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - describe('mv should work', () => { - it('file', async () => { - const { ossClient } = testConfig - const dd = new Date() - console.log('start:', new Date().toTimeString()) - - const target = `${cloudUrlPrefix}/${Date.now().toString()}-tsconfig.json` - console.log('cp:', { src, target }) - const ret = await ossClient.cp(src, target) - console.log('cp done:', new Date().toTimeString()) - assert(! ret.exitCode) - - const newPath = `${target}-${Date.now().toString()}` - console.log('mv:', { target, newPath }) - const mv = await ossClient.mv(target, newPath) - console.log('mv done:', new Date().toTimeString()) - assert(! mv.exitCode, ` ${mv.stderr}`) - - const existsDst = await ossClient.pathExists(newPath) - console.log('existsDst done:', new Date().toTimeString()) - assert(existsDst === true, `${newPath} not exists after mv`) - - const existsOri = await ossClient.pathExists(target) - console.log('existsOri done:', new Date().toTimeString()) - assert(existsOri === false, `${target} exists after mv`) - }) - - it('cloud file dst already exists', async () => { - const { ossClient } = testConfig - - const target = `${cloudUrlPrefix}/${Date.now().toString()}-tsconfig.json` - const ret = await ossClient.cp(src, target) - assert(! ret.exitCode) - - const dst2 = `${target}-${Date.now().toString()}` - const cp = await ossClient.cp(target, dst2, { encodeSource: true }) - assert(! cp.exitCode, cp.stderr) - - const mv = await ossClient.mv(target, dst2) - assert(mv.exitCode, mv.stderr) - assert(mv.stderr.includes(Msg.cloudFileAlreadyExists)) - }) - - it('link', async () => { - const { CI, ossClient } = testConfig - - const target = `${cloudUrlPrefix}/${Date.now().toString()}-tsconfig.json` - await ossClient.cp(src, target) - - const link = `${target}-link` - const ret = await ossClient.createSymlink(target, link) - CI || console.log(ret) - assert(ret.exitCode === 0) - assert(ret.data) - assert(typeof ret.data.elapsed === 'string') - - const exists = await ossClient.pathExists(link) - assert(exists === true) - - const link2 = `${link}-${Date.now().toString()}` - const mv = await ossClient.mv(link, link2) - assert(! mv.exitCode) - - const existsDst = await ossClient.pathExists(link2) - assert(existsDst === true) - - const existsOri = await ossClient.pathExists(link) - assert(existsOri === false) - }) - - }) -}) - - diff --git a/packages/ali-oss/test/component/19.syncRemote.test.ts b/packages/ali-oss/test/component/19.syncRemote.test.ts deleted file mode 100644 index b4ab4d318..000000000 --- a/packages/ali-oss/test/component/19.syncRemote.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* eslint-disable no-await-in-loop */ -import assert from 'node:assert' -import { join } from 'node:path' - -import { fileShortPath } from '@waiting/shared-core' - -import type { SyncOptions } from '../../src/index.js' -import { assertFileExists, assertUploadFiles } from '../helper.js' -import { TestRespBody, cloudUrlPrefix, files, src, srcDir, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - const target = `${cloudUrlPrefix}/sync-${Date.now().toString()}` - - describe('syncRemote should work', () => { - it('include *.txt', async () => { - const { CI, ossClient } = testConfig - - const opts: SyncOptions = { - include: '*.txt', - } - const ret = await ossClient.syncRemote(srcDir, target, opts) - CI || console.log(ret) - assert(! ret.exitCode, `upload ${srcDir} ${target} failed, ${ret.stderr}`) - assertUploadFiles(ret.data, 5, 1, 4, ret.stderr) - - for (const file of files) { - const d2 = join(target, file) - - if (file.endsWith('.txt')) { - await assertFileExists(ossClient, d2) - } - else { - try { - await assertFileExists(ossClient, d2) - } - catch { - continue - } - assert(false, `${file} should not exists`) - } - } - }) - - it('all', async () => { - const { CI, ossClient } = testConfig - - const ret = await ossClient.syncRemote(srcDir, target) - CI || console.log(ret) - assert(! ret.exitCode, `upload ${srcDir} ${target} failed, ${ret.stderr}`) - assertUploadFiles(ret.data, 10, 1, 9, ret.stderr) - - for (const file of files) { - const d2 = join(target, file) - await assertFileExists(ossClient, d2) - } - }) - }) -}) - - diff --git a/packages/ali-oss/test/component/20.syncLocal.test.ts b/packages/ali-oss/test/component/20.syncLocal.test.ts deleted file mode 100644 index 08b6f34e8..000000000 --- a/packages/ali-oss/test/component/20.syncLocal.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -/* eslint-disable no-await-in-loop */ -import assert from 'node:assert' -import { mkdir } from 'node:fs/promises' -import { join } from 'node:path' - -import { fileShortPath } from '@waiting/shared-core' - -import type { SyncOptions } from '../../src/index.js' -import { assertLocalFileExists } from '../helper.js' -import { cloudUrlPrefix, files, srcDir, testConfig, testDir } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const target = `${cloudUrlPrefix}/sync-${Date.now().toString()}` - - describe('syncLocal should work', () => { - it('include *.txt', async () => { - const { CI, ossClient } = testConfig - - await ossClient.syncRemote(srcDir, target) - - const localDir = join(testDir, 'tmp', `files-${Math.random().toString()}/`) - await mkdir(localDir, { recursive: true }) - const opts: SyncOptions = { - include: '*.txt', - } - const ret = await ossClient.syncLocal(target, localDir, opts) - CI || console.log(ret) - - for (const file of files) { - const d2 = join(localDir, file) - - if (file.endsWith('.txt')) { - await assertLocalFileExists(d2) - } - else { - try { - await assertLocalFileExists(d2) - } - catch { - continue - } - assert(false, `${file} should not exists`) - } - } - }) - - it('all', async () => { - const { CI, ossClient } = testConfig - - await ossClient.syncRemote(srcDir, target) - - const localDir = join(testDir, 'tmp', `files-${Math.random().toString()}/`) - await mkdir(localDir, { recursive: true }) - const ret = await ossClient.syncLocal(target, localDir) - CI || console.log(ret) - - for (const file of files) { - const d2 = join(localDir, file) - await assertLocalFileExists(d2) - } - }) - }) -}) - diff --git a/packages/ali-oss/test/component/22.sign.test.ts b/packages/ali-oss/test/component/22.sign.test.ts deleted file mode 100644 index 249cce1d5..000000000 --- a/packages/ali-oss/test/component/22.sign.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import type { SignOptions } from '../../src/index.js' -import { cloudUrlPrefix, src, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - describe('sign should work', () => { - it('normal', async () => { - const { CI, ossClient } = testConfig - - const target = `${cloudUrlPrefix}/${Date.now().toString()}-tsconfig.json` - const ret = await ossClient.cp(src, target) - CI || console.log(ret) - assert(! ret.exitCode, `cp ${src} ${target} failed, ${ret.stderr}`) - assert(ret.data) - - const sign = await ossClient.sign(target, { disableEncodeSlash: true }) - assert(! sign.exitCode, `sign ${target} failed, ${sign.stderr}`) - assert(sign.data) - - const { data } = sign - assert(data.httpUrl) - assert(data.httpUrl.startsWith('https://')) - assert(! data.httpUrl.includes('?Expires=')) - assert(! data.httpUrl.includes('AccessKeyId=')) - - assert(data.httpShareUrl) - assert(data.httpShareUrl.startsWith('https://')) - assert(data.httpShareUrl.includes('?Expires=')) - assert(data.httpShareUrl.includes('AccessKeyId=')) - - assert(data.link) - assert(data.link.startsWith('https://')) - assert(! data.link.includes('?Expires=')) - assert(! data.link.includes('AccessKeyId=')) - assert(! data.link.includes('%2F')) - }) - - it('param trafic-limit (typo)', async () => { - const { CI, ossClient } = testConfig - - const target = `${cloudUrlPrefix}/${Date.now().toString()}-config.js` - const ret = await ossClient.cp(src, target) - CI || console.log(ret) - assert(! ret.exitCode, `cp ${src} ${target} failed, ${ret.stderr}`) - assert(ret.data) - - const opts2: SignOptions = { - trafficLimit: 245760, - timeoutSec: 360, - } - const sign = await ossClient.sign(src, opts2) - assert(! sign.exitCode, `sign ${target} failed, ${sign.stderr}`) - assert(sign.data) - - const { data } = sign - assert(data.httpShareUrl) - }) - - }) -}) - - diff --git a/packages/ali-oss/test/component/23.download.test.ts b/packages/ali-oss/test/component/23.download.test.ts deleted file mode 100644 index e6e87dfdb..000000000 --- a/packages/ali-oss/test/component/23.download.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import assert from 'node:assert/strict' -import { stat } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' - -import { fileShortPath } from '@waiting/shared-core' - -import { cloudUrlPrefix, src, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - describe('Should download() work', () => { - it('normal string', async () => { - const { ossClient } = testConfig - - const target = `${cloudUrlPrefix}/${Date.now().toString()}-tsconfig.json` - - const ret = await ossClient.upload(src, target) - assert(! ret.exitCode, `upload ${src} ${target} failed, ${ret.stderr}`) - assert(ret.data) - - const localFile = join(tmpdir(), `${Date.now().toString()}-tsconfig.json`) - const down = await ossClient.download(target, localFile) - assert(! down.exitCode, `download ${target} ${localFile} failed, ${down.stderr}`) - - const statOri = await stat(src) - const statRet = await stat(localFile) - assert.deepStrictEqual(statRet.size, statOri.size) - }) - }) - -}) - diff --git a/packages/ali-oss/test/component/30.rm.test.ts b/packages/ali-oss/test/component/30.rm.test.ts deleted file mode 100644 index 5071c53f7..000000000 --- a/packages/ali-oss/test/component/30.rm.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { cloudUrlPrefix, src, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - describe('rm should work', () => { - it('normal', async () => { - const { CI, ossClient } = testConfig - - const target = `${cloudUrlPrefix}/${Date.now().toString()}-tsconfig.json` - await ossClient.upload(src, target) - - const ret = await ossClient.rm(target) - CI || console.log(ret) - assert(ret.data) - assert(typeof ret.data.elapsed === 'string') - }) - }) -}) - diff --git a/packages/ali-oss/test/files/.nycrc.json b/packages/ali-oss/test/files/.nycrc.json deleted file mode 100644 index 0d12c44bf..000000000 --- a/packages/ali-oss/test/files/.nycrc.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "include": [ - "src/**/*.ts" - ], - "exclude": [ - ".githooks", - "dist", - "node_modules*", - "src/bin", - "src/domain.ts", - "src/interface.ts", - "test*", - "**/node_modules*", - "**/*.d.ts", - "**/*.js" - ], - "extension": [ - ".ts" - ], - "reporter": [ - "html", - "json", - "text-summary" - ], - "all": true -} diff --git a/packages/ali-oss/test/files/1.txt b/packages/ali-oss/test/files/1.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/packages/ali-oss/test/files/2.txt b/packages/ali-oss/test/files/2.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/packages/ali-oss/test/files/subdir/.nycrc.json b/packages/ali-oss/test/files/subdir/.nycrc.json deleted file mode 100644 index 0d12c44bf..000000000 --- a/packages/ali-oss/test/files/subdir/.nycrc.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "include": [ - "src/**/*.ts" - ], - "exclude": [ - ".githooks", - "dist", - "node_modules*", - "src/bin", - "src/domain.ts", - "src/interface.ts", - "test*", - "**/node_modules*", - "**/*.d.ts", - "**/*.js" - ], - "extension": [ - ".ts" - ], - "reporter": [ - "html", - "json", - "text-summary" - ], - "all": true -} diff --git a/packages/ali-oss/test/files/subdir/1.txt b/packages/ali-oss/test/files/subdir/1.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/packages/ali-oss/test/files/subdir/2.txt b/packages/ali-oss/test/files/subdir/2.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/packages/ali-oss/test/files/subdir/tsconfig.json b/packages/ali-oss/test/files/subdir/tsconfig.json deleted file mode 100644 index 2cb4904f0..000000000 --- a/packages/ali-oss/test/files/subdir/tsconfig.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "declaration": false, - "inlineSourceMap": false, - "noEmit": true, - "noImplicitAny": false, - "noImplicitThis": false, - "noUnusedLocals": false, - "sourceMap": false, - "target": "ESNEXT" - }, - "ts-node": { - "esm": true, - "preferTsExts": true, - "transpileOnly": false - }, - "include": [ - "**/*.ts" - ], - "exclude": [ - "asset/", - "fixtures/", - "node_modules*", - "**/*.d.ts", - "**/*.spec.ts" - ] -} diff --git a/packages/ali-oss/test/files/tsconfig.json b/packages/ali-oss/test/files/tsconfig.json deleted file mode 100644 index 38ca0b13b..000000000 --- a/packages/ali-oss/test/files/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../tsconfig.test.json" -} diff --git "a/packages/ali-oss/test/files/\350\201\224\351\200\232\342\202\254-&a'b^c=.json" "b/packages/ali-oss/test/files/\350\201\224\351\200\232\342\202\254-&a'b^c=.json" deleted file mode 100644 index 4cb45e685..000000000 --- "a/packages/ali-oss/test/files/\350\201\224\351\200\232\342\202\254-&a'b^c=.json" +++ /dev/null @@ -1,22 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": { - "rootDir": "..", - "declaration": false, - "declarationMap": false, - "noEmit": true, - "noImplicitAny": false, - "noImplicitThis": false, - "noPropertyAccessFromIndexSignature": false, - "noUnusedLocals": false, - "rootDir": "..", - "sourceMap": false - }, - "include": [ - "../src/", - "./**/*.ts" - ], - "exclude": [ - "**/*.d.ts" - ], -} diff --git a/packages/ali-oss/test/fixtures/base-app/package.json b/packages/ali-oss/test/fixtures/base-app/package.json deleted file mode 100644 index b9a4ea900..000000000 --- a/packages/ali-oss/test/fixtures/base-app/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "base-app", - "version": "1.0.0", - "type": "module", - "imports": { - "#package.json": "../../../package.json", - "##/*": "../../../dist/*", - "#@/*": "../../../test/*" - }, - "dependencies": { - } -} diff --git a/packages/ali-oss/test/fixtures/base-app/src/configuration.ts b/packages/ali-oss/test/fixtures/base-app/src/configuration.ts deleted file mode 100644 index a239c41da..000000000 --- a/packages/ali-oss/test/fixtures/base-app/src/configuration.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { App, Configuration } from '@midwayjs/core' -import type { Application } from '@mwcp/share' - -import * as SRC from './types/index.js' - - -@Configuration({ - imports: [SRC], -}) -export class AutoConfiguration { - - @App() readonly app: Application - - async onReady(): Promise { - // const foo = this.app.getConfig() as unknown - // void foo - } - -} diff --git a/packages/ali-oss/test/fixtures/base-app/src/home.ts b/packages/ali-oss/test/fixtures/base-app/src/home.ts deleted file mode 100644 index d3e274246..000000000 --- a/packages/ali-oss/test/fixtures/base-app/src/home.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { - Controller, - Get, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import type { Context } from '@mwcp/share' - -import { apiBase, apiMethod } from './types/api-test.js' -import { ConfigKey } from './types/lib-types.js' -import type { Config, MiddlewareConfig } from './types/lib-types.js' -import type { RespData } from './types/root.config.js' - - -@Controller(apiBase.root) -export class HomeController { - - @MConfig(ConfigKey.config) protected readonly config: Config - @MConfig(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig - - @Get(apiMethod.root) - async home(ctx: Context): Promise { - const { - cookies, - header, - url, - } = ctx - - const res = { - cookies, - header, - url, - } - return res - } - -} - diff --git a/packages/ali-oss/test/fixtures/base-app/src/oss.controller.ts b/packages/ali-oss/test/fixtures/base-app/src/oss.controller.ts deleted file mode 100644 index 0ea9ae077..000000000 --- a/packages/ali-oss/test/fixtures/base-app/src/oss.controller.ts +++ /dev/null @@ -1,56 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Init, - Inject, - Post, - Query, -} from '@midwayjs/core' -import { Context } from '@mwcp/share' - -import { apiBase, apiMethod } from './types/api-test.js' -import { - AliOssComponent, - AliOssManager, -} from './types/index.js' -import { ClientKey } from './types/lib-types.js' - - -@Controller(apiBase.oss) -export class OssController { - - @Inject() readonly aliOssManager: AliOssManager - @Inject() readonly ctx: Context - - ossClient: AliOssComponent - - @Init() - async init(): Promise { - this.ossClient = this.aliOssManager.getDataSource(ClientKey.unitTest) - void this.aliOssManager.getDataSource(ClientKey.unitTest) // cov cache - assert(await this.aliOssManager.isConnected(ClientKey.unitTest)) - } - - @Get(`/${apiMethod.stat}`) - @Get(apiMethod.root) - async stat(@Query('target') target: string): Promise> { - const res = await this.ossClient.stat(target) - return res - } - - @Post(`/${apiMethod.mkdir}`) - async mkdir(@Query() parm: { - target: Parameters[0], - opts: Parameters[1], - }): Promise> { - - const { target, opts } = parm - assert(target) - const res = await this.ossClient.mkdir(target, opts) - return res - } - -} - diff --git a/packages/ali-oss/test/fixtures/base-app/src/types/api-test.ts b/packages/ali-oss/test/fixtures/base-app/src/types/api-test.ts deleted file mode 100644 index 5b59da9cd..000000000 --- a/packages/ali-oss/test/fixtures/base-app/src/types/api-test.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../api-test.js' - diff --git a/packages/ali-oss/test/fixtures/base-app/src/types/index.ts b/packages/ali-oss/test/fixtures/base-app/src/types/index.ts deleted file mode 100644 index 3b423e718..000000000 --- a/packages/ali-oss/test/fixtures/base-app/src/types/index.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/index.js' - diff --git a/packages/ali-oss/test/fixtures/base-app/src/types/lib-index.ts b/packages/ali-oss/test/fixtures/base-app/src/types/lib-index.ts deleted file mode 100644 index a776b6f14..000000000 --- a/packages/ali-oss/test/fixtures/base-app/src/types/lib-index.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/lib/index.js' - diff --git a/packages/ali-oss/test/fixtures/base-app/src/types/lib-types.ts b/packages/ali-oss/test/fixtures/base-app/src/types/lib-types.ts deleted file mode 100644 index 0ef106bf2..000000000 --- a/packages/ali-oss/test/fixtures/base-app/src/types/lib-types.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/lib/types.js' - diff --git a/packages/ali-oss/test/fixtures/base-app/src/types/root.config.ts b/packages/ali-oss/test/fixtures/base-app/src/types/root.config.ts deleted file mode 100644 index 1ebbbf75c..000000000 --- a/packages/ali-oss/test/fixtures/base-app/src/types/root.config.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../root.config.js' - diff --git a/packages/ali-oss/test/fixtures/base-app/tsconfig.json b/packages/ali-oss/test/fixtures/base-app/tsconfig.json deleted file mode 100644 index e3e9c84c9..000000000 --- a/packages/ali-oss/test/fixtures/base-app/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "../../..", - "declarationMap": false, - "strictPropertyInitialization": false - }, - "include": [ - "../../../src/**/*.ts", - "../../../test/**/*.ts" - ], - "exclude": [ - "dist", - "node_modules*", - "test", - "**/*.d.ts", - "**/*.spec.ts" - ] -} diff --git a/packages/ali-oss/test/helper.ts b/packages/ali-oss/test/helper.ts deleted file mode 100644 index 78bc1dd43..000000000 --- a/packages/ali-oss/test/helper.ts +++ /dev/null @@ -1,43 +0,0 @@ -import assert from 'node:assert' -import { stat } from 'node:fs/promises' - -import type { AliOssComponent, DataCp } from '../src/index.js' - - -export async function assertFileExists( - client: AliOssComponent, - cloudFile: string, -): Promise { - - const exists = await client.pathExists(cloudFile) - assert(exists === true, `${cloudFile} should exists`) -} - -export function assertUploadFiles( - data: DataCp | undefined, - expectTotalNumber: number, - expectDirs: number, - expectFiles: number, - stderr: string, -): void { - - assert(data) - assert(typeof data.elapsed === 'string', stderr) - assert(typeof data.averageSpeed === 'number', stderr) - assert(typeof data.succeedTotalNumber === 'number', stderr) - assert(data.succeedTotalNumber === expectTotalNumber, stderr) - assert(typeof data.succeedTotalSize === 'string', stderr) - assert(data.succeedTotalSize.length, stderr) - - assert(typeof data.uploadDirs === 'number', stderr) - assert(typeof data.uploadFiles === 'number', stderr) - assert(data.uploadDirs === expectDirs, stderr) - assert(data.uploadFiles === expectFiles, stderr) -} - -export async function assertLocalFileExists(file: string): Promise { - - const exists = (await stat(file)).isFile() - assert(exists === true, `${file} should exists`) -} - diff --git a/packages/ali-oss/test/root.config.ts b/packages/ali-oss/test/root.config.ts deleted file mode 100644 index a81fbb03e..000000000 --- a/packages/ali-oss/test/root.config.ts +++ /dev/null @@ -1,70 +0,0 @@ -import type { IncomingHttpHeaders } from 'node:http' -import { join } from 'node:path' - -import type { Application, IMidwayContainer, JsonResp } from '@mwcp/share' -import { genCurrentDirname } from '@waiting/shared-core' -import type { SuperTest } from 'supertest' -import type supertest from 'supertest' - -import type { AliOssComponent, AliOssManager } from '../src/lib/index.js' - - -export const testDir = genCurrentDirname(import.meta.url) -export const baseDir = join(testDir, '..') - -const CI = !! ((process.env['CI'] - ?? process.env['MIDWAY_SERVER_ENV'] === 'unittest') - || process.env['MIDWAY_SERVER_ENV'] === 'local' - || process.env['NODE_ENV'] === 'unittest' - || process.env['NODE_ENV'] === 'local' -) - -export type TestResponse = supertest.Response -export type TestRespBody = JsonResp -export interface RespData { - header: IncomingHttpHeaders - url: string - cookies: unknown -} - -export interface TestConfig { - baseDir: string - testDir: string - testAppDir: string - CI: boolean - app: Application - container: IMidwayContainer - host: string - httpRequest: SuperTest - aliOssManager: AliOssManager - ossClient: AliOssComponent -} - -const testAppDir = join(testDir, 'fixtures', 'base-app') -export const testConfig = { - baseDir, - testDir, - testAppDir, - CI, - host: '', - httpRequest: {}, -} as TestConfig - - -export const cloudUrlPrefix = 'mobileFile/debug' + Math.random().toString() -export const nameLT = '联通€-&a\'b^c=.json' -export const src = join(testDir, 'tsconfig.json') -export const srcLT = join(testDir, 'files', nameLT) -export const srcDir = join(testDir, 'files') -export const files: string[] = [ - nameLT, - '1.txt', - '2.txt', - '.nycrc.json', - 'tsconfig.json', - 'subdir/1.txt', - 'subdir/2.txt', - 'subdir/.nycrc.json', - 'subdir/tsconfig.json', -] - diff --git a/packages/ali-oss/test/setup.ts b/packages/ali-oss/test/setup.ts deleted file mode 100644 index a815ae03f..000000000 --- a/packages/ali-oss/test/setup.ts +++ /dev/null @@ -1,95 +0,0 @@ -// https://mochajs.org/#global-fixtures -// https://mochajs.org/#root-hook-plugins -import assert from 'node:assert/strict' -import { rm } from 'node:fs/promises' -import { join } from 'node:path' - -import { close, createApp, createHttpRequest } from '@midwayjs/mock' -import type { Application } from '@mwcp/share' -import type { Suite } from 'mocha' - - -import { AliOssManager } from '##/index.js' -import { ClientKey } from '##/lib/types.js' - -import { cloudUrlPrefix, testConfig, testDir } from './root.config.js' -import type { TestConfig } from './root.config.js' - - -let app: Application - -export async function mochaGlobalSetup(this: Suite) { - app = await createAppInstance() - await updateConfig(app, testConfig) - await updateConfig2(app, testConfig) -} - -export async function mochaGlobalTeardown(this: Suite) { - await clean(app, testConfig) - await close(app) -} - - -/** - * Update testConfig in place - */ -async function createAppInstance(): Promise { - try { - app = await createApp(testConfig.testAppDir) as Application - } - catch (ex) { - console.error('createApp error:', ex) - throw ex - } - - assert(app, 'app not exists') - - const middlewares = app.getMiddleware().getNames() - console.info({ middlewares }) - - return app - // https://midwayjs.org/docs/testing -} - -async function updateConfig(mockApp: Application, config: TestConfig): Promise { - config.app = mockApp - config.httpRequest = createHttpRequest(mockApp) - - assert(config.httpRequest, 'httpRequest not exists') - const { url } = config.httpRequest.get('/') - config.host = url - - config.container = mockApp.getApplicationContext() - // const svc = await testConfig.container.getAsync(TaskQueueService) -} - -async function updateConfig2(mockApp: Application, config: TestConfig): Promise { - - const container = mockApp.getApplicationContext() - const aliOssManager = await container.getAsync(AliOssManager) - config.aliOssManager = aliOssManager - - const client = aliOssManager.getDataSource(ClientKey.unitTest) - testConfig.ossClient = client - void aliOssManager.getDataSource(ClientKey.unitTest) // cov cache - - const target = `${cloudUrlPrefix}/` - - await client.rmrf(target) - const ret = await client.mkdir(target) - assert(! ret.exitCode, `mkdir ${target} failed, ${ret.stderr}`) - assert(ret.data) -} - -async function clean(mockApp: Application, config: TestConfig): Promise { - void mockApp - - const { ossClient } = config - const target = `${cloudUrlPrefix}/` - - const ret = await ossClient.rmrf(target) - assert(! ret.exitCode, `mkdir ${target} failed, ${ret.stderr}`) - assert(ret.data) - - await rm(join(config.testDir, 'tmp'), { recursive: true }).catch(() => void 0) -} diff --git a/packages/ali-oss/test/source-manager/111.mkdir.test.ts b/packages/ali-oss/test/source-manager/111.mkdir.test.ts deleted file mode 100644 index 77ca84c03..000000000 --- a/packages/ali-oss/test/source-manager/111.mkdir.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '#@/api-test.js' - -import type { AliOssComponent } from '../../src/index.js' -import { cloudUrlPrefix, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.oss}/${apiMethod.mkdir}` - - describe('should work', () => { - it('normal', async () => { - const { CI, httpRequest } = testConfig - - const target = `${cloudUrlPrefix}/1${Math.random().toString()}/` - const resp = await httpRequest - .post(path) - .query({ target }) - - assert(resp.ok, resp.text) - const data = resp.body as Awaited> - - CI || console.log(data) - - assert(! data.exitCode, `mkdir ${target} failed, ${data.stderr}`) - assert(data.data) - assert(typeof data.data.elapsed === 'string', JSON.stringify(data.data)) - }) - - it('mchar', async () => { - const { CI, httpRequest } = testConfig - - const target = `${cloudUrlPrefix}/联通€-&a'b"ce^f?g*-${Math.random().toString()}/v2/v3/` - const resp = await httpRequest - .post(path) - .query({ target }) - - assert(resp.ok, resp.text) - const data = resp.body as Awaited> - - assert(! data.exitCode, `mkdir ${target} failed, ${data.stderr}`) - assert(data.data) - - assert(typeof data.data.elapsed === 'string') - }) - - }) -}) - diff --git a/packages/ali-oss/test/source-manager/115.stat.test.ts b/packages/ali-oss/test/source-manager/115.stat.test.ts deleted file mode 100644 index 14571bdc7..000000000 --- a/packages/ali-oss/test/source-manager/115.stat.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '#@/api-test.js' - -import type { AliOssComponent } from '../../src/index.js' -import { cloudUrlPrefix, src, testConfig } from '../root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - describe('should work', () => { - it('stat', async () => { - const { CI, httpRequest } = testConfig - - const path = `${apiBase.oss}/${apiMethod.mkdir}` - const target = `${cloudUrlPrefix}/联通€-&a'b"ce^f?g*-${Math.random().toString()}/v2/v3/` - const resp = await httpRequest - .post(path) - .query({ target }) - - assert(resp.ok, resp.text) - const ret = resp.body as Awaited> - - CI || console.log(ret) - assert(! ret.exitCode, `mkdir ${target} failed, ${ret.stderr}`) - assert(ret.data) - // @FIXME - // assert(typeof ret.data.elapsed === 'string') - - const path2 = `${apiBase.oss}/${apiMethod.stat}` - const resp2 = await httpRequest - .get(path2) - .query({ target }) - - assert(resp2.ok, resp2.text) - const ret2 = resp2.body as Awaited> - CI || console.log(ret2) - assert(! ret2.exitCode, `stat ${target} failed, ${ret2.stderr}`) - assert(ret2) - }) - - }) -}) - diff --git a/packages/ali-oss/test/tsconfig.json b/packages/ali-oss/test/tsconfig.json deleted file mode 100644 index cfbe091fd..000000000 --- a/packages/ali-oss/test/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": { - "noEmit": true, - "noImplicitAny": false, - "noImplicitThis": false, - "noPropertyAccessFromIndexSignature": false, - "noUnusedLocals": false, - "rootDir": ".." - }, - "include": [ - "../src/", - "." - ] -} diff --git a/packages/ali-oss/tsconfig.json b/packages/ali-oss/tsconfig.json deleted file mode 100644 index 8890df64a..000000000 --- a/packages/ali-oss/tsconfig.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "./tsconfig.base.json", - "compilerOptions": { - "rootDir": "src" - } -} diff --git a/packages/demo/database/default/ddl/ci-config.sql b/packages/demo/database/default/ddl/ci-config.sql deleted file mode 100644 index 6c945b46a..000000000 --- a/packages/demo/database/default/ddl/ci-config.sql +++ /dev/null @@ -1,5 +0,0 @@ - -SELECT pg_reload_conf(); - --- SET search_path TO "$user", public, pgmq; - diff --git a/packages/demo/database/default/ddl/tb_user.sql b/packages/demo/database/default/ddl/tb_user.sql deleted file mode 100644 index 5edf9b196..000000000 --- a/packages/demo/database/default/ddl/tb_user.sql +++ /dev/null @@ -1,11 +0,0 @@ - --- -CREATE TABLE tb_user ( - uid int8 GENERATED ALWAYS AS IDENTITY NOT NULL, - user_name varchar(60) NOT NULL, - PRIMARY KEY (uid), - ctime TIMESTAMP(6) NOT NULL DEFAULT now(), - mtime TIMESTAMP(6) -); -CREATE INDEX idx_tb_user_user_name ON tb_user(ctime); - diff --git a/packages/demo/database/default/ddl/tb_user_insert.sql b/packages/demo/database/default/ddl/tb_user_insert.sql deleted file mode 100644 index 6db90714e..000000000 --- a/packages/demo/database/default/ddl/tb_user_insert.sql +++ /dev/null @@ -1,5 +0,0 @@ - --- -INSERT INTO tb_user (user_name) VALUES ('admin'); -SELECT * FROM tb_user; - diff --git a/packages/demo/database/default/init.sh b/packages/demo/database/default/init.sh deleted file mode 100644 index f6938bcdc..000000000 --- a/packages/demo/database/default/init.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash -set -e - -echo -e "\n" - -export PGPASSWORD="$POSTGRES_PWD" -psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U$POSTGRES_USER -d $POSTGRES_DB -bq \ - -f ddl/ci-config.sql \ - -f ddl/tb_user.sql \ - -export PGPASSWORD="$DBUSER_PWD" -psql -h $POSTGRES_HOST -p $POSTGRES_PORT -U$DBUSER -d $POSTGRES_DB \ - -f ddl/tb_user_insert.sql \ - diff --git a/packages/demo/database/init-db.sh b/packages/demo/database/init-db.sh deleted file mode 100644 index 73b934dad..000000000 --- a/packages/demo/database/init-db.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -set -e - -echo -e "\n" - -SQL_DIR='default' -cd "$SQL_DIR" -. ./init.sh -cd - - diff --git a/packages/jwt/.editorconfig b/packages/jwt/.editorconfig deleted file mode 100644 index 731bcab2c..000000000 --- a/packages/jwt/.editorconfig +++ /dev/null @@ -1,16 +0,0 @@ -# EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs -# Editor configuration, see http://editorconfig.org - -root = true - -[*] -charset = utf-8 -end_of_line = lf -indent_style = space -indent_size = 2 -insert_final_newline = true -trim_trailing_whitespace = true - -[*.md] -max_line_length = off -trim_trailing_whitespace = false diff --git a/packages/jwt/CHANGELOG.md b/packages/jwt/CHANGELOG.md deleted file mode 100644 index 9cb69fccb..000000000 --- a/packages/jwt/CHANGELOG.md +++ /dev/null @@ -1,993 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. -See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. - -# [41.0.0](https://github.com/waitingsong/midway-components/compare/v40.1.1...v41.0.0) (2024-11-21) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [40.1.1](https://github.com/waitingsong/midway-components/compare/v40.1.0...v40.1.1) (2024-11-12) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [40.1.0](https://github.com/waitingsong/midway-components/compare/v40.0.0...v40.1.0) (2024-11-10) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [40.0.0](https://github.com/waitingsong/midway-components/compare/v39.3.0...v40.0.0) (2024-11-10) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [39.3.0](https://github.com/waitingsong/midway-components/compare/v39.2.0...v39.3.0) (2024-11-06) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [39.2.0](https://github.com/waitingsong/midway-components/compare/v39.1.2...v39.2.0) (2024-11-04) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [39.1.2](https://github.com/waitingsong/midway-components/compare/v39.1.1...v39.1.2) (2024-10-31) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [39.1.1](https://github.com/waitingsong/midway-components/compare/v39.1.0...v39.1.1) (2024-10-30) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [39.1.0](https://github.com/waitingsong/midway-components/compare/v39.0.2...v39.1.0) (2024-10-30) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [39.0.2](https://github.com/waitingsong/midway-components/compare/v39.0.1...v39.0.2) (2024-10-29) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [39.0.1](https://github.com/waitingsong/midway-components/compare/v39.0.0...v39.0.1) (2024-10-29) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [39.0.0](https://github.com/waitingsong/midway-components/compare/v38.4.0...v39.0.0) (2024-10-29) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [38.4.0](https://github.com/waitingsong/midway-components/compare/v38.3.0...v38.4.0) (2024-10-28) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [38.3.0](https://github.com/waitingsong/midway-components/compare/v38.2.3...v38.3.0) (2024-10-28) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [38.2.3](https://github.com/waitingsong/midway-components/compare/v38.2.2...v38.2.3) (2024-10-25) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [38.2.2](https://github.com/waitingsong/midway-components/compare/v38.2.1...v38.2.2) (2024-10-05) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [38.2.1](https://github.com/waitingsong/midway-components/compare/v38.2.0...v38.2.1) (2024-09-15) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [38.2.0](https://github.com/waitingsong/midway-components/compare/v38.1.0...v38.2.0) (2024-09-15) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [38.1.0](https://github.com/waitingsong/midway-components/compare/v38.0.0...v38.1.0) (2024-09-15) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [38.0.0](https://github.com/waitingsong/midway-components/compare/v37.4.1...v38.0.0) (2024-09-14) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [37.4.1](https://github.com/waitingsong/midway-components/compare/v37.4.0...v37.4.1) (2024-09-10) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [37.4.0](https://github.com/waitingsong/midway-components/compare/v37.3.0...v37.4.0) (2024-09-07) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [37.3.0](https://github.com/waitingsong/midway-components/compare/v37.2.4...v37.3.0) (2024-09-04) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [37.2.4](https://github.com/waitingsong/midway-components/compare/v37.2.3...v37.2.4) (2024-09-04) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [37.2.3](https://github.com/waitingsong/midway-components/compare/v37.2.2...v37.2.3) (2024-09-04) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [37.2.2](https://github.com/waitingsong/midway-components/compare/v37.2.1...v37.2.2) (2024-09-04) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [37.2.1](https://github.com/waitingsong/midway-components/compare/v37.2.0...v37.2.1) (2024-08-29) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [37.2.0](https://github.com/waitingsong/midway-components/compare/v37.1.0...v37.2.0) (2024-08-17) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [37.1.0](https://github.com/waitingsong/midway-components/compare/v37.0.0...v37.1.0) (2024-08-16) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [37.0.0](https://github.com/waitingsong/midway-components/compare/v36.1.3...v37.0.0) (2024-08-12) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [36.1.3](https://github.com/waitingsong/midway-components/compare/v36.1.2...v36.1.3) (2024-08-06) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [36.1.2](https://github.com/waitingsong/midway-components/compare/v36.1.1...v36.1.2) (2024-08-06) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [36.1.1](https://github.com/waitingsong/midway-components/compare/v36.1.0...v36.1.1) (2024-08-06) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [36.1.0](https://github.com/waitingsong/midway-components/compare/v36.0.0...v36.1.0) (2024-08-03) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [36.0.0](https://github.com/waitingsong/midway-components/compare/v35.2.1...v36.0.0) (2024-08-02) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [35.2.1](https://github.com/waitingsong/midway-components/compare/v35.2.0...v35.2.1) (2024-08-02) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [35.2.0](https://github.com/waitingsong/midway-components/compare/v35.1.0...v35.2.0) (2024-08-01) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [35.1.0](https://github.com/waitingsong/midway-components/compare/v35.0.1...v35.1.0) (2024-08-01) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [35.0.1](https://github.com/waitingsong/midway-components/compare/v35.0.0...v35.0.1) (2024-07-30) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [35.0.0](https://github.com/waitingsong/midway-components/compare/v34.0.1...v35.0.0) (2024-07-30) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [34.0.1](https://github.com/waitingsong/midway-components/compare/v34.0.0...v34.0.1) (2024-07-30) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [34.0.0](https://github.com/waitingsong/midway-components/compare/v33.0.0...v34.0.0) (2024-07-30) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [33.0.0](https://github.com/waitingsong/midway-components/compare/v32.0.0...v33.0.0) (2024-07-28) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [32.0.0](https://github.com/waitingsong/midway-components/compare/v31.0.0...v32.0.0) (2024-07-24) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [31.0.0](https://github.com/waitingsong/midway-components/compare/v30.21.0...v31.0.0) (2024-07-22) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.21.0](https://github.com/waitingsong/midway-components/compare/v30.20.0...v30.21.0) (2024-07-22) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.20.0](https://github.com/waitingsong/midway-components/compare/v30.19.0...v30.20.0) (2024-07-15) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.19.0](https://github.com/waitingsong/midway-components/compare/v30.18.0...v30.19.0) (2024-07-14) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.18.0](https://github.com/waitingsong/midway-components/compare/v30.17.1...v30.18.0) (2024-07-12) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.17.1](https://github.com/waitingsong/midway-components/compare/v30.17.0...v30.17.1) (2024-07-12) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.17.0](https://github.com/waitingsong/midway-components/compare/v30.16.1...v30.17.0) (2024-07-06) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.16.1](https://github.com/waitingsong/midway-components/compare/v30.16.0...v30.16.1) (2024-07-05) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.16.0](https://github.com/waitingsong/midway-components/compare/v30.15.2...v30.16.0) (2024-07-04) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.15.2](https://github.com/waitingsong/midway-components/compare/v30.15.1...v30.15.2) (2024-07-03) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.15.1](https://github.com/waitingsong/midway-components/compare/v30.15.0...v30.15.1) (2024-07-02) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.15.0](https://github.com/waitingsong/midway-components/compare/v30.14.0...v30.15.0) (2024-07-02) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.14.0](https://github.com/waitingsong/midway-components/compare/v30.13.0...v30.14.0) (2024-06-12) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.13.0](https://github.com/waitingsong/midway-components/compare/v30.12.1...v30.13.0) (2024-06-12) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.12.1](https://github.com/waitingsong/midway-components/compare/v30.12.0...v30.12.1) (2024-06-12) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.12.0](https://github.com/waitingsong/midway-components/compare/v30.11.2...v30.12.0) (2024-06-12) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.11.2](https://github.com/waitingsong/midway-components/compare/v30.11.1...v30.11.2) (2024-06-11) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.11.1](https://github.com/waitingsong/midway-components/compare/v30.11.0...v30.11.1) (2024-06-11) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.11.0](https://github.com/waitingsong/midway-components/compare/v30.10.2...v30.11.0) (2024-06-11) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.10.2](https://github.com/waitingsong/midway-components/compare/v30.10.1...v30.10.2) (2024-06-11) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.10.1](https://github.com/waitingsong/midway-components/compare/v30.10.0...v30.10.1) (2024-06-09) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.10.0](https://github.com/waitingsong/midway-components/compare/v30.9.1...v30.10.0) (2024-06-09) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.9.1](https://github.com/waitingsong/midway-components/compare/v30.9.0...v30.9.1) (2024-06-08) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.9.0](https://github.com/waitingsong/midway-components/compare/v30.8.0...v30.9.0) (2024-06-08) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.5.0](https://github.com/waitingsong/midway-components/compare/v30.4.0...v30.5.0) (2024-06-05) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [30.1.1](https://github.com/waitingsong/midway-components/compare/v30.1.0...v30.1.1) (2024-06-04) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [30.0.0](https://github.com/waitingsong/midway-components/compare/v29.3.1...v30.0.0) (2024-06-02) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [29.3.0](https://github.com/waitingsong/midway-components/compare/v29.2.0...v29.3.0) (2024-05-31) - - -### Features - -* **jwt:** decorator Public() to skip JWT Authentication ([7f72eb1](https://github.com/waitingsong/midway-components/commit/7f72eb14a5b99d359d5814e65984b490c13aecb3)) - - - - - -# [29.2.0](https://github.com/waitingsong/midway-components/compare/v29.1.0...v29.2.0) (2024-05-30) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [29.1.0](https://github.com/waitingsong/midway-components/compare/v29.0.1...v29.1.0) (2024-05-29) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [29.0.1](https://github.com/waitingsong/midway-components/compare/v29.0.0...v29.0.1) (2024-05-28) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [29.0.0](https://github.com/waitingsong/midway-components/compare/v28.2.0...v29.0.0) (2024-05-27) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [28.2.0](https://github.com/waitingsong/midway-components/compare/v28.1.1...v28.2.0) (2024-05-24) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [28.1.1](https://github.com/waitingsong/midway-components/compare/v28.1.0...v28.1.1) (2024-05-24) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [28.0.0](https://github.com/waitingsong/midway-components/compare/v27.0.1...v28.0.0) (2024-05-23) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [27.0.0](https://github.com/waitingsong/midway-components/compare/v26.5.3...v27.0.0) (2024-05-21) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [26.5.2](https://github.com/waitingsong/midway-components/compare/v26.5.1...v26.5.2) (2024-05-09) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [26.5.0](https://github.com/waitingsong/midway-components/compare/v26.4.0...v26.5.0) (2024-04-24) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [26.4.0](https://github.com/waitingsong/midway-components/compare/v26.3.2...v26.4.0) (2024-04-24) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [26.3.2](https://github.com/waitingsong/midway-components/compare/v26.3.1...v26.3.2) (2024-04-24) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [26.3.1](https://github.com/waitingsong/midway-components/compare/v26.3.0...v26.3.1) (2024-04-23) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [26.3.0](https://github.com/waitingsong/midway-components/compare/v26.2.1...v26.3.0) (2024-04-23) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [26.2.0](https://github.com/waitingsong/midway-components/compare/v26.1.0...v26.2.0) (2024-04-22) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [26.0.2](https://github.com/waitingsong/midway-components/compare/v26.0.1...v26.0.2) (2024-04-22) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [26.0.0](https://github.com/waitingsong/midway-components/compare/v25.2.3...v26.0.0) (2024-04-21) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [25.2.3](https://github.com/waitingsong/midway-components/compare/v25.2.2...v25.2.3) (2024-04-14) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [25.2.2](https://github.com/waitingsong/midway-components/compare/v25.2.1...v25.2.2) (2024-04-09) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [25.2.1](https://github.com/waitingsong/midway-components/compare/v25.2.0...v25.2.1) (2024-04-09) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [25.2.0](https://github.com/waitingsong/midway-components/compare/v25.1.0...v25.2.0) (2024-04-09) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [25.1.0](https://github.com/waitingsong/midway-components/compare/v25.0.2...v25.1.0) (2024-04-09) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [25.0.2](https://github.com/waitingsong/midway-components/compare/v25.0.1...v25.0.2) (2024-04-08) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [25.0.1](https://github.com/waitingsong/midway-components/compare/v25.0.0...v25.0.1) (2024-04-08) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [25.0.0](https://github.com/waitingsong/midway-components/compare/v24.2.4...v25.0.0) (2024-04-08) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [24.2.4](https://github.com/waitingsong/midway-components/compare/v24.2.3...v24.2.4) (2024-04-08) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [24.2.3](https://github.com/waitingsong/midway-components/compare/v24.2.2...v24.2.3) (2024-04-08) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [24.2.1](https://github.com/waitingsong/midway-components/compare/v24.2.0...v24.2.1) (2024-04-05) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [24.2.0](https://github.com/waitingsong/midway-components/compare/v24.1.0...v24.2.0) (2024-04-05) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [24.1.0](https://github.com/waitingsong/midway-components/compare/v24.0.0...v24.1.0) (2024-04-05) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [24.0.0](https://github.com/waitingsong/midway-components/compare/v23.2.0...v24.0.0) (2024-04-03) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [23.1.0](https://github.com/waitingsong/midway-components/compare/v23.0.0...v23.1.0) (2024-04-02) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [23.0.0](https://github.com/waitingsong/midway-components/compare/v22.1.2...v23.0.0) (2024-03-27) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [22.1.2](https://github.com/waitingsong/midway-components/compare/v22.1.1...v22.1.2) (2024-03-08) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [22.1.0](https://github.com/waitingsong/midway-components/compare/v22.0.1...v22.1.0) (2024-03-05) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [22.0.1](https://github.com/waitingsong/midway-components/compare/v22.0.0...v22.0.1) (2024-02-26) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [22.0.0](https://github.com/waitingsong/midway-components/compare/v21.1.0...v22.0.0) (2024-02-25) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [21.0.0](https://github.com/waitingsong/midway-components/compare/v20.12.0...v21.0.0) (2024-02-25) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.12.0](https://github.com/waitingsong/midway-components/compare/v20.11.1...v20.12.0) (2024-02-25) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.11.0](https://github.com/waitingsong/midway-components/compare/v20.10.1...v20.11.0) (2024-02-22) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -## [20.10.1](https://github.com/waitingsong/midway-components/compare/v20.10.0...v20.10.1) (2024-02-03) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.10.0](https://github.com/waitingsong/midway-components/compare/v20.9.0...v20.10.0) (2024-02-02) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.9.0](https://github.com/waitingsong/midway-components/compare/v20.8.1...v20.9.0) (2024-01-27) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.8.0](https://github.com/waitingsong/midway-components/compare/v20.7.0...v20.8.0) (2024-01-26) - - -### Features - -* deleteRouter if enableDefaultRoute false ([bc4027e](https://github.com/waitingsong/midway-components/commit/bc4027ed6c4233ee906dee9bae97986ff9f5e1c2)) - - - - - -# [20.7.0](https://github.com/waitingsong/midway-components/compare/v20.6.0...v20.7.0) (2024-01-26) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.6.0](https://github.com/waitingsong/midway-components/compare/v20.5.0...v20.6.0) (2024-01-26) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.5.0](https://github.com/waitingsong/midway-components/compare/v20.4.0...v20.5.0) (2024-01-26) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.3.0](https://github.com/waitingsong/midway-components/compare/v20.2.0...v20.3.0) (2024-01-25) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.2.0](https://github.com/waitingsong/midway-components/compare/v20.1.0...v20.2.0) (2024-01-24) - - -### Features - -* **jwt:** update ignore list ([16dbe85](https://github.com/waitingsong/midway-components/commit/16dbe8563ed4b19dc1094528f9b17415ec39e27f)) - - - - - -# [20.1.0](https://github.com/waitingsong/midway-components/compare/v20.0.2...v20.1.0) (2024-01-24) - -**Note:** Version bump only for package @mwcp/jwt - - - - - -# [20.0.0](https://github.com/waitingsong/midway-components/compare/v19.2.5...v20.0.0) (2024-01-21) - -**Note:** Version bump only for package @mwcp/jwt diff --git a/packages/jwt/LICENSE b/packages/jwt/LICENSE deleted file mode 100644 index 050e16851..000000000 --- a/packages/jwt/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -The MIT License (MIT) - -Copyright (c) waiting - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/jwt/README.md b/packages/jwt/README.md deleted file mode 100644 index 4b172fd83..000000000 --- a/packages/jwt/README.md +++ /dev/null @@ -1,102 +0,0 @@ -# [@mwcp/jwt](https://www.npmjs.com/package/@mwcp/jwt) -Signing, verifying and authentication for midway framework. - - -## Note - -ESM build only, requires `@midwayjs >= 3.16` and set `"type": "module"` in `packages.json` - -## Installation -```sh -npm i @mwcp/jwt -``` - - -## Configuration - -### Enable Plugin - -Edit `${app_root}/src/configuration.ts`: - -```ts -import { join } from 'path' -import { ILifeCycle } from '@midwayjs/core' -import { Configuration } from '@midwayjs/decorator' -import * as jwt from '@mw-components/jwt' - -@Configuration({ - imports: [ - jwt, - ], - importConfigs: [join(__dirname, 'config')], -}) -export class ContainerConfiguration implements ILifeCycle { } - - -declare module '@midwayjs/koa/dist/interface' { - interface Context { - jwtState: JwtState - } -} -export interface User { - uid: string - uname: string -} -``` - -### Add Configurations - -```ts -/* location: ${app_root}/src/config/config.${env}.ts */ - -import { - JwtConfig, - JwtMiddlewareConfig, - initPathArray, -} from '@mw-components/jwt' - -export const jwtConfig: JwtConfig = { - secret: '123456abc', // 默认密钥,生产环境一定要更改! -} -export const jwtMiddlewareConfig: JwtMiddlewareConfig = { - enableMiddleware: true, -} -// OR add extra ignore rules -export const jwtMiddlewareConfig: JwtMiddlewareConfig = { - enableMiddleware: true, - ignore: [ - ...initPathArray, - '/ip', - '/test/sign', - /\/foo\/bar.+/u, - ] -} -``` - -## `Public` Decorator - -No JWT Authentication - -Caution: -- it works even if the route is in the match list -- it will cause some latency when first request for each route - -```ts -import { Public } from '@mwcp/jwt' - -@Controller('/') -export class FooController { - - @Inject() readonly svc: FooService - - @Public() // <-- Set this route public access without jwt authentication - async hello(): Promise { - return 'hello' - } - -} -``` - -## License -[MIT](LICENSE) - diff --git a/packages/jwt/bootstrap.js b/packages/jwt/bootstrap.js deleted file mode 100644 index 01b9c2c35..000000000 --- a/packages/jwt/bootstrap.js +++ /dev/null @@ -1,2 +0,0 @@ -import { Bootstrap } from '@midwayjs/bootstrap'; -await Bootstrap.run(); diff --git a/packages/jwt/package.json b/packages/jwt/package.json deleted file mode 100644 index d2f635dea..000000000 --- a/packages/jwt/package.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "name": "@mwcp/jwt", - "author": "waiting", - "version": "41.0.0", - "description": "midway component jwt", - "keywords": [ - "midway", - "IoC", - "plugin", - "jwt", - "authorization", - "authentication", - "@Public()", - "ts" - ], - "type": "module", - "bin": {}, - "types": "dist/index.d.ts", - "imports": { - "#package.json": "./package.json", - "##/*": "./src/*", - "#@/*": "./test/*" - }, - "exports": { - ".": "./dist/index.js", - "./package.json": "./package.json" - }, - "bugs": { - "url": "https://github.com/waitingsong/midway-components/issues" - }, - "homepage": "https://github.com/waitingsong/midway-components/tree/main/packages/jwt#readme", - "repository": { - "type": "git", - "url": "https://github.com/waitingsong/midway-components" - }, - "license": "MIT", - "dependencies": { - "@midwayjs/info": "^3.20.0", - "@mwcp/share": "^41.0.0", - "@waiting/shared-core": "^23.25.5", - "jsonwebtoken": "^9.0.2" - }, - "devDependencies": { - "@mwcp/otel": "^41.0.0", - "@types/jsonwebtoken": "^9.0.7" - }, - "engines": { - "node": ">=18.12.0", - "@midwayjs/core": ">=3.16.0" - }, - "files": [ - "README.*.md", - "Dockerfile", - "npm-shrinkwrap.json", - "tsconfig.json", - "tsconfig.base.json", - "asset", - "bin", - "database", - "dist", - "src", - "!**/*.spec.*", - "!**/*.tsbuildinfo" - ], - "publishConfig": { - "access": "public" - }, - "scripts": { - "build": "npm run tsc && tsc-alias && npm run rp", - "build:unit": "tsc -p test/tsconfig.json", - "clean": "npm run clean:lock && npm run clean:dist && npm run clean:log", - "clean:cache": "rm -rf .eslintcache .tsbuildinfo", - "clean:dist": "npm run clean:cache && rm -rf dist/*", - "clean:lock": "rm -f package-lock.json", - "clean:log": "rm -rf ./logs ./run", - "cov": "c8 --all npm run test -- --parallel=false", - "dev": "cross-env MIDWAY_SERVER_ENV=local mwtsc --watch --run @midwayjs/mock/app", - "lint": "eslint --fix --cache src test", - "lint:nofix": "eslint --cache src test", - "predev": "npm run build", - "pretest": "npm run build:unit", - "rp": "tsx bin-hashbang.js", - "start": "cross-env NODE_ENV=production node ./bootstrap.js", - "test": "cross-env MIDWAY_SERVER_ENV=unittest TS_NODE_PROJECT=test/tsconfig.json mocha --parallel=false", - "tsc": "tsc -p tsconfig.json" - } -} diff --git a/packages/jwt/src/app/default.controller.ts b/packages/jwt/src/app/default.controller.ts deleted file mode 100644 index 160d6f1c5..000000000 --- a/packages/jwt/src/app/default.controller.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - Controller, - Get, -} from '@midwayjs/core' -import { ApiResponse } from '@midwayjs/swagger' -import { MConfig } from '@mwcp/share' - -import { Config, ConfigKey, Msg } from '##/lib/types.js' - -import { DefaultApi } from './default.types.js' - - - -@Controller(DefaultApi.base) -export class DefaultJwtComponentController { - - @MConfig(ConfigKey.config) private readonly config: Config - - @Get(DefaultApi.hello) - @ApiResponse({ - type: 'string', - description: Msg.hello, - }) - async hello(): Promise { - void this.config - return Msg.hello - } - -} - diff --git a/packages/jwt/src/app/default.types.ts b/packages/jwt/src/app/default.types.ts deleted file mode 100644 index e65cc7bab..000000000 --- a/packages/jwt/src/app/default.types.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { ConfigKey } from '##/lib/types.js' - - -export class DefaultApi { - - static readonly base = `/_${ConfigKey.namespace}` - static readonly hello = '/hello' - -} diff --git a/packages/jwt/src/app/index.controller.ts b/packages/jwt/src/app/index.controller.ts deleted file mode 100644 index 4933eeacb..000000000 --- a/packages/jwt/src/app/index.controller.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from './default.controller.js' - diff --git a/packages/jwt/src/config/config.default.ts b/packages/jwt/src/config/config.default.ts deleted file mode 100644 index b61392bf8..000000000 --- a/packages/jwt/src/config/config.default.ts +++ /dev/null @@ -1,28 +0,0 @@ - -import { - initMiddlewareOptions, - initPathArray, - initialConfig, - initialMiddlewareConfig, -} from '##/lib/config.js' -import type { Config, MiddlewareConfig } from '##/lib/types.js' - - -export const koa = { - port: 7001, -} - -export const jwtConfig: Config = { - ...initialConfig, -} - -export const jwtMiddlewareConfig: Readonly> = { - ...initialMiddlewareConfig, - ignore: [...initPathArray], - options: { - ...initMiddlewareOptions, - cookie: false, - passthrough: false, - }, -} - diff --git a/packages/jwt/src/config/config.local.ts b/packages/jwt/src/config/config.local.ts deleted file mode 100644 index 48e8a35ae..000000000 --- a/packages/jwt/src/config/config.local.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - initMiddlewareOptions, - initPathArray, - initialConfig, - initialMiddlewareConfig, -} from '##/lib/config.js' -import { ConfigKey } from '##/lib/types.js' -import type { Config, MiddlewareConfig } from '##/lib/types.js' - - -export const keys = 123456 - -export const jwtConfig: Config = { - ...initialConfig, - enableDefaultRoute: true, - secret: '123456abc', -} - -export const jwtMiddlewareConfig: Readonly> = { - ...initialMiddlewareConfig, - enableMiddleware: true, - ignore: [ - ...initPathArray, - `/_${ConfigKey.namespace}/hello`, - // /\/test\/.*/u, // do not add, this path will be used for unit test - ], - options: { - ...initMiddlewareOptions, - }, -} - diff --git a/packages/jwt/src/config/config.unittest.ts b/packages/jwt/src/config/config.unittest.ts deleted file mode 100644 index 9e14faa58..000000000 --- a/packages/jwt/src/config/config.unittest.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { - initMiddlewareOptions, - initPathArray, - initialConfig, - initialMiddlewareConfig, -} from '##/lib/config.js' -import { ConfigKey } from '##/lib/types.js' -import type { Config, MiddlewareConfig } from '##/lib/types.js' - - -export const koa = { - port: 7002, -} -export const keys = 123456 - -export const jwtConfig: Config = { - ...initialConfig, - enableDefaultRoute: true, - secret: '123456abc', -} - -export const jwtMiddlewareConfig: Readonly> = { - ...initialMiddlewareConfig, - enableMiddleware: true, - ignore: [ - ...initPathArray, - `/_${ConfigKey.namespace}/hello`, - `/demo/id/:id`, // for test case 100.test.ts - // /\/test\/.*/u, // do not add, this path will be used for unit test - ], - options: { - ...initMiddlewareOptions, - }, -} - diff --git a/packages/jwt/src/configuration.ts b/packages/jwt/src/configuration.ts deleted file mode 100644 index a25758333..000000000 --- a/packages/jwt/src/configuration.ts +++ /dev/null @@ -1,95 +0,0 @@ -import assert from 'node:assert' - -import { - type ILifeCycle, - type ILogger, - App, - Configuration, - Inject, - Logger, - MidwayDecoratorService, - MidwayEnvironmentService, - MidwayInformationService, - MidwayWebRouterService, -} from '@midwayjs/core' -// import { TraceInit } from '@mwcp/otel' -import { - MConfig, - deleteRouter, - registerMiddleware, -} from '@mwcp/share' -import type { Application, IMidwayContainer } from '@mwcp/share' - -import * as DefaultConfig from './config/config.default.js' -import * as LocalConfig from './config/config.local.js' -import * as UnittestConfig from './config/config.unittest.js' -import { useComponents } from './imports.js' -import { ConfigKey } from './lib/types.js' -import type { Config, MiddlewareConfig } from './lib/types.js' -import { JwtMiddleware } from './middleware/index.middleware.js' - - -@Configuration({ - namespace: ConfigKey.namespace, - importConfigs: [ - { - default: DefaultConfig, - local: LocalConfig, - unittest: UnittestConfig, - }, - ], - imports: useComponents, -}) -export class AutoConfiguration implements ILifeCycle { - - @App() readonly app: Application - - @Inject() protected readonly environmentService: MidwayEnvironmentService - @Inject() protected readonly informationService: MidwayInformationService - @Inject() protected readonly decoratorService: MidwayDecoratorService - @Inject() protected readonly webRouterService: MidwayWebRouterService - - @Logger() protected readonly logger: ILogger - - @MConfig(ConfigKey.config) protected readonly config: Config - @MConfig(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig - - async onConfigLoad(): Promise { - /* c8 ignore next 3 */ - if (! this.config.enableDefaultRoute) { - await deleteRouter(`/_${ConfigKey.namespace}`, this.webRouterService) - } - else if (this.mwConfig.ignore) { - this.mwConfig.ignore.push(new RegExp(`/_${ConfigKey.namespace}/.+`, 'u')) - } - } - - // @TraceInit(`INIT ${ConfigKey.componentName}.onReady`) - async onReady(container: IMidwayContainer): Promise { - void container - assert( - this.app, - 'this.app undefined. If start for development, please set env first like `export MIDWAY_SERVER_ENV=local`', - ) - - const { enableMiddleware } = this.mwConfig - if (enableMiddleware || typeof enableMiddleware === 'number') { - registerMiddleware(this.app, JwtMiddleware) - } - } - - async onStop(container: IMidwayContainer): Promise { - void container - this.logger.info(`[${ConfigKey.componentName}] stopping`) - - // const out = 10_000 - // const p1 = new Promise(done => setTimeout(done, out)) - // const p2 = this.dbSourceManager.stop() - // await Promise.race([p1, p2]) - // .catch((ex: Error) => { - // console.error(ex.message) - // }) - this.logger.info(`[${ConfigKey.componentName}] stopped`) - } -} - diff --git a/packages/jwt/src/imports.ts b/packages/jwt/src/imports.ts deleted file mode 100644 index 910964960..000000000 --- a/packages/jwt/src/imports.ts +++ /dev/null @@ -1,28 +0,0 @@ -import * as info from '@midwayjs/info' -import * as koa from '@midwayjs/koa' -import * as swagger from '@midwayjs/swagger' -import * as otel from '@mwcp/otel' -import * as share from '@mwcp/share' - -/* c8 ignore next 5 */ -const CI = !! (process.env['MIDWAY_SERVER_ENV'] === 'unittest' - || process.env['MIDWAY_SERVER_ENV'] === 'local' - || process.env['NODE_ENV'] === 'unittest' - || process.env['NODE_ENV'] === 'local' -) - -export const useComponents: IComponentInfo[] = [] - -useComponents.push(share) -if (CI) { - useComponents.push(koa) - useComponents.push(info) - useComponents.push(swagger) - useComponents.push(otel) -} - -export interface IComponentInfo { - Configuration: unknown - [key: string]: unknown -} - diff --git a/packages/jwt/src/index.ts b/packages/jwt/src/index.ts deleted file mode 100644 index ade1d1a46..000000000 --- a/packages/jwt/src/index.ts +++ /dev/null @@ -1,38 +0,0 @@ - -import type { Config, ConfigKey, MiddlewareConfig } from './lib/types.js' - - -export { AutoConfiguration as Configuration } from './configuration.js' -export * from './app/index.controller.js' -export * from './lib/index.js' -export * from './middleware/index.middleware.js' -export type { - DecodeOptions, - JwtHeader, - Secret, - SignOptions, -} from 'jsonwebtoken' - -declare module '@midwayjs/core/dist/interface.js' { - interface MidwayConfig { - [ConfigKey.config]?: Partial - [ConfigKey.middlewareConfig]?: Partial - } -} - -/* -declare module '@midwayjs/koa/dist/interface' { - interface Context { - jwtState: JwtState - } -} */ - - -export type { - JsonObject, - JsonResp, - JsonType, - NpmPkg, -} from '@waiting/shared-types' - - diff --git a/packages/jwt/src/lib/component.ts b/packages/jwt/src/lib/component.ts deleted file mode 100644 index 8205e63b3..000000000 --- a/packages/jwt/src/lib/component.ts +++ /dev/null @@ -1,215 +0,0 @@ -import assert from 'node:assert' - -import { - Init, - Provide, - Scope, - ScopeEnum, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import { JsonObject } from '@waiting/shared-types' -import JWT from 'jsonwebtoken' -import type { - DecodeOptions, - Secret, - SignOptions, -} from 'jsonwebtoken' - -import { - Config, - ConfigKey, - JwtPayload, - JwtResult, - JwtToken, - Msg, - VerifyOpts, - VerifySecret, -} from './types.js' -import { - validatePayload, - validateSignSecret, - validateTokenString, - validateVerifySecret, -} from './util.js' - - -const { - decode, - sign, - verify, -} = JWT - - -@Provide() -@Scope(ScopeEnum.Singleton) -export class JwtComponent { - - @MConfig(ConfigKey.config) protected readonly config: Config - - private verifySecretSet: Set - - @Init() - async init(): Promise { - const verifySet = processSecret(this.config.verifySecret) - const signSet = processSecret(this.config.secret) - signSet.forEach(val => verifySet.add(val)) - this.verifySecretSet = verifySet - } - - /** - * @description using app.config.jwt.secret if secretOrPrivateKey is undefined or false - */ - sign( - payload: JwtPayload, - secretOrPrivateKey?: Secret, - options?: SignOptions, - ): JwtToken { - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (! this) { throw new TypeError('Should call with class name, such as jwt.foo()') } - - const secret = secretOrPrivateKey - ? secretOrPrivateKey - : this.config.secret - - const opts: SignOptions = options - ? { ...this.config.signOpts, ...options } - : { ...this.config.signOpts } - - validatePayload(payload) - validateSignSecret(secret) - - const ret = sign(payload, secret, opts) - return ret - - } - - - /** - * @description using app.config.jwt.secret if secretOrPrivateKey is undefined or false - */ - verify( - token: JwtToken, - secretOrPrivateKey?: VerifySecret, - options?: VerifyOpts, - ): JwtResult { - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (! this) { throw new TypeError('Should call with class name, such as jwt.verify()') } - - const opts: JWT.VerifyOptions = options - ? { ...this.config.verifyOpts, ...options } - : { ...this.config.verifyOpts } - opts.complete = true - - const secret = secretOrPrivateKey - ? secretOrPrivateKey - : this.config.secret - - validateTokenString(token) - validateVerifySecret(secret) - - const ret = verify(token, secret, opts) - return ret as JwtResult - } - - - /** - * Decode token, - * Warning: This will not verify whether the signature is valid. - * You should not use this for untrusted messages. You most likely want to use jwt.verify instead - * - * @param options value of complete always be TRUE - */ - decode(token: JwtToken): JwtResult { - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (! this) { throw new TypeError('Should call with class name, such as jwt.decode()') } - - const opts: DecodeOptions = { - complete: true, - ...this.config.decodeOpts, - } - const ret = decode(token, opts) - return ret as JwtResult - } - - validateToken( - token: JwtToken, - secretSet: Set, - ): JwtResult { - - /* istanbul ignore next */ - if (! secretSet.size) { throw new Error(Msg.VerifySecretInvalid) } - - const ret: JwtResult[] = [] - const msgs: string[] = [] - Array.from(secretSet).some((secret) => { - try { - const decoded = this.verify(token, secret) - ret.push(decoded) - return true - } - catch { - const ss = typeof secret === 'string' ? secret : secret.toString() - const start = ss.slice(0, 2) - let end = ss - /* istanbul ignore else */ - if (! process.env['CI']) { - end = ss.length > 10 ? ss.slice(-2) : '**' - } - msgs.push(`Error during verify: with secret "${start}****${end}"`) - } - }) - - if (ret.length) { - const resp = ret[0] - assert(resp, 'Should have response') - return resp - } - throw new Error(Msg.TokenValidFailed + ':\n' + msgs.join('\n')) - } - - /** - * Generate secrets for verify, - * Note: use ctxSecret only if available - */ - genVerifySecretSet(ctxSecret?: unknown): Set { - - if (ctxSecret) { - const cs = processSecret(ctxSecret) - /* istanbul ignore else */ - if (cs.size) { - return cs - } - } - return this.verifySecretSet - } - -} - - -function processSecret(input?: unknown): Set { - const ret = new Set() - - /* istanbul ignore else */ - if (typeof input === 'string') { - ret.add(input) - } - else if (Buffer.isBuffer(input)) { - ret.add(input) - } - else if (Array.isArray(input)) { - input.forEach((secret) => { - if (typeof secret === 'string') { - ret.add(secret) - } - else if (Buffer.isBuffer(secret)) { - ret.add(secret) - } - }) - } - - return ret -} - diff --git a/packages/jwt/src/lib/config.ts b/packages/jwt/src/lib/config.ts deleted file mode 100644 index 912b07352..000000000 --- a/packages/jwt/src/lib/config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { Config, MiddlewareConfig, MiddlewareOptions } from './types.js' - - -export const initialConfig: Readonly = { - enableDefaultRoute: false, - secret: '', -} -export const initMiddlewareOptions: MiddlewareOptions = { - debug: false, - cookie: false, - passthrough: false, -} -export const initialMiddlewareConfig: Readonly> = { - enableMiddleware: true, - options: { - debug: false, - cookie: false, - passthrough: false, - }, -} - -export const initPathArray = [ - '/', - '/auth/login', - '/login', - '/metrics', - '/ping', - '/favicon.ico', - '/favicon.png', - /\/swagger-ui\/.+(html|json|js|css|png|ico)#?/u, -] - -export const schemePrefix = 'Bearer' - -export const DECORATOR_KEY_Public = 'decorator_key_jwt:public' - diff --git a/packages/jwt/src/lib/decorator.public/index.decorator.ts b/packages/jwt/src/lib/decorator.public/index.decorator.ts deleted file mode 100644 index 7d2602d5e..000000000 --- a/packages/jwt/src/lib/decorator.public/index.decorator.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from './public.decorator-handler.js' -export * from './public.decorator.js' diff --git a/packages/jwt/src/lib/decorator.public/public.decorator-handler.ts b/packages/jwt/src/lib/decorator.public/public.decorator-handler.ts deleted file mode 100644 index 1734e7bd1..000000000 --- a/packages/jwt/src/lib/decorator.public/public.decorator-handler.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/no-unsafe-argument */ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ -import assert from 'node:assert' - -import { - CONTROLLER_KEY, - Init, - Singleton, - WEB_ROUTER_KEY, - getClassMetadata, - listModule, -} from '@midwayjs/core' -import { - ConfigKey as ShareConfigKey, - DecoratorHandlerBase, - MConfig, - MiddlewarePathPattern, - instanceMethodHasMethodDecorator, -} from '@mwcp/share' - -import { DECORATOR_KEY_Public } from '../config.js' -import { Config, ConfigKey, MiddlewareConfig } from '../types.js' - - -@Singleton() -export class DecoratorHandlerPublic extends DecoratorHandlerBase { - @MConfig(ConfigKey.config) protected readonly config: Config - @MConfig(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig - - @MConfig(ShareConfigKey.routerInfoConfig) protected readonly routerInfoConfig: { enable: boolean } - - @Init() - async init() { - if (! this.mwConfig.enableMiddleware) { return } - - this.enableRouterInfo() - this.processIgnoreList() - } - - - // #region private methods - - private enableRouterInfo(): void { - if (! this.routerInfoConfig.enable) { - this.routerInfoConfig.enable = true - } - } - - private processIgnoreList(): void { - const arr: MiddlewarePathPattern = [] - listModule(CONTROLLER_KEY).forEach((module) => { - const list = this.genList(module) - if (list.length) { - arr.push(...list) - } - }) - - if (arr.length) { - this.mwConfig.ignore = this.mwConfig.ignore ? arr.concat(this.mwConfig.ignore) : arr - } - } - - private genList(module: unknown): MiddlewarePathPattern { - const { mwConfig } = this - const ret: MiddlewarePathPattern = [] - - const { prefix } = getClassMetadata( - CONTROLLER_KEY, - module, - ) - if (! prefix) { - return ret - } - assert(typeof prefix === 'string', 'prefix must be string') - - const webRouterInfo: unknown[] = getClassMetadata( - WEB_ROUTER_KEY, - module, - ) - // console.info({ webRouterInfo }) - webRouterInfo.forEach((info) => { - const { method, path } = info as any - // @ts-expect-error - module - const isDecorated = instanceMethodHasMethodDecorator(module, DECORATOR_KEY_Public, method) - if (! isDecorated) { return } - - const needle = `${prefix}${path}` - - if (mwConfig.match?.includes(needle)) { // remove needle from match - mwConfig.match = mwConfig.match.filter(val => val !== needle) - } - - if (! mwConfig.ignore || mwConfig.ignore.includes(needle)) { return } - ret.push(needle) - }) - - return ret - } - -} - diff --git a/packages/jwt/src/lib/decorator.public/public.decorator.ts b/packages/jwt/src/lib/decorator.public/public.decorator.ts deleted file mode 100644 index 7ea9df002..000000000 --- a/packages/jwt/src/lib/decorator.public/public.decorator.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { customDecoratorFactory } from '@mwcp/share' - -import { DECORATOR_KEY_Public } from '../config.js' - -import { DecoratorHandlerPublic } from './public.decorator-handler.js' - - -/** - * No JWT Authentication - * @Caution - * - it works even if the route is in the match list - * - it will cause some latency when first request for each route - */ -export function Public(): MethodDecorator { - return customDecoratorFactory({ - decoratorArgs: void 0, - decoratorKey: DECORATOR_KEY_Public, - enableClassDecorator: false, - decoratorHandlerClass: DecoratorHandlerPublic, - }) -} - diff --git a/packages/jwt/src/lib/index.ts b/packages/jwt/src/lib/index.ts deleted file mode 100644 index 0f30d21b3..000000000 --- a/packages/jwt/src/lib/index.ts +++ /dev/null @@ -1,24 +0,0 @@ - -export * from './config.js' -export * from './resolvers.js' -export * from './util.js' -export { JwtComponent } from './component.js' -export * from './decorator.public/index.decorator.js' - -export { - type Config as JwtConfig, - - type JwtPayload, - type JwtResult, - type JwtState, - type MiddlewareConfig as JwtMiddlewareConfig, - type MiddlewareOptions as JwtMiddlewareOptions, - type PassthroughCallback, - type RedirectURL, - type VerifyOpts, - type VerifySecret, - ConfigKey as JwtConfigKey, - Msg as JwtMsg, -} from './types.js' - - diff --git a/packages/jwt/src/lib/resolvers.ts b/packages/jwt/src/lib/resolvers.ts deleted file mode 100644 index 8122921b7..000000000 --- a/packages/jwt/src/lib/resolvers.ts +++ /dev/null @@ -1,124 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unnecessary-condition */ - -import type { Context } from '@mwcp/share' - -import { schemePrefix } from './config.js' -import type { JwtAuthenticateOptions, JwtToken } from './types.js' - - -/** - * - * Note: trim trailing white space from cookies/header, - * according to node.js security since v10.19, v12.15 - * @link https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/ - */ -export function retrieveToken(ctx: Context, cookieKey: JwtAuthenticateOptions['cookie']): JwtToken { - let token = resolveFromCookies(ctx.cookies, cookieKey) - - if (token) { - token = token.trimEnd() - } - else if (ctx?.header?.cookie) { - token = pickTokenFromHeaderCookies(ctx.header.cookie, cookieKey ?? false) - } - - if (token) { - token = token.trimEnd() - } - else { - // eslint-disable-next-line @typescript-eslint/prefer-optional-chain - let authorization: string = ctx.header && ctx.header.authorization - ? ctx.header.authorization - : '' - if (authorization) { - authorization = authorization.trimEnd() - token = resolveFromAuthorizationHeader(authorization) - } - else { - token = '' - } - } - - return token ? token : '' -} - - -/** - * Attempts to parse the token from the Authorization header, - * This function checks the Authorization header for a `Bearer ` pattern and return the token section - * - * @param authorization from ctx.header.authorization - */ -export function resolveFromAuthorizationHeader(authorization: string): JwtToken { - if (typeof authorization !== 'string' || ! authorization) { - return '' - } - - const parts = authorization.split(/ +/u) - - if (parts.length === 2) { - const [scheme, credentials] = parts - - if (scheme && scheme === schemePrefix) { - return credentials ? credentials : '' - } - } - - return '' -} - - -/** - * Attempts to retrieve the token from a cookie, - * This function uses the opts.cookie option to retrieve the token - */ -export function resolveFromCookies( - cookies: Context['cookies'], - cookieKey?: JwtAuthenticateOptions['cookie'], -): JwtToken | undefined { - - if (! cookieKey) { - return '' - } - - - const token = cookies && typeof cookies.get === 'function' - - ? cookies.get(cookieKey) - : '' - return token -} - -export function pickTokenFromHeaderCookies( - cookie: string | string[], - key: string | false, -): string { - - if (! key) { - return '' - } - - if (typeof cookie === 'string') { - return pickTokenFromCookie(cookie, key) - } - else { - for (const line of cookie) { - const token = pickTokenFromCookie(line, key) - if (token) { - return token - } - } - } - - return '' -} - -function pickTokenFromCookie( - cookie: string, - key: string, -): string { - - const re = new RegExp(`(?<=\\b${key}=)[\\w\\d.]+`, 'u') - const match = re.exec(cookie) - return match && Array.isArray(match) && match[0] ? match[0] : '' -} diff --git a/packages/jwt/src/lib/types.ts b/packages/jwt/src/lib/types.ts deleted file mode 100644 index f20687e45..000000000 --- a/packages/jwt/src/lib/types.ts +++ /dev/null @@ -1,96 +0,0 @@ -import type { Context } from '@mwcp/share' -import type { JsonObject, MiddlewareConfig as MWConfig } from '@waiting/shared-types' -import type { DecodeOptions, JwtHeader, Secret, SignOptions, VerifyOptions } from 'jsonwebtoken' - - -export enum ConfigKey { - namespace = 'jwt', - config = 'jwtConfig', - middlewareConfig = 'jwtMiddlewareConfig', - componentName = 'jwtComponent', - middlewareName = 'jwtMiddleware', -} - -export enum Msg { - hello = 'hello jwt', - AuthFailed = 'Authentication Failed', - - InvalidInput = 'Value of input invalid', - InvalidInputBuffer = 'Value of input is empty Buffer', - InvalidInputObject = 'Value of input is invalid Object', - InvalidInputString = 'Value of input is blank string', - - VerifyNotFunc = 'jwt.verify is not a function', - TokenNotFound = 'Token not found. Header format is "Authorization: Bearer "', - TokenValidFailed = 'Token validation failed', - VerifySecretInvalid = 'VerifySecret not provided', -} - - -export interface Config { - /** - * Enable default http route, eg. /hello - * @default false - */ - enableDefaultRoute?: boolean | undefined - /** - * For signing and verifying if without passing secret param, - * Note: the type of VerifySecret without object - */ - secret: Secret - /** Authentication options for middleware */ - decodeOpts?: DecodeOptions - signOpts?: SignOptions - verifySecret?: VerifySecret | VerifySecret[] - verifyOpts?: VerifyOpts -} - - -/** Authentication options for middleware */ -export interface MiddlewareOptions { - debug?: boolean | undefined - /** - * Retrieving the token from the name of cookie, instead of from HTTP header (Authorization), - * @default false - */ - cookie?: string | false | undefined - /** - * - false (Default): throw error - * - true: always yield next, even if no valid Authorization header was found, - * and ignore value of JwtOptions.debug - * - : redirect and without yield next - * @default false - */ - passthrough?: boolean | RedirectURL | PassthroughCallback | undefined -} -export type MiddlewareConfig = MWConfig -export type JwtAuthenticateOptions = MiddlewareOptions - - -export type JwtToken = string -export type JwtPayload = string | Buffer | JsonObject -export interface JwtResult { - header: JwtHeader - payload: T - signature: string -} - -export type VerifySecret = string | Buffer -export type VerifyOpts = Omit - -// export type MiddlewarePathPattern = (string | RegExp | PathPatternFunc)[] -// export type PathPatternFunc = (ctx: Context) => boolean -export type RedirectURL = string -export type PassthroughCallback = (ctx: Context) => Promise - - -/** Bind on Context.jwtState */ -export interface JwtState { - header?: JwtHeader - secret?: unknown - signature?: string - /** Decode Result */ - user?: JwtResult['payload'] - jwtOriginalError?: Error -} - diff --git a/packages/jwt/src/lib/util.ts b/packages/jwt/src/lib/util.ts deleted file mode 100644 index 6acd4fd47..000000000 --- a/packages/jwt/src/lib/util.ts +++ /dev/null @@ -1,74 +0,0 @@ -import assert from 'node:assert' -import { KeyObject } from 'node:crypto' - -import { Msg } from './types.js' -import type { Config, JwtPayload, JwtToken } from './types.js' - - -export function validateTokenString(input: JwtToken): void { - if (typeof input === 'string') { - assert(input.length > 0) - } - else { - throw new TypeError(Msg.InvalidInput) - } -} - - -export function validatePayload(input: JwtPayload): void { - if (typeof input === 'string') { - assert(input.length > 0, Msg.InvalidInputString) - return - } - else if (Buffer.isBuffer(input)) { - assert(input.length > 0, Msg.InvalidInputBuffer) - } - else if (typeof input === 'object') { - assert(Object.keys(input).length > 0) - } - else { - throw new TypeError(Msg.InvalidInput) - } - -} - - -export function validateSignSecret(input: Config['secret']): void { - if (typeof input === 'string') { - assert(input.length > 0, Msg.InvalidInputString) - return - } - else if (Buffer.isBuffer(input)) { - assert(input.length > 0, Msg.InvalidInputBuffer) - } - else if (input instanceof KeyObject) { - assert(input.type) - } - else if (typeof input === 'object') { - assert(Object.keys(input).length > 0) - const prop = Object.getOwnPropertyDescriptor(input, 'key') - assert(prop, 'key property not found') - // assert(typeof input.key === 'string' && input.key.length > 0) - assert(typeof input.key === 'string' || Buffer.isBuffer(input.key)) - assert(typeof input.passphrase === 'string') - } - else { - throw new TypeError(Msg.InvalidInput) - } -} - - -export function validateVerifySecret(input: unknown): void { - if (typeof input === 'string') { - assert(input.length > 0, Msg.InvalidInputString) - } - else if (Buffer.isBuffer(input)) { - assert(input.length > 0, Msg.InvalidInputBuffer) - } - // else if (typeof input === 'function') { // promise callback - // return - // } - else { - throw new TypeError(Msg.InvalidInput) - } -} diff --git a/packages/jwt/src/middleware/index.middleware.ts b/packages/jwt/src/middleware/index.middleware.ts deleted file mode 100644 index f0dfc2143..000000000 --- a/packages/jwt/src/middleware/index.middleware.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from './jwt.middleware.js' - diff --git a/packages/jwt/src/middleware/jwt.middleware.ts b/packages/jwt/src/middleware/jwt.middleware.ts deleted file mode 100644 index 595a0cf33..000000000 --- a/packages/jwt/src/middleware/jwt.middleware.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { Middleware } from '@midwayjs/core' -import { - Context, - IMiddleware, - NextFunction, - requestPathMatched, -} from '@mwcp/share' - -import { JwtComponent } from '##/lib/component.js' -import { retrieveToken } from '##/lib/resolvers.js' -import { - ConfigKey, - JwtAuthenticateOptions, - JwtState, - MiddlewareConfig, - Msg, - RedirectURL, - VerifySecret, -} from '##/lib/types.js' - - -@Middleware() -export class JwtMiddleware implements IMiddleware { - - static getName(): string { - const name = ConfigKey.middlewareName - return name - } - - match(ctx?: Context) { - if (ctx) { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (! ctx.state) { - ctx.state = {} - } - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (! ctx['jwtState']) { - ctx['jwtState'] = {} as JwtState - } - - const mwConfig = ctx.app.getConfig(ConfigKey.middlewareConfig) as MiddlewareConfig - const path = ctx._routerInfo?.fullUrl ?? ctx.path - const flag = requestPathMatched(path, mwConfig) - return flag - } - - return false - } - - resolve() { - return middleware - } - -} - -export async function middleware( - ctx: Context, - next: NextFunction, -): Promise { - - const { app } = ctx - - const mwConfig = app.getConfig(ConfigKey.middlewareConfig) as MiddlewareConfig - const { options } = mwConfig - if (! options) { - console.error('[JWT] mwConfig.options undefined') - throw new TypeError('options undefined') - } - const { debug, cookie, passthrough } = options - - try { - const token = retrieveToken(ctx, cookie) - - if (! token) { - throw new Error(Msg.TokenNotFound) - } - - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const secretSet: Set = svc.genVerifySecretSet(ctx['jwtState'].secret ?? ctx.state['secret']) - const decoded = svc.validateToken(token, secretSet) - - ctx['jwtState'].header = decoded.header - ctx['jwtState'].signature = decoded.signature - ctx['jwtState'].user = decoded.payload - - - ctx.state['user'] = decoded.payload - if (typeof ctx.status === 'undefined') { - ctx.status = 200 - } - } - catch (ex) { - const pass = await parseByPassthrough(ctx, passthrough) - if (pass === true) { - // lets downstream middlewares handle JWT exceptions - // lets downstream middlewares handle JWT exceptions - ctx['jwtState'].jwtOriginalError = ex as Error - - - ctx.state['jwtOriginalError'] = ex as Error - if (typeof ctx.status === 'undefined') { - ctx.status = 200 - } - } - else if (typeof pass === 'string' && pass.length > 0) { - ctx.redirect(pass) - return - } - else { - const msg = debug === true ? (ex as Error).message : Msg.AuthFailed - ctx.status = 401 - if (typeof ctx.throw === 'function') { - ctx.throw(401, msg, { originalError: ex }) - } - else { - throw new TypeError(msg) - } - } - } - - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return next() -} - - - -/** Compute passthrough state */ -async function parseByPassthrough( - ctx: Context, - input: JwtAuthenticateOptions['passthrough'], -): Promise { - - switch (typeof input) { - case 'boolean': - return input - - case 'string': - return input - - case 'function': - return input(ctx) - - default: - return false - } -} - diff --git a/packages/jwt/test/00.dummy.test.ts b/packages/jwt/test/00.dummy.test.ts deleted file mode 100644 index 0dc314d66..000000000 --- a/packages/jwt/test/00.dummy.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('should work', () => { - it('always passed', () => { - assert(testConfig) - }) - }) - -}) - diff --git a/packages/jwt/test/01.index.test.ts b/packages/jwt/test/01.index.test.ts deleted file mode 100644 index 178dd01e3..000000000 --- a/packages/jwt/test/01.index.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { useComponents } from '##/imports.js' -import * as Foo from '##/index.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('should work', () => { - it('index', () => { - assert(Foo) - }) - - it('useComponents', () => { - assert(Array.isArray(useComponents)) - }) - - it('testAppDir eq testConfig.testAppDir', () => { - const { app } = testConfig - assert(app) - - const appDir = app.getAppDir() - assert(appDir) - assert(appDir === testConfig.testAppDir) - }) - }) - -}) - diff --git a/packages/jwt/test/02.home.test.ts b/packages/jwt/test/02.home.test.ts deleted file mode 100644 index 730f8b91e..000000000 --- a/packages/jwt/test/02.home.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { ConfigKey, Msg } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' -import type { RespData, TestRespBody } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - const helloPath = `${apiBase.prefix}/${apiMethod.hello}` - - it(`Should ${apiBase.root} work`, async () => { - const { app, httpRequest } = testConfig - - const resp = await httpRequest.get(apiBase.root) - assert(resp.ok, resp.text) - - const ret = resp.body as TestRespBody | RespData - assert(typeof ret === 'object', JSON.stringify(ret, null, 2)) - - if ('code' in ret && typeof ret.code === 'number') { - assert(ret.code === 0) - assert(typeof ret.data === 'object', JSON.stringify(ret, null, 2)) - - const { url, header } = ret.data - const { host } = header - assert(url === '/', JSON.stringify(ret, null, 2)) - assert(host && testConfig.host.includes(host), JSON.stringify(ret, null, 2)) - } - else { - const { url, header } = ret as RespData - const { host } = header - assert(url === '/', JSON.stringify(ret, null, 2)) - assert(host && testConfig.host.includes(host), JSON.stringify(ret, null, 2)) - } - }) - - it(`Should ${helloPath} work`, async () => { - const { app, httpRequest } = testConfig - - const resp = await httpRequest.get(helloPath) - assert(resp.ok, resp.text) - - const ret = resp.text - assert(ret.includes(Msg.hello), JSON.stringify(ret, null, 2)) - }) - -}) - diff --git a/packages/jwt/test/api-test.ts b/packages/jwt/test/api-test.ts deleted file mode 100644 index c7059e7c8..000000000 --- a/packages/jwt/test/api-test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { ConfigKey } from '##/lib/types.js' - - -export const apiBase = { - root: '/', - prefix: `/_${ConfigKey.namespace}`, - demo: '/demo', -} - -export const apiMethod = { - root: '/', - hello: 'hello', - component: 'component', - home2: 'home2', - test: 'test', - id: 'id', -} diff --git a/packages/jwt/test/decorator/100.test.ts b/packages/jwt/test/decorator/100.test.ts deleted file mode 100644 index 9b25d2e79..000000000 --- a/packages/jwt/test/decorator/100.test.ts +++ /dev/null @@ -1,26 +0,0 @@ - -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `${apiBase.demo}/${apiMethod.id}` - - it(path, async () => { - const { httpRequest } = testConfig - - const url = path + '/123' - const resp = await httpRequest.get(url) - assert(resp.ok, resp.text) - - const res = resp.text - assert(res === 'OK') - }) - -}) - diff --git a/packages/jwt/test/fixtures/base-app/package.json b/packages/jwt/test/fixtures/base-app/package.json deleted file mode 100644 index b9a4ea900..000000000 --- a/packages/jwt/test/fixtures/base-app/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "base-app", - "version": "1.0.0", - "type": "module", - "imports": { - "#package.json": "../../../package.json", - "##/*": "../../../dist/*", - "#@/*": "../../../test/*" - }, - "dependencies": { - } -} diff --git a/packages/jwt/test/fixtures/base-app/src/100.controller.ts b/packages/jwt/test/fixtures/base-app/src/100.controller.ts deleted file mode 100644 index a8e3f65cf..000000000 --- a/packages/jwt/test/fixtures/base-app/src/100.controller.ts +++ /dev/null @@ -1,33 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Param, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from './types/api-test.js' -import { Public } from './types/index.js' -import { - Config, - ConfigKey, - MiddlewareConfig, -} from './types/lib-types.js' - - -@Controller(apiBase.demo) -export class PublicTestController { - - @MConfig(ConfigKey.config) protected readonly config: Config - @MConfig(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig - - @Public() - @Get(`/${apiMethod.id}/:id`) - async simple(@Param('id') id: number): Promise<'OK'> { - assert(typeof id === 'number', 'id must be number') - return 'OK' - } - -} - diff --git a/packages/jwt/test/fixtures/base-app/src/configuration.ts b/packages/jwt/test/fixtures/base-app/src/configuration.ts deleted file mode 100644 index a239c41da..000000000 --- a/packages/jwt/test/fixtures/base-app/src/configuration.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { App, Configuration } from '@midwayjs/core' -import type { Application } from '@mwcp/share' - -import * as SRC from './types/index.js' - - -@Configuration({ - imports: [SRC], -}) -export class AutoConfiguration { - - @App() readonly app: Application - - async onReady(): Promise { - // const foo = this.app.getConfig() as unknown - // void foo - } - -} diff --git a/packages/jwt/test/fixtures/base-app/src/home.ts b/packages/jwt/test/fixtures/base-app/src/home.ts deleted file mode 100644 index d3e274246..000000000 --- a/packages/jwt/test/fixtures/base-app/src/home.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { - Controller, - Get, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import type { Context } from '@mwcp/share' - -import { apiBase, apiMethod } from './types/api-test.js' -import { ConfigKey } from './types/lib-types.js' -import type { Config, MiddlewareConfig } from './types/lib-types.js' -import type { RespData } from './types/root.config.js' - - -@Controller(apiBase.root) -export class HomeController { - - @MConfig(ConfigKey.config) protected readonly config: Config - @MConfig(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig - - @Get(apiMethod.root) - async home(ctx: Context): Promise { - const { - cookies, - header, - url, - } = ctx - - const res = { - cookies, - header, - url, - } - return res - } - -} - diff --git a/packages/jwt/test/fixtures/base-app/src/home2.ts b/packages/jwt/test/fixtures/base-app/src/home2.ts deleted file mode 100644 index 335b7deff..000000000 --- a/packages/jwt/test/fixtures/base-app/src/home2.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { - Controller, - Get, -} from '@midwayjs/core' -import { Context, MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from './types/api-test.js' -import { - Config, - ConfigKey, - MiddlewareConfig, -} from './types/lib-types.js' -import { RespData } from './types/root.config.js' - - -@Controller(apiBase.root) -export class HomeController { - - @MConfig(ConfigKey.config) protected readonly config: Config - @MConfig(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig - - @Get('/home2') - async home2(ctx: Context): Promise { - const { - cookies, - header, - url, - jwtState, - } = ctx - const config = this.config - const mwConfig = this.mwConfig - const res = { - config, - mwConfig, - cookies, - header, - url, - jwtState, - jwtOriginalErrorText: '', - } - if (jwtState.jwtOriginalError) { - res.jwtOriginalErrorText = jwtState.jwtOriginalError.message - } - return res - } - - @Get(`/${apiMethod.test}`) - async test(ctx: Context): Promise { - const { jwtState, cookies, header, url } = ctx - const config = this.config - const mwConfig = this.mwConfig - const res = { - config, - mwConfig, - cookies, - header, - url, - jwtState, - jwtOriginalErrorText: '', - } - if (jwtState.jwtOriginalError) { - res.jwtOriginalErrorText = jwtState.jwtOriginalError.message - } - return res - } - -} - diff --git a/packages/jwt/test/fixtures/base-app/src/types/api-test.ts b/packages/jwt/test/fixtures/base-app/src/types/api-test.ts deleted file mode 100644 index 5b59da9cd..000000000 --- a/packages/jwt/test/fixtures/base-app/src/types/api-test.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../api-test.js' - diff --git a/packages/jwt/test/fixtures/base-app/src/types/index.ts b/packages/jwt/test/fixtures/base-app/src/types/index.ts deleted file mode 100644 index 3b423e718..000000000 --- a/packages/jwt/test/fixtures/base-app/src/types/index.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/index.js' - diff --git a/packages/jwt/test/fixtures/base-app/src/types/lib-index.ts b/packages/jwt/test/fixtures/base-app/src/types/lib-index.ts deleted file mode 100644 index a776b6f14..000000000 --- a/packages/jwt/test/fixtures/base-app/src/types/lib-index.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/lib/index.js' - diff --git a/packages/jwt/test/fixtures/base-app/src/types/lib-types.ts b/packages/jwt/test/fixtures/base-app/src/types/lib-types.ts deleted file mode 100644 index 0ef106bf2..000000000 --- a/packages/jwt/test/fixtures/base-app/src/types/lib-types.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/lib/types.js' - diff --git a/packages/jwt/test/fixtures/base-app/src/types/root.config.ts b/packages/jwt/test/fixtures/base-app/src/types/root.config.ts deleted file mode 100644 index 1ebbbf75c..000000000 --- a/packages/jwt/test/fixtures/base-app/src/types/root.config.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../root.config.js' - diff --git a/packages/jwt/test/fixtures/base-app/tsconfig.json b/packages/jwt/test/fixtures/base-app/tsconfig.json deleted file mode 100644 index e3e9c84c9..000000000 --- a/packages/jwt/test/fixtures/base-app/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "../../..", - "declarationMap": false, - "strictPropertyInitialization": false - }, - "include": [ - "../../../src/**/*.ts", - "../../../test/**/*.ts" - ], - "exclude": [ - "dist", - "node_modules*", - "test", - "**/*.d.ts", - "**/*.spec.ts" - ] -} diff --git a/packages/jwt/test/jwt-component/decode.test.ts b/packages/jwt/test/jwt-component/decode.test.ts deleted file mode 100644 index 0d0982c79..000000000 --- a/packages/jwt/test/jwt-component/decode.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { jwtConfig } from '##/config/config.unittest.js' -import { JwtComponent } from '##/index.js' -import { - payload1, - - - signature1, - token1, -} from '#@/mock-data.js' -import type { PayloadExt1, PayloadSig1 } from '#@/mock-data.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('Should Jwt:decode() work', () => { - it('normal string', async () => { - const { app } = testConfig - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const input = 'fooabc' + Math.random().toString() - const token = svc.sign(input, jwtConfig.secret) - const ret = svc.decode(token) - assert(ret.payload === input) - }) - - it('various generics types', async () => { - const { app } = testConfig - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const token = svc.sign(payload1, jwtConfig.secret) - - const ret1 = svc.decode(token) // index signature - const ret2 = svc.decode(token) // extends from - const ret3 = svc.decode(token) // pick type - const ret4 = svc.decode(token) // default json type - - assert.deepStrictEqual(ret1.payload, payload1) - assert.deepStrictEqual(ret2.payload, payload1) - assert.deepStrictEqual(ret3.payload, payload1) - assert.deepStrictEqual(ret4.payload, payload1) - }) - - it('pass secret', async () => { - const { app } = testConfig - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const token = svc.sign(payload1, jwtConfig.secret) - const ret = svc.decode(token) - const { header, payload, signature } = ret - - assert(header && header.alg === 'HS256') - assert(header.typ === 'JWT') - assert(signature === signature1) - assert.deepStrictEqual(payload, payload1) - }) - - it('with invalid scope', async () => { - const { app } = testConfig - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - // eslint-disable-next-line @typescript-eslint/unbound-method - const { decode } = svc - try { - decode(token1) - } - catch (ex) { - return assert(ex instanceof TypeError) - } - assert(false, 'Should throw error but NOT.') - }) - }) -}) diff --git a/packages/jwt/test/jwt-component/sign.test.ts b/packages/jwt/test/jwt-component/sign.test.ts deleted file mode 100644 index b8777f164..000000000 --- a/packages/jwt/test/jwt-component/sign.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { jwtConfig } from '##/config/config.unittest.js' -import { JwtComponent } from '##/index.js' -import { - payload1, - payload2, - token1, - tokenHeader2, -} from '#@/mock-data.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('Should Jwt:sign() work', () => { - - it('initializ secret', async () => { - const { app } = testConfig - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const token = svc.sign(payload1) - assert(token === token1) - }) - - it('pass secret', async () => { - const { app } = testConfig - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const token = svc.sign(payload1, jwtConfig.secret) - assert(token === token1) - }) - - it('without iat', async () => { - const { app } = testConfig - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const token = svc.sign(payload2) - assert(token.startsWith(tokenHeader2)) - }) - }) -}) diff --git a/packages/jwt/test/jwt-component/verify.test.ts b/packages/jwt/test/jwt-component/verify.test.ts deleted file mode 100644 index ba6d6c459..000000000 --- a/packages/jwt/test/jwt-component/verify.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { JwtComponent } from '##/index.js' -import type { Config } from '##/lib/types.js' -import { - payload1, - token1, -} from '#@/mock-data.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - const secret = '123456abc' - - describe('Should Jwt:verify() work', () => { - it('initializ secret', async () => { - const { app } = testConfig - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const token = svc.sign(payload1) - const ret = svc.verify(token) - assert.deepStrictEqual(ret.payload, payload1) - }) - - it('pass secret', async () => { - const { app } = testConfig - const jwtConfig: Config = { - secret: '', - } - app.addConfigObject({ jwtConfig }) - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const token = svc.sign(payload1, secret) - const ret = svc.verify(token, secret) - assert.deepStrictEqual(ret.payload, payload1) - }) - - it('without verify secret (using signing secret)', async () => { - const { app } = testConfig - const jwtConfig: Config = { - secret: 'not-used', - } - app.addConfigObject({ jwtConfig }) - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const token = svc.sign(payload1, jwtConfig.secret) - const ret = svc.verify(token) - assert.deepStrictEqual(ret.payload, payload1) - }) - - it('both initializing and passing secret', async () => { - const { app } = testConfig - const jwtConfig: Config = { - secret: 'not used', - } - app.addConfigObject({ jwtConfig }) - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - const token = svc.sign(payload1, secret) - const ret = svc.verify(token, secret) - assert.deepStrictEqual(ret.payload, payload1) - }) - - it('with invalid scope', async () => { - const { app } = testConfig - const container = app.getApplicationContext() - const svc = await container.getAsync(JwtComponent) - - // eslint-disable-next-line @typescript-eslint/unbound-method - const { verify } = svc - try { - verify(token1) - } - catch (ex) { - return assert(ex instanceof TypeError) - } - assert(false, 'Should throw error but not.') - }) - }) -}) diff --git a/packages/jwt/test/middleware/helper.ts b/packages/jwt/test/middleware/helper.ts deleted file mode 100644 index 7cf0c9bc4..000000000 --- a/packages/jwt/test/middleware/helper.ts +++ /dev/null @@ -1,158 +0,0 @@ -import assert from 'node:assert/strict' - -import { JwtMsg } from '##/index.js' -import type { JwtState } from '##/index.js' -import type { RespData2, TestResponse } from '#@/root.config.js' - - -export function authShouldPassed( - resp: TestResponse, - expectPayload: unknown, -): void { - - const { status } = resp - const { jwtState } = resp.body as RespData2 - - assert(status === 200) - assert(jwtState) - assert(jwtState.user) - assert(jwtState.header) - assert(jwtState.signature) - assert.deepStrictEqual(jwtState.user, expectPayload) -} - -export function authShouldSkipped(resp: TestResponse): void { - - const { status } = resp - const { jwtState } = resp.body as RespData2 - - assert(status === 200) - console.info({ jwtState }) - assert(! jwtState.user, 'jwtState.user empty') - assert(! jwtState.signature, 'jwtState.signature empty') -} - -export function authShouldFailedWithNotFound2( - resp: TestResponse, - expectStatus = 401, -): void { - - const { status, error } = resp - const { jwtState } = resp.body as RespData2 - - assert(status === expectStatus) - assert(! jwtState, 'jwtState not empty') - assert(error) - assert(error.text.includes('401') || error.text.includes(JwtMsg.AuthFailed)) -} - -export function authShouldFailedWithNotFound( - resp: TestResponse, - expectStatus = 401, -): void { - - const { status, error } = resp - const { jwtState } = resp.body as RespData2 - - assert(status === expectStatus) - assert(! jwtState, 'jwtState not empty') - assert(error, 'error empty') - assert(error.text.includes('401') || error.text.includes(JwtMsg.AuthFailed)) -} - -export function authShouldValidatFailed(resp: TestResponse): void { - - const { status, error } = resp - const { jwtState } = resp.body as RespData2 - - assert(status === 401) - assert(! jwtState, 'jwtState not empty') - assert(error) - assert(error.text.includes('401') || error.text.includes(JwtMsg.AuthFailed)) -} - -export function authShouldPassthroughNotFound( - resp: TestResponse, - expectStatus = 200, -): void { - - const { status } = resp - const { jwtState, jwtOriginalErrorText } = resp.body as RespData2 - - assert(status === expectStatus, `status: ${status} != expect: ${expectStatus}`) - validateData(resp.body as RespData2) - assert(jwtOriginalErrorText.includes(JwtMsg.TokenNotFound), jwtOriginalErrorText) -} - -export function authShouldPassthroughValidFailed( - resp: TestResponse, - expectStatus = 200, -): void { - - const { status } = resp - const { jwtOriginalErrorText } = resp.body as RespData2 - - assert(status === expectStatus, `status: ${status} != expect: ${expectStatus}`) - validateData(resp.body as RespData2) - assert(jwtOriginalErrorText.includes(JwtMsg.TokenValidFailed), jwtOriginalErrorText) -} - - -export function authShouldRedirect( - resp: TestResponse, - redirectUrl: string, -): void { - - const { status } = resp - const { jwtState } = resp.body as RespData2 - - assert(status === 302) - assert(! jwtState) - - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const loc = resp.header.location as string - assert(loc === redirectUrl) -} - -export function authShouldPassthroughEmptyStringNotFound( - resp: TestResponse, - expectStatus = 200, -): void { - - const { status, error } = resp - const { jwtState } = resp.body as RespData2 - - assert(status === expectStatus) - assert(! jwtState) - assert(error) - assert(error.text.includes('401') || error.text.includes(JwtMsg.AuthFailed)) -} - -export function authShouldFailedWithNotFoundFromDebug( - resp: TestResponse, - expectStatus = 401, -): void { - - const { status, error } = resp - const { jwtState } = resp.body as RespData2 - - assert(status === expectStatus) - assert(! jwtState) - assert(error) - assert(error.text.includes('401') || error.text.includes(JwtMsg.TokenNotFound)) -} - -function validateData(data: RespData2): void { - const { jwtState } = data - - assert(jwtState, 'jwtState empty') - assert(! jwtState.user, 'jwtState.user empty') - assert(! jwtState.secret, 'jwtState.secret empty') - assert(! jwtState.signature, 'jwtState.signature empty') -} - -declare module '@midwayjs/core' { - interface Context { - jwtState: JwtState - } -} diff --git a/packages/jwt/test/middleware/with-token/jwt.middleware.passthough-func.test.ts b/packages/jwt/test/middleware/with-token/jwt.middleware.passthough-func.test.ts deleted file mode 100644 index 577c42da9..000000000 --- a/packages/jwt/test/middleware/with-token/jwt.middleware.passthough-func.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - - -import { ConfigKey } from '##/lib/types.js' -import type { MiddlewareConfig, PassthroughCallback } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { authHeader1, payload1 } from '#@/mock-data.js' -import { testConfig } from '#@/root.config.js' - -import { - authShouldFailedWithNotFound2, - authShouldPassed, - authShouldPassthroughNotFound, -} from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const callbackTrue: PassthroughCallback = async () => true - const callbackFalse: PassthroughCallback = async () => false - const path = `/${apiMethod.test}` - - describe('Should JwtAuthenticateOptions.passthrough work with func', () => { - it('true: passed', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - passthrough: callbackFalse, - }, - } - assert(mwConfig.options) - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const sendHeader = { - authorization: authHeader1, - } - - // validate 401 without token and passthrough - const resp1 = await httpRequest.get(path) - assert(! resp1.ok, `resp1.ok: ${resp1.ok}`) - assert(resp1, 'resp1 is empty') - assert(resp1.status === 401, `resp1.status: ${resp1.status}`) - - mwConfig.options.passthrough = callbackTrue - - const resp = await httpRequest - .get(path) - .set(sendHeader) - .expect(200) - - assert(resp, 'resp is empty') - authShouldPassed(resp, payload1) - }) - - it('true: w/o token', async () => { - const { app, httpRequest } = testConfig - - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - passthrough: callbackTrue, - }, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldPassthroughNotFound(resp, 200) - }) - - it('invalid value: w/o token', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - // @ts-expect-error - passthrough: 0, - }, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldFailedWithNotFound2(resp, 401) - }) - - it('invalid value 1: w/o token', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - // @ts-expect-error - passthrough: 1, - }, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldFailedWithNotFound2(resp, 401) - }) - }) -}) - diff --git a/packages/jwt/test/middleware/with-token/jwt.middleware.passthough-string.test.ts b/packages/jwt/test/middleware/with-token/jwt.middleware.passthough-string.test.ts deleted file mode 100644 index 26f60e9b0..000000000 --- a/packages/jwt/test/middleware/with-token/jwt.middleware.passthough-string.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { ConfigKey } from '##/lib/types.js' -import type { MiddlewareConfig } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - -import { - authShouldPassthroughEmptyStringNotFound, - authShouldRedirect, -} from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `/${apiMethod.test}` - - describe('Should JwtAuthenticateOptions.passthrough work with value string', () => { - it('valid url', async () => { - const { app, httpRequest } = testConfig - const path2 = '/redirect-' + Math.random().toString() - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - passthrough: path2, - }, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldRedirect(resp, path2) - }) - - it('empty string', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - passthrough: '', - }, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldPassthroughEmptyStringNotFound(resp, 401) - }) - }) -}) - diff --git a/packages/jwt/test/middleware/with-token/jwt.middleware.passthough-true.test.ts b/packages/jwt/test/middleware/with-token/jwt.middleware.passthough-true.test.ts deleted file mode 100644 index 458a3378a..000000000 --- a/packages/jwt/test/middleware/with-token/jwt.middleware.passthough-true.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { fileShortPath } from '@waiting/shared-core' - -import { ConfigKey } from '##/lib/types.js' -import type { MiddlewareConfig } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { authHeader1, payload1 } from '#@/mock-data.js' -import { testConfig } from '#@/root.config.js' - -import { - authShouldPassed, - authShouldPassthroughNotFound, - authShouldPassthroughValidFailed, -} from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `/${apiMethod.test}` - - describe('Should JwtAuthenticateOptions.passthrough work with value: true', () => { - it('passed', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - passthrough: true, - }, - } - app.addConfigObject({ [ConfigKey.middlewareConfig]: mwConfig }) - - const sendHeader = { - authorization: authHeader1, - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldPassed(resp, payload1) - }) - - it('token not found', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - passthrough: true, - }, - } - app.addConfigObject({ [ConfigKey.middlewareConfig]: mwConfig }) - - const sendHeader = { - authorization: '', - } - const resp = await httpRequest - .get(path) - authShouldPassthroughNotFound(resp) - }) - - it('token valid faied', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - passthrough: true, - }, - } - app.addConfigObject({ [ConfigKey.middlewareConfig]: mwConfig }) - - const sendHeader = { - authorization: authHeader1 + 'FAKE', - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldPassthroughValidFailed(resp) - }) - }) -}) - diff --git a/packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-cookie.test.ts b/packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-cookie.test.ts deleted file mode 100644 index 603f16f93..000000000 --- a/packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-cookie.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { initPathArray, initialMiddlewareConfig } from '##/lib/config.js' -import { ConfigKey } from '##/lib/types.js' -import type { MiddlewareConfig } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { payload1, token1 } from '#@/mock-data.js' -import { testConfig } from '#@/root.config.js' - -import { authShouldFailedWithNotFound, authShouldPassed, authShouldSkipped } from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `/${apiMethod.test}` - - describe('Should JwtComponent.validateToken() work with cookie', () => { - it('auth skipped', async () => { - const { app, httpRequest } = testConfig - const cookieKey = 'user' - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - ignore: [path], - options: { - cookie: cookieKey, - }, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const cookie = [`${cookieKey}=${token1}`] - const sendHeader = { - authorization: '', - Cookie: cookie, - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldSkipped(resp) - }) - - it('auth test with JwtAuthenticateOptions.cookie user value', async () => { - const { app, httpRequest } = testConfig - const cookieKey = 'user' - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - ignore: initPathArray, - options: { - cookie: cookieKey, - }, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const cookie = [`${cookieKey}=${token1}; path=/; expires=Wed, 24 Feb 2021 06:59:09 GMT; httponly`] - const sendHeader = { - authorization: '', - Cookie: cookie, - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldPassed(resp, payload1) - }) - - it('auth test with JwtAuthenticateOptions.cookie false (default)', async () => { - const { app, httpRequest } = testConfig - const cookieKey = 'user' - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - ignore: initPathArray, - options: { - ...initialMiddlewareConfig.options, - }, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const cookie = [`${cookieKey}=${token1}; path=/; expires=Wed, 24 Feb 2021 06:59:09 GMT; httponly`] - const sendHeader = { - authorization: '', - Cookie: cookie, - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldFailedWithNotFound(resp) - }) - }) -}) - diff --git a/packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-header.test.ts b/packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-header.test.ts deleted file mode 100644 index 10ebb0664..000000000 --- a/packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-header.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { jwtMiddlewareConfig as mConfig } from '##/config/config.unittest.js' -import { ConfigKey } from '##/lib/types.js' -import type { MiddlewareConfig } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { authHeader1, payload1 } from '#@/mock-data.js' -import { testConfig } from '#@/root.config.js' - -import { - authShouldPassed, - authShouldSkipped, - authShouldValidatFailed, -} from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `/${apiMethod.test}` - - describe('Should JwtComponent.validateToken() work with header', () => { - it('auth skipped', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - ignore: [path], - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const sendHeader = { - authorization: authHeader1, - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldSkipped(resp) - }) - - it('auth testing passed', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - ...mConfig, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const sendHeader = { - authorization: authHeader1, - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldPassed(resp, payload1) - }) - - it('auth validation failed', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - ...mConfig, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const sendHeader = { - authorization: authHeader1 + 'fake', - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldValidatFailed(resp) - }) - }) -}) - diff --git a/packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-jwtState.test.ts b/packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-jwtState.test.ts deleted file mode 100644 index fb376ed2b..000000000 --- a/packages/jwt/test/middleware/with-token/jwt.middleware.verifyToken-jwtState.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { jwtMiddlewareConfig as mConfig } from '##/config/config.unittest.js' -import { ConfigKey } from '##/lib/types.js' -import type { Config, MiddlewareConfig } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { authHeader1, payload1 } from '#@/mock-data.js' -import { testConfig } from '#@/root.config.js' - -import { authShouldPassed } from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `/${apiMethod.test}` - - describe('Should JwtComponent.validateToken() work with secret from ctx', () => { - const config: Config = { - secret: 'FAKE', - } - - it('passed with ctx.jwtState.secret', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - ...mConfig, - } - app.addConfigObject({ - [ConfigKey.config]: config, - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const sendHeader = { - authorization: authHeader1, - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldPassed(resp, payload1) - }) - - it('passed with ctx.state.secret', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - ...mConfig, - } - app.addConfigObject({ - [ConfigKey.config]: config, - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const sendHeader = { - authorization: authHeader1, - } - const resp = await httpRequest - .get(path) - .set(sendHeader) - authShouldPassed(resp, payload1) - }) - - }) -}) - diff --git a/packages/jwt/test/middleware/without-token/jwt.middleware.debug.test.ts b/packages/jwt/test/middleware/without-token/jwt.middleware.debug.test.ts deleted file mode 100644 index 50b547b5d..000000000 --- a/packages/jwt/test/middleware/without-token/jwt.middleware.debug.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { ConfigKey } from '##/lib/types.js' -import type { MiddlewareConfig } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - -import { - authShouldFailedWithNotFoundFromDebug, - authShouldPassthroughNotFound, -} from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `/${apiMethod.test}` - - describe('Should MiddlewareConfig.debug work true', () => { - it('normal', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - debug: true, - }, - } - app.addConfigObject({ [ConfigKey.middlewareConfig]: mwConfig }) - - const resp = await httpRequest - .get(path) - authShouldFailedWithNotFoundFromDebug(resp) - }) - - it('ignored with passthrough:true', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - enableMiddleware: true, - options: { - debug: true, - passthrough: true, - }, - } - app.addConfigObject({ [ConfigKey.middlewareConfig]: mwConfig }) - - const resp = await httpRequest - .get(path) - authShouldPassthroughNotFound(resp) - }) - }) -}) - diff --git a/packages/jwt/test/middleware/without-token/jwt.middleware.ignore-func.test.ts b/packages/jwt/test/middleware/without-token/jwt.middleware.ignore-func.test.ts deleted file mode 100644 index 95b95011f..000000000 --- a/packages/jwt/test/middleware/without-token/jwt.middleware.ignore-func.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { jwtMiddlewareConfig as mConfig } from '##/config/config.unittest.js' -import { ConfigKey } from '##/lib/types.js' -import type { MiddlewareConfig } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - -import { authShouldFailedWithNotFound, authShouldSkipped } from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `/${apiMethod.test}` - - describe('Should MiddlewareConfig.ignore work with func', () => { - it('auth skipped eq', async () => { - const { app, httpRequest } = testConfig - const cb = (url: string) => { - return url === path - } - const mwConfig: MiddlewareConfig = { - ...mConfig, - ignore: [cb], - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldSkipped(resp) - }) - - it('auth skipped neq', async () => { - const { app, httpRequest } = testConfig - const cb = (url: string) => { - return url !== path // actual eq - } - const mwConfig: MiddlewareConfig = { - ...mConfig, - ignore: [cb], - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - - console.log(resp.body) - authShouldFailedWithNotFound(resp) - }) - }) -}) - diff --git a/packages/jwt/test/middleware/without-token/jwt.middleware.ignore-regex.test.ts b/packages/jwt/test/middleware/without-token/jwt.middleware.ignore-regex.test.ts deleted file mode 100644 index 52f9d1b39..000000000 --- a/packages/jwt/test/middleware/without-token/jwt.middleware.ignore-regex.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { jwtMiddlewareConfig as mConfig } from '##/config/config.unittest.js' -import { ConfigKey } from '##/lib/types.js' -import type { MiddlewareConfig } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - -import { authShouldSkipped } from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `/${apiMethod.test}` - - describe('Should MiddlewareConfig.ignore work with regex', () => { - it('auth skipped', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - ...mConfig, - ignore: [/^\/.*/u], - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldSkipped(resp) - }) - - }) -}) - diff --git a/packages/jwt/test/middleware/without-token/jwt.middleware.ignore-string.test.ts b/packages/jwt/test/middleware/without-token/jwt.middleware.ignore-string.test.ts deleted file mode 100644 index 378990386..000000000 --- a/packages/jwt/test/middleware/without-token/jwt.middleware.ignore-string.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { jwtMiddlewareConfig as mConfig } from '##/config/config.unittest.js' -import { ConfigKey } from '##/lib/types.js' -import type { MiddlewareConfig } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - -import { authShouldFailedWithNotFound, authShouldSkipped } from '../helper.js' - - -describe(fileShortPath(import.meta.url), () => { - - const path = `/${apiMethod.test}` - - describe('Should MiddlewareConfig.ignore work with string', () => { - it('auth skipped', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - ...mConfig, - ignore: [path], - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldSkipped(resp) - }) - - it('auth skipped with empty ignore', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - ...mConfig, - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldFailedWithNotFound(resp) - }) - - it('auth skipped with random ignore', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - ...mConfig, - ignore: ['/' + Math.random().toString()], - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldFailedWithNotFound(resp) - }) - - it('auth skipped mixed with invalid value', async () => { - const { app, httpRequest } = testConfig - const mwConfig: MiddlewareConfig = { - ...mConfig, - // @ts-expect-error - ignore: [false, '', path], - } - app.addConfigObject({ - [ConfigKey.middlewareConfig]: mwConfig, - }) - - const resp = await httpRequest - .get(path) - authShouldSkipped(resp) - }) - - }) -}) - diff --git a/packages/jwt/test/mock-data.ts b/packages/jwt/test/mock-data.ts deleted file mode 100644 index 56d09dff9..000000000 --- a/packages/jwt/test/mock-data.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { JsonObject } from '@waiting/shared-types' - - -/** Type with index signature */ -export interface PayloadSig1 { - foo: string - iat: number - [index: string]: string | number -} -/** Type extends from JsonType */ -export interface PayloadExt1 extends JsonObject { - foo: string - iat: number -} - - -export const payload1 = { foo: 'bar', iat: 1566629919 } -export const signature1 = 'PZkACzct30IcrymoodYlW0LW0Fc1r6Hs1l8yOZSeNpk' -export const token1 = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' - + 'eyJmb28iOiJiYXIiLCJpYXQiOjE1NjY2Mjk5MTl9.' - + signature1 - -export const authHeader1 = `Bearer ${token1}` - -export const token7d = ` -eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpYXQiOjE1NjY2Mjk5MTksImV4cCI6MTU2NzIzNDcxOX0.MdR1Z1gHTExIUIOTHurwIao7vbfrkqynDsoNZ8nMsnE -`.trim() - - -export const payload2 = { foo: 'bar' } -export const tokenHeader2 = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' - -export const testRedirectURL = Math.random().toString() - diff --git a/packages/jwt/test/root.config.ts b/packages/jwt/test/root.config.ts deleted file mode 100644 index 1d54ac02a..000000000 --- a/packages/jwt/test/root.config.ts +++ /dev/null @@ -1,60 +0,0 @@ -import type { IncomingHttpHeaders } from 'node:http' -import { join } from 'node:path' - -import type { Application, IMidwayContainer, JsonResp } from '@mwcp/share' -import { genCurrentDirname } from '@waiting/shared-core' -import type { SuperTest } from 'supertest' -import type supertest from 'supertest' - -import type { JwtState } from '../src/lib/types.js' - - -export const testDir = genCurrentDirname(import.meta.url) -export const baseDir = join(testDir, '..') - -const CI = !! ((process.env['CI'] - ?? process.env['MIDWAY_SERVER_ENV'] === 'unittest') - || process.env['MIDWAY_SERVER_ENV'] === 'local' - || process.env['NODE_ENV'] === 'unittest' - || process.env['NODE_ENV'] === 'local' -) - -export type TestResponse = supertest.Response -export type TestRespBody = JsonResp -export interface RespData { - header: IncomingHttpHeaders - url: string - cookies: unknown -} - -export interface TestConfig { - baseDir: string - testDir: string - testAppDir: string - CI: boolean - app: Application - container: IMidwayContainer - host: string - httpRequest: SuperTest -} - -const testAppDir = join(testDir, 'fixtures', 'base-app') -export const testConfig = { - baseDir, - testDir, - testAppDir, - CI, - host: '', - httpRequest: {}, -} as TestConfig - - - -export interface RespData2 { - header: IncomingHttpHeaders - url: string - cookies: unknown - jwtState: JwtState - jwtOriginalErrorText: string -} - diff --git a/packages/jwt/test/setup.ts b/packages/jwt/test/setup.ts deleted file mode 100644 index 655800c43..000000000 --- a/packages/jwt/test/setup.ts +++ /dev/null @@ -1,68 +0,0 @@ -// https://mochajs.org/#global-fixtures -// https://mochajs.org/#root-hook-plugins -import assert from 'node:assert' - -import { close, createApp, createHttpRequest } from '@midwayjs/mock' -import type { Application } from '@mwcp/share' -import type { Suite } from 'mocha' - -import { testConfig } from './root.config.js' -import type { TestConfig } from './root.config.js' - - -let app: Application - -export async function mochaGlobalSetup(this: Suite) { - app = await createAppInstance() - await updateConfig(app, testConfig) - await updateConfig2(app, testConfig) -} - -export async function mochaGlobalTeardown(this: Suite) { - await clean(app, testConfig) - await close(app) -} - - -/** - * Update testConfig in place - */ -async function createAppInstance(): Promise { - try { - app = await createApp(testConfig.testAppDir) as Application - } - catch (ex) { - console.error('createApp error:', ex) - throw ex - } - - assert(app, 'app not exists') - - const middlewares = app.getMiddleware().getNames() - console.info({ middlewares }) - - return app - // https://midwayjs.org/docs/testing -} - -async function updateConfig(mockApp: Application, config: TestConfig): Promise { - config.app = mockApp - config.httpRequest = createHttpRequest(mockApp) - - assert(config.httpRequest, 'httpRequest not exists') - const { url } = config.httpRequest.get('/') - config.host = url - - config.container = mockApp.getApplicationContext() - // const svc = await testConfig.container.getAsync(TaskQueueService) -} - -async function updateConfig2(mockApp: Application, config: TestConfig): Promise { - void mockApp - void config -} - -async function clean(mockApp: Application, config: TestConfig): Promise { - void mockApp - void config -} diff --git a/packages/jwt/test/tsconfig.json b/packages/jwt/test/tsconfig.json deleted file mode 100644 index cfbe091fd..000000000 --- a/packages/jwt/test/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": { - "noEmit": true, - "noImplicitAny": false, - "noImplicitThis": false, - "noPropertyAccessFromIndexSignature": false, - "noUnusedLocals": false, - "rootDir": ".." - }, - "include": [ - "../src/", - "." - ] -} diff --git a/packages/jwt/test/util/resolver.test.ts b/packages/jwt/test/util/resolver.test.ts deleted file mode 100644 index 60e73a228..000000000 --- a/packages/jwt/test/util/resolver.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import assert from 'node:assert/strict' -import { relative } from 'node:path' - -import { fileShortPath } from '@waiting/shared-core' - -import { - resolveFromAuthorizationHeader, - resolveFromCookies, - schemePrefix, -} from '##/index.js' -import { token1 } from '#@/mock-data.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('Should resolveFromAuthorizationHeader() works', () => { - it('with valid input', () => { - const arr = [ - `${schemePrefix} ${token1}`, - `${schemePrefix} ${token1}`, - ] - - arr.forEach((val) => { - const token = resolveFromAuthorizationHeader(val) - assert(token && token === token1) - }) - }) - - it('with invalid type input', () => { - const arr = [ - '', - 1, - true, - false, - null, - void 0, - ] - - arr.forEach((val) => { - // @ts-ignore - const token = resolveFromAuthorizationHeader(val) - assert(token === '') - }) - }) - - it('with invalid header input', () => { - const arr = [ - ` ${schemePrefix} ${token1}`, - ` ${schemePrefix} ${token1}`, - `${schemePrefix} ${token1} `, - `${schemePrefix} ${token1} `, - `${schemePrefix} ${token1} fake`, - `${schemePrefix}: ${token1}`, - `${schemePrefix} `, - `${token1}`, - ` ${token1}`, - ] - - arr.forEach((val) => { - const token = resolveFromAuthorizationHeader(val) - assert(token === '') - }) - }) - }) - - - describe('Should resolveFromCookies() works', () => { - it('with valid cookieKey', () => { - const cookies = new Map() - cookies.set('user', token1) - // @ts-ignore - const ret = resolveFromCookies(cookies, 'user') - assert(ret === token1) - }) - - it('with blank cookieKey', () => { - const cookies = new Map() - cookies.set('user', token1) - // @ts-ignore - const ret = resolveFromCookies(cookies, '') - assert(ret === '') - }) - }) -}) - diff --git a/packages/jwt/test/util/validatePayload.test.ts b/packages/jwt/test/util/validatePayload.test.ts deleted file mode 100644 index e3ede2cf5..000000000 --- a/packages/jwt/test/util/validatePayload.test.ts +++ /dev/null @@ -1,45 +0,0 @@ - -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { validatePayload } from '##/index.js' -import { token1 } from '#@/mock-data.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('Should validatePayload() work', () => { - it('with valid input', () => { - const arr = [ - 'abc', '\n', token1, - Buffer.from('foo'), - { foo: 'bar' }, - ] - - arr.forEach(validatePayload) - }) - - it('with invalid input', () => { - const arr = [ - '', Buffer.alloc(0), {}, - true, false, null, void 0, Symbol('foo'), - // eslint-disable-next-line @typescript-eslint/no-empty-function - () => {}, - ] - - arr.forEach((val) => { - try { - // @ts-ignore - validatePayload(val) - } - catch (ex) { - return assert(true) - } - assert(false, 'Should throw error but NOT.') - }) - }) - }) - -}) - diff --git a/packages/jwt/test/util/validateSignSecret.test.ts b/packages/jwt/test/util/validateSignSecret.test.ts deleted file mode 100644 index 5655b7d6d..000000000 --- a/packages/jwt/test/util/validateSignSecret.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { validateSignSecret } from '##/index.js' -import { token1 } from '#@/mock-data.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('Should validateSignSecret() work', () => { - it('with valid input', () => { - const arr = [ - 'abc', '\n', token1, - { key: 'foo', passphrase: 'bar' }, - Buffer.from('foo'), - ] - - arr.forEach(validateSignSecret) - }) - - it('with invalid input', () => { - const arr = [ - '', Buffer.alloc(0), - {}, { foo: 'bar' }, - { key: 123 }, - { passphrase: 123 }, - true, false, null, void 0, Symbol('foo'), - // eslint-disable-next-line @typescript-eslint/no-empty-function - () => {}, - ] - - arr.forEach((val) => { - try { - // @ts-ignore - validateSignSecret(val) - } - catch (ex) { - return assert(true) - } - assert(false, 'Should throw error but NOT.') - }) - }) - }) - -}) - diff --git a/packages/jwt/test/util/validateTokenString.test.ts b/packages/jwt/test/util/validateTokenString.test.ts deleted file mode 100644 index e534acab6..000000000 --- a/packages/jwt/test/util/validateTokenString.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { validateTokenString } from '##/index.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('Should validateTokenString() work', () => { - it('with invalid input', () => { - const arr = [true, false, null, void 0, ''] - - arr.forEach((val) => { - try { - // @ts-ignore - validateTokenString(val) - } - catch (ex) { - return assert(true) - } - assert(false, 'Should throw error but NOT.') - }) - }) - }) - -}) - diff --git a/packages/jwt/test/util/validateVerifySecret.test.ts b/packages/jwt/test/util/validateVerifySecret.test.ts deleted file mode 100644 index 8071a9df7..000000000 --- a/packages/jwt/test/util/validateVerifySecret.test.ts +++ /dev/null @@ -1,45 +0,0 @@ - -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { validateVerifySecret } from '##/index.js' -import { token1 } from '#@/mock-data.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('Should validateVerifySecret() work', () => { - it('with valid input', () => { - const arr = [ - 'abc', '\n', token1, - Buffer.from('foo'), - ] as const - - arr.forEach(validateVerifySecret) - }) - - it('with invalid input', () => { - const arr = [ - '', Buffer.alloc(0), {}, - true, null, void 0, Symbol('foo'), - // eslint-disable-next-line @typescript-eslint/no-empty-function - () => { }, - false, - ] - - arr.forEach((val) => { - try { - // @ts-ignore - validateVerifySecret(val) - } - catch (ex) { - return assert(true) - } - assert(false, 'Should throw error but NOT.') - }) - }) - }) - -}) - diff --git a/packages/jwt/tsconfig.json b/packages/jwt/tsconfig.json deleted file mode 100644 index 8890df64a..000000000 --- a/packages/jwt/tsconfig.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "./tsconfig.base.json", - "compilerOptions": { - "rootDir": "src" - } -} diff --git a/packages/otel/.editorconfig b/packages/otel/.editorconfig deleted file mode 100644 index 731bcab2c..000000000 --- a/packages/otel/.editorconfig +++ /dev/null @@ -1,16 +0,0 @@ -# EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs -# Editor configuration, see http://editorconfig.org - -root = true - -[*] -charset = utf-8 -end_of_line = lf -indent_style = space -indent_size = 2 -insert_final_newline = true -trim_trailing_whitespace = true - -[*.md] -max_line_length = off -trim_trailing_whitespace = false diff --git a/packages/otel/.eslintrc.yml b/packages/otel/.eslintrc.yml deleted file mode 100644 index 9a79cb2d6..000000000 --- a/packages/otel/.eslintrc.yml +++ /dev/null @@ -1,21 +0,0 @@ -extends: '@waiting/eslint-config' -parserOptions: - project: 'tsconfig.eslint.json' - -rules: - "@typescript-eslint/no-unused-vars": 0 - "@typescript-eslint/prefer-ts-expect-error": 0 - "@typescript-eslint/no-extraneous-class": 0 - "import/no-extraneous-dependencies": - - 0 - - packageDir: - - ./ - - ../share/ - - ../../node_modules/@opentelemetry/sdk-node - - ../../node_modules/@opentelemetry/instrumentation-http - - ../../node_modules/@opentelemetry/auto-instrumentations-node - - ../../node_modules/@opentelemetry/otlp-grpc-exporter-base - # - ../../node_modules/@midwayjs/core - -# ignorePatterns: -# - test diff --git a/packages/otel/CHANGELOG.md b/packages/otel/CHANGELOG.md deleted file mode 100644 index a0918c239..000000000 --- a/packages/otel/CHANGELOG.md +++ /dev/null @@ -1,1302 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. -See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. - -# [41.0.0](https://github.com/waitingsong/midway-components/compare/v40.1.1...v41.0.0) (2024-11-21) - - -### Bug Fixes - -* **otel:** arrow function detecting ([472675f](https://github.com/waitingsong/midway-components/commit/472675fbac14bd478890048dff87b15ce8ffc679)) - - -### Features - -* **otel:** DecoratorTraceData['endSpanAfterTraceLog'] supports Span[] ([1e8e26c](https://github.com/waitingsong/midway-components/commit/1e8e26c16c0dd04638db739d27ee66317c27764b)) - - - - - -## [40.1.1](https://github.com/waitingsong/midway-components/compare/v40.1.0...v40.1.1) (2024-11-12) - - -### Bug Fixes - -* **otel:** afterReturnSync(), afterReturnAsync() of TraceLog() missing trace context ([b1e8c3f](https://github.com/waitingsong/midway-components/commit/b1e8c3fa931a1970f3dc1f81a6e0126f57c1856a)) - - - - - -# [40.1.0](https://github.com/waitingsong/midway-components/compare/v40.0.0...v40.1.0) (2024-11-10) - - -### Features - -* **otel:** do not validate scope during create new span ([3702536](https://github.com/waitingsong/midway-components/commit/3702536be34a4df433b232bcd7108c17c3ea1b46)) - - - - - -# [40.0.0](https://github.com/waitingsong/midway-components/compare/v39.3.0...v40.0.0) (2024-11-10) - - -### Features - -* **otel:** breaking changes for using context.active() inner method or function ([8403238](https://github.com/waitingsong/midway-components/commit/84032388ce3bf3a05ebafab6ce5cdfd50d362cfc)) -* **otel:** rename OtelComponent.getGlobalCurrentContext() to getActiveContext() ([c8e5463](https://github.com/waitingsong/midway-components/commit/c8e54630df86f6a30aa4bdf22a74860f6a2e5025)) -* **otel:** rename OtelComponent.getGlobalCurrentSpan() to getActiveSpan() ([1d3a6f9](https://github.com/waitingsong/midway-components/commit/1d3a6f9967e02897a3b4696595c181891d4d2d2f)) -* **otel:** update TraceServiceSpan.startScopeActiveSpan() ([666f11a](https://github.com/waitingsong/midway-components/commit/666f11a1cf1ce432784dad1f27ffcb0edf9eca08)) -* remove TraceServiceSpan.setAttributesLater() ([90ed626](https://github.com/waitingsong/midway-components/commit/90ed6269420fe83084dfaada0d5e4cedb62f84b6)) - - - - - -# [39.3.0](https://github.com/waitingsong/midway-components/compare/v39.2.0...v39.3.0) (2024-11-06) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [39.2.0](https://github.com/waitingsong/midway-components/compare/v39.1.2...v39.2.0) (2024-11-04) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [39.1.2](https://github.com/waitingsong/midway-components/compare/v39.1.1...v39.1.2) (2024-10-31) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [39.1.1](https://github.com/waitingsong/midway-components/compare/v39.1.0...v39.1.1) (2024-10-30) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [39.1.0](https://github.com/waitingsong/midway-components/compare/v39.0.2...v39.1.0) (2024-10-30) - - -### Bug Fixes - -* **otel:** middlewares using order ([ed07659](https://github.com/waitingsong/midway-components/commit/ed076594dd345a2cb8b22483758caa38950b0fec)) - - -### Features - -* **otel:** addSpanEventWithIncomingRequestData() skip log if none ([73b536c](https://github.com/waitingsong/midway-components/commit/73b536ce403979a02cc1b7c6cd63968daf95e40b)) - - - - - -## [39.0.2](https://github.com/waitingsong/midway-components/compare/v39.0.1...v39.0.2) (2024-10-29) - - -### Bug Fixes - -* **otel:** fix src/configuration.ts using middleware ([e965166](https://github.com/waitingsong/midway-components/commit/e9651663c7c0e5c9a2e365c36164a9328ce3dccf)) -* **otel:** order of using TraceMiddlewareInnerGRpc ([3e56a14](https://github.com/waitingsong/midway-components/commit/3e56a14a3f515ff8d4201c186d0042ea53af7d30)) - - - - - -## [39.0.1](https://github.com/waitingsong/midway-components/compare/v39.0.0...v39.0.1) (2024-10-29) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [39.0.0](https://github.com/waitingsong/midway-components/compare/v38.4.0...v39.0.0) (2024-10-29) - - -### Features - -* **otel:** add property of parameter of AssertsRootOptions() ([9897828](https://github.com/waitingsong/midway-components/commit/9897828e022eb18157f56e510cabcb70f249ea9f)) -* **otel:** addSpanEventWithIncomingRequestData() always log AttrNames.Incoming_Request_data ([cd120b9](https://github.com/waitingsong/midway-components/commit/cd120b9b58172dd0938b0a8b55a2941181a15c46)) -* **otel:** supports RPC request by @midwayjs/grpc ([c4e1333](https://github.com/waitingsong/midway-components/commit/c4e1333d8fbdc55d103b84049ddf4328b1af831f)) -* **otel:** TraceServiceSpan.getTraceId() accepts optional param scope ([bb05a60](https://github.com/waitingsong/midway-components/commit/bb05a60065f4fcd8256e74c773a18b3e52fcb1b3)) - - - - - -# [38.4.0](https://github.com/waitingsong/midway-components/compare/v38.3.0...v38.4.0) (2024-10-28) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [38.3.0](https://github.com/waitingsong/midway-components/compare/v38.2.3...v38.3.0) (2024-10-28) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [38.2.3](https://github.com/waitingsong/midway-components/compare/v38.2.2...v38.2.3) (2024-10-25) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [38.2.2](https://github.com/waitingsong/midway-components/compare/v38.2.1...v38.2.2) (2024-10-05) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [38.2.1](https://github.com/waitingsong/midway-components/compare/v38.2.0...v38.2.1) (2024-09-15) - - -### Bug Fixes - -* **otel:** assertJaegerTagItem(), assertJaegerLogField() ([e981248](https://github.com/waitingsong/midway-components/commit/e981248ce5e5ad38ea87ff08442353ebb45a3560)) - - - - - -# [38.2.0](https://github.com/waitingsong/midway-components/compare/v38.1.0...v38.2.0) (2024-09-15) - - -### Features - -* **otel:** assertJaegerTagItem(), assertJaegerLogField() ([cb941c5](https://github.com/waitingsong/midway-components/commit/cb941c59e22968d16a92c799e87093d21d42cd7d)) -* **otel:** update ExpectAttributes support RegExp value for assertsSpan() ([31a2e4e](https://github.com/waitingsong/midway-components/commit/31a2e4e023189102ccfc96287cd6edf50fac88f6)) - - - - - -# [38.1.0](https://github.com/waitingsong/midway-components/compare/v38.0.0...v38.1.0) (2024-09-15) - - -### Features - -* **otel:** update type AssertsRootOp for assertRootSpan() ([382e6a3](https://github.com/waitingsong/midway-components/commit/382e6a385f2fb108bd0959da8dc9104d9ca85471)) - - - - - -# [38.0.0](https://github.com/waitingsong/midway-components/compare/v37.4.1...v38.0.0) (2024-09-14) - - -### Features - -* **otel:** breaking change DecoratorHandlerTraceBase.getWebContext() eat error ([8b8c509](https://github.com/waitingsong/midway-components/commit/8b8c509950730bcd679f0d6d57a6c949a6f5c63a)) - - - - - -## [37.4.1](https://github.com/waitingsong/midway-components/compare/v37.4.0...v37.4.1) (2024-09-10) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [37.4.0](https://github.com/waitingsong/midway-components/compare/v37.3.0...v37.4.0) (2024-09-07) - - -### Bug Fixes - -* **otel:** assign traceContext for Trace() ([fa00c3b](https://github.com/waitingsong/midway-components/commit/fa00c3bf88de10df4218b2b44688d98ec1ba86fe)) - - -### Features - -* **otel:** add properties of DecoratorTraceData for TraceLog() ([ba26cc6](https://github.com/waitingsong/midway-components/commit/ba26cc65ad4653ec53d77b7dc5d2a3233cb81600)) -* **otel:** TraceServiceSpan.getActiveTraceInfo() ([5802b1c](https://github.com/waitingsong/midway-components/commit/5802b1c3eb9abaf2a7cce89fba2e5069116dc9b2)) - - - - - -# [37.3.0](https://github.com/waitingsong/midway-components/compare/v37.2.4...v37.3.0) (2024-09-04) - - -### Features - -* **otel:** TraceService.retrieveContextBySpanId() ([55bbe5b](https://github.com/waitingsong/midway-components/commit/55bbe5b1c142da6a206d70c2abfbe1623d07c3cd)) -* **otel:** TraceService.retrieveParentTraceInfoBySpan() and retrieveTraceInfoBySpanId() ([e96ea2f](https://github.com/waitingsong/midway-components/commit/e96ea2f683a5c18ddcbe12039152d97669467d98)) -* **otel:** type TraceInfo ([5690552](https://github.com/waitingsong/midway-components/commit/56905524eb70af940e2ceafd614e26b484177a98)) - - - - - -## [37.2.4](https://github.com/waitingsong/midway-components/compare/v37.2.3...v37.2.4) (2024-09-04) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [37.2.3](https://github.com/waitingsong/midway-components/compare/v37.2.2...v37.2.3) (2024-09-04) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [37.2.2](https://github.com/waitingsong/midway-components/compare/v37.2.1...v37.2.2) (2024-09-04) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [37.2.1](https://github.com/waitingsong/midway-components/compare/v37.2.0...v37.2.1) (2024-08-29) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [37.2.0](https://github.com/waitingsong/midway-components/compare/v37.1.0...v37.2.0) (2024-08-17) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [37.1.0](https://github.com/waitingsong/midway-components/compare/v37.0.0...v37.1.0) (2024-08-16) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [37.0.0](https://github.com/waitingsong/midway-components/compare/v36.1.3...v37.0.0) (2024-08-12) - - -### Bug Fixes - -* **otel:** wrong type of afterReturnSync() ([0006dfd](https://github.com/waitingsong/midway-components/commit/0006dfd18e8f50b751dc4cf39a8d1183999227da)) - - -### Features - -* **otel:** add TraceService methods ([e7c3346](https://github.com/waitingsong/midway-components/commit/e7c3346132839948e272ca66d8dbaa0f04718c95)) -* **otel:** breaking change return type of startSpan() ([0f3943d](https://github.com/waitingsong/midway-components/commit/0f3943d410f251caa0ae67e30d4d852d94cb0de6)) -* **otel:** DecoratorTraceData['spanStatusOptions'] ([cb6d479](https://github.com/waitingsong/midway-components/commit/cb6d479bf7ee0e00438fd30a7394159ee4e962e6)) -* **otel:** DecoratorTraceDataResp accepts null ([9c54840](https://github.com/waitingsong/midway-components/commit/9c5484001fd7ffddb60e005aa5882c178341d5a9)) -* **otel:** getRootSpan() ([93372b3](https://github.com/waitingsong/midway-components/commit/93372b3f5d0e849f775c9368091482518825033f)) -* **otel:** remove TraceService.rootSpanMap and TraceService.setRootSpan() ([0c10347](https://github.com/waitingsong/midway-components/commit/0c103474a1dd3a1d6d1f0a003f7b56ff9fb52b73)) -* **otel:** rename OtelComponent.delScopeActiveContext() to emptyScopeActiveContext() ([8286b2b](https://github.com/waitingsong/midway-components/commit/8286b2b221ff9fc9d7245a2cc6fb11731ef2cbca)) -* **otel:** TraceLog supports end span ([0978a0c](https://github.com/waitingsong/midway-components/commit/0978a0ccf83b910d4e6f8f843bb67438774a3d25)) -* **otel:** update TraceService.getActiveContext() ([6124291](https://github.com/waitingsong/midway-components/commit/6124291929874c4ebdfa34feb2dc9b32519495a7)) - - - - - -## [36.1.3](https://github.com/waitingsong/midway-components/compare/v36.1.2...v36.1.3) (2024-08-06) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [36.1.2](https://github.com/waitingsong/midway-components/compare/v36.1.1...v36.1.2) (2024-08-06) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [36.1.1](https://github.com/waitingsong/midway-components/compare/v36.1.0...v36.1.1) (2024-08-06) - - -### Bug Fixes - -* **otel:** trace scope ([47b7cef](https://github.com/waitingsong/midway-components/commit/47b7cef8bfd1df6f30cbf4c64eafd0133598492b)) - - - - - -# [36.1.0](https://github.com/waitingsong/midway-components/compare/v36.0.0...v36.1.0) (2024-08-03) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [36.0.0](https://github.com/waitingsong/midway-components/compare/v35.2.1...v36.0.0) (2024-08-02) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [35.2.1](https://github.com/waitingsong/midway-components/compare/v35.2.0...v35.2.1) (2024-08-02) - - -### Bug Fixes - -* **otel:** param inner DecoratorHandlerTraceBase.traceError() ([30a26fd](https://github.com/waitingsong/midway-components/commit/30a26fdb677a48b749eb4e0355e8ec2162057070)) - - - - - -# [35.2.0](https://github.com/waitingsong/midway-components/compare/v35.1.0...v35.2.0) (2024-08-01) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [35.1.0](https://github.com/waitingsong/midway-components/compare/v35.0.1...v35.1.0) (2024-08-01) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [35.0.1](https://github.com/waitingsong/midway-components/compare/v35.0.0...v35.0.1) (2024-07-30) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [35.0.0](https://github.com/waitingsong/midway-components/compare/v34.0.1...v35.0.0) (2024-07-30) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [34.0.1](https://github.com/waitingsong/midway-components/compare/v34.0.0...v34.0.1) (2024-07-30) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [34.0.0](https://github.com/waitingsong/midway-components/compare/v33.0.0...v34.0.0) (2024-07-30) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [33.0.0](https://github.com/waitingsong/midway-components/compare/v32.0.0...v33.0.0) (2024-07-28) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [32.0.0](https://github.com/waitingsong/midway-components/compare/v31.0.0...v32.0.0) (2024-07-24) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [31.0.0](https://github.com/waitingsong/midway-components/compare/v30.21.0...v31.0.0) (2024-07-22) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.21.0](https://github.com/waitingsong/midway-components/compare/v30.20.0...v30.21.0) (2024-07-22) - - -### Features - -* **otel:** add util function ([df8b66e](https://github.com/waitingsong/midway-components/commit/df8b66e11e0f4a17f223881bf555eaf14914dad2)) - - - - - -# [30.20.0](https://github.com/waitingsong/midway-components/compare/v30.19.0...v30.20.0) (2024-07-15) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.19.0](https://github.com/waitingsong/midway-components/compare/v30.18.0...v30.19.0) (2024-07-14) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.18.0](https://github.com/waitingsong/midway-components/compare/v30.17.1...v30.18.0) (2024-07-12) - - -### Features - -* **otel:** decorator method spanName(), scope() support this param ([a438d22](https://github.com/waitingsong/midway-components/commit/a438d22e6f16394ffa8c11f22b3f8d0cff674737)) - - - - - -## [30.17.1](https://github.com/waitingsong/midway-components/compare/v30.17.0...v30.17.1) (2024-07-12) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.17.0](https://github.com/waitingsong/midway-components/compare/v30.16.1...v30.17.0) (2024-07-06) - - -### Features - -* **otel:** add HeadersKey.TRACE_PARENT_HEADER and TRACE_STATE_HEADER ([bdd1016](https://github.com/waitingsong/midway-components/commit/bdd10162435db729299cc911a8cabb43dee311e3)) -* **otel:** retrieveTraceparentFromHeader() ([e63eca2](https://github.com/waitingsong/midway-components/commit/e63eca25350b41590fb696b916c61eace8d10d16)) - - - - - -## [30.16.1](https://github.com/waitingsong/midway-components/compare/v30.16.0...v30.16.1) (2024-07-05) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.16.0](https://github.com/waitingsong/midway-components/compare/v30.15.2...v30.16.0) (2024-07-04) - - -### Features - -* **otel:** TraceLog accepts afterThrow callback via TraceDecoratorOptions['afterThrow'] ([3e38a51](https://github.com/waitingsong/midway-components/commit/3e38a51a2400971458fb8b4082b87ae53f0dc601)) - - - - - -## [30.15.2](https://github.com/waitingsong/midway-components/compare/v30.15.1...v30.15.2) (2024-07-03) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [30.15.1](https://github.com/waitingsong/midway-components/compare/v30.15.0...v30.15.1) (2024-07-02) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.15.0](https://github.com/waitingsong/midway-components/compare/v30.14.0...v30.15.0) (2024-07-02) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.14.0](https://github.com/waitingsong/midway-components/compare/v30.13.0...v30.14.0) (2024-06-12) - - -### Features - -* **otel:** move test.helper.ts to src/util/common.ts ([077e92c](https://github.com/waitingsong/midway-components/commit/077e92cdacd0a2bb929ed813358e6da7b0c6fd3d)) - - - - - -# [30.13.0](https://github.com/waitingsong/midway-components/compare/v30.12.1...v30.13.0) (2024-06-12) - - -### Features - -* **otel:** add generics MThis of TraceOptions ([72c59a4](https://github.com/waitingsong/midway-components/commit/72c59a4dbb115d1654471c30118fdb0a2d3eebf5)) -* **otel:** use ClzInstance isntead of InstanceWithDecorator ([0758993](https://github.com/waitingsong/midway-components/commit/0758993e180706a3364c6e28a7fab57971099079)) - - - - - -## [30.12.1](https://github.com/waitingsong/midway-components/compare/v30.12.0...v30.12.1) (2024-06-12) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.12.0](https://github.com/waitingsong/midway-components/compare/v30.11.2...v30.12.0) (2024-06-12) - - -### Features - -* **otel:** pass decorated instance as decorator before/after callback this param ([d9f99a7](https://github.com/waitingsong/midway-components/commit/d9f99a752573bfc9e506ae85faf57110d78764c1)) - - - - - -## [30.11.2](https://github.com/waitingsong/midway-components/compare/v30.11.1...v30.11.2) (2024-06-11) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [30.11.1](https://github.com/waitingsong/midway-components/compare/v30.11.0...v30.11.1) (2024-06-11) - - -### Bug Fixes - -* **otel:** key of span event name ([3071ea0](https://github.com/waitingsong/midway-components/commit/3071ea068a6cad443acc2dcaf210df19fca3b8d7)) - - - - - -# [30.11.0](https://github.com/waitingsong/midway-components/compare/v30.10.2...v30.11.0) (2024-06-11) - - -### Features - -* **otel:** expose DecoratorContext ([d7953e9](https://github.com/waitingsong/midway-components/commit/d7953e9efb8e196849b81c0bb5a9d5d7439a933e)) - - - - - -## [30.10.2](https://github.com/waitingsong/midway-components/compare/v30.10.1...v30.10.2) (2024-06-11) - - -### Bug Fixes - -* **otel:** ctx.status assignment within handleTopExceptionAndNext() in middleware/helper.middleware.ts ([60ce644](https://github.com/waitingsong/midway-components/commit/60ce644278e956ea5499764fb80ed148aaa354b4)) - - - - - -## [30.10.1](https://github.com/waitingsong/midway-components/compare/v30.10.0...v30.10.1) (2024-06-09) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.10.0](https://github.com/waitingsong/midway-components/compare/v30.9.1...v30.10.0) (2024-06-09) - - -### Bug Fixes - -* **otel:** isSpanEnded() in util.ts ([ba40cca](https://github.com/waitingsong/midway-components/commit/ba40ccaf2ce29181e8b654419f1feeaf50dd1cb2)) - - -### Features - -* **otel:** retrieve traceScope from methodArgs automatically ([644732d](https://github.com/waitingsong/midway-components/commit/644732d196b985516b72ac428f1c6ce75831800b)) - - - - - -## [30.9.1](https://github.com/waitingsong/midway-components/compare/v30.9.0...v30.9.1) (2024-06-08) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.9.0](https://github.com/waitingsong/midway-components/compare/v30.8.0...v30.9.0) (2024-06-08) - - -### Features - -* **otel:** update AttrNames ([a9c92fd](https://github.com/waitingsong/midway-components/commit/a9c92fd627e4ee40b7f74b8b918c109ed0b59b01)) - - - - - -# [30.8.0](https://github.com/waitingsong/midway-components/compare/v30.7.2...v30.8.0) (2024-06-07) - - -### Features - -* **otel:** decorator TraceLog() ([e427604](https://github.com/waitingsong/midway-components/commit/e4276040d9e45e9f62abd67f4fa1842114754b9e)) -* **otel:** update DecoratorTraceDataResp, DecoratorTraceDataRespAsync ([b604ca9](https://github.com/waitingsong/midway-components/commit/b604ca9866f3eed313c6680fb254a87325aca9de)) - - - - - -## [30.7.2](https://github.com/waitingsong/midway-components/compare/v30.7.1...v30.7.2) (2024-06-07) - - -### Bug Fixes - -* **otel:** DecoratorHandlerTraceInit.traceError() ([ab6f201](https://github.com/waitingsong/midway-components/commit/ab6f2010023c49ace75aa6b7132616bb0085d282)) - - - - - -## [30.7.1](https://github.com/waitingsong/midway-components/compare/v30.7.0...v30.7.1) (2024-06-07) - - -### Bug Fixes - -* **otel:** DecoratorHandlerTraceBase.traceError() ([9872643](https://github.com/waitingsong/midway-components/commit/98726437db7636d89002d3f3eae2373c7bd73fa8)) - - - - - -# [30.7.0](https://github.com/waitingsong/midway-components/compare/v30.6.1...v30.7.0) (2024-06-06) - - -### Features - -* **otel:** add properties of type DecoratorContextBase ([049d0de](https://github.com/waitingsong/midway-components/commit/049d0ded7209c7b1a2cb151cdb0beccdf119c208)) - - - - - -## [30.6.1](https://github.com/waitingsong/midway-components/compare/v30.6.0...v30.6.1) (2024-06-06) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.6.0](https://github.com/waitingsong/midway-components/compare/v30.5.0...v30.6.0) (2024-06-05) - - -### Features - -* **otel:** expose genTraceScope() ([74cfd8d](https://github.com/waitingsong/midway-components/commit/74cfd8d1d2740b7d843c96d185fabc664ffca61d)) - - - - - -# [30.5.0](https://github.com/waitingsong/midway-components/compare/v30.4.0...v30.5.0) (2024-06-05) - - -### Features - -* **otel:** Trace decorator accepts scope ([865bf31](https://github.com/waitingsong/midway-components/commit/865bf31fad008e9cb8871258446e2b6c8c398d00)) - - - - - -# [30.4.0](https://github.com/waitingsong/midway-components/compare/v30.3.0...v30.4.0) (2024-06-04) - - -### Bug Fixes - -* **otel:** check span ended within OtelComponent.getActiveContextFromArray() ([2c4d83f](https://github.com/waitingsong/midway-components/commit/2c4d83f37342afa688ad37d26a58a31a3da80a0a)) - - -### Features - -* **otel:** isSpanEnded() ([4e3e9a5](https://github.com/waitingsong/midway-components/commit/4e3e9a5907b2dcdc608ddbf329198037451c0a58)) - - - - - -# [30.3.0](https://github.com/waitingsong/midway-components/compare/v30.2.0...v30.3.0) (2024-06-04) - - -### Features - -* **otel:** add TraceService.startScopeActiveSpan() ([08c4534](https://github.com/waitingsong/midway-components/commit/08c45346b226afbda99fc1cd87d3bcf76f8da218)) - - - - - -# [30.2.0](https://github.com/waitingsong/midway-components/compare/v30.1.1...v30.2.0) (2024-06-04) - - -### Features - -* **otel:** add TraceService.delActiveContext() ([bbf3d3b](https://github.com/waitingsong/midway-components/commit/bbf3d3bfd216b6d78b822e14bf7310969bad8ccd)) -* **otel:** TraceService.getActiveContext() accepts optional param scope ([5d8d235](https://github.com/waitingsong/midway-components/commit/5d8d235ad1a43843a21356a2f8c55faf42397d9d)) -* **otel:** TraceService.getActiveSpan()/startSpan()/startActiveSpan() accepts optional param scope ([5013d60](https://github.com/waitingsong/midway-components/commit/5013d60a2653bc2c2122356d6561912347e7b79d)) -* **otel:** TraceService.setActiveContext() accepts 2nd param scope ([3c13781](https://github.com/waitingsong/midway-components/commit/3c137814da5ae37bf64db654f7ed1f0503bbb914)) - - - - - -## [30.1.1](https://github.com/waitingsong/midway-components/compare/v30.1.0...v30.1.1) (2024-06-04) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [30.1.0](https://github.com/waitingsong/midway-components/compare/v30.0.0...v30.1.0) (2024-06-03) - - -### Features - -* **otel:** manage trace Context on OtelComponent ([dc55f8e](https://github.com/waitingsong/midway-components/commit/dc55f8e7782208227117c7fe82aa9e46ff61f85f)) - - - - - -# [30.0.0](https://github.com/waitingsong/midway-components/compare/v29.3.1...v30.0.0) (2024-06-02) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [29.3.1](https://github.com/waitingsong/midway-components/compare/v29.3.0...v29.3.1) (2024-05-31) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [29.3.0](https://github.com/waitingsong/midway-components/compare/v29.2.0...v29.3.0) (2024-05-31) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [29.2.0](https://github.com/waitingsong/midway-components/compare/v29.1.0...v29.2.0) (2024-05-30) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [29.1.0](https://github.com/waitingsong/midway-components/compare/v29.0.1...v29.1.0) (2024-05-29) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [29.0.1](https://github.com/waitingsong/midway-components/compare/v29.0.0...v29.0.1) (2024-05-28) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [29.0.0](https://github.com/waitingsong/midway-components/compare/v28.2.0...v29.0.0) (2024-05-27) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [28.2.0](https://github.com/waitingsong/midway-components/compare/v28.1.1...v28.2.0) (2024-05-24) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [28.1.1](https://github.com/waitingsong/midway-components/compare/v28.1.0...v28.1.1) (2024-05-24) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [28.1.0](https://github.com/waitingsong/midway-components/compare/v28.0.0...v28.1.0) (2024-05-23) - - -### Features - -* **otel:** set enableMiddleware to true in config.default.ts ([a5f34a3](https://github.com/waitingsong/midway-components/commit/a5f34a34bf4ff3cd9f15054bd1aa15ca20c68fa3)) - - - - - -# [28.0.0](https://github.com/waitingsong/midway-components/compare/v27.0.1...v28.0.0) (2024-05-23) - - -### Features - -* **otel:** breaking change parameters order and return type of decorator before()/after() ([f8eb988](https://github.com/waitingsong/midway-components/commit/f8eb98831a6e4deb25e7c1867e7bec3cc9e8dfe2)) - - - - - -## [27.0.1](https://github.com/waitingsong/midway-components/compare/v27.0.0...v27.0.1) (2024-05-22) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [27.0.0](https://github.com/waitingsong/midway-components/compare/v26.5.3...v27.0.0) (2024-05-21) - - -### Features - -* **otel:** breaking change functions ([a6d5459](https://github.com/waitingsong/midway-components/commit/a6d54596ee5e620bc690eb5f7436875e134d3787)) -* **otel:** process span name correctly ([6773857](https://github.com/waitingsong/midway-components/commit/6773857c6e8541ff830010013a055b26873f6643)) - - - - - -## [26.5.3](https://github.com/waitingsong/midway-components/compare/v26.5.2...v26.5.3) (2024-05-21) - - -### Bug Fixes - -* **otel:** tracing event if ctx.path matched otelMiddlewareConfig.ignore lists ([4c1d55c](https://github.com/waitingsong/midway-components/commit/4c1d55c7aa92e8cc448935a34c8ea609fed8ef5a)) - - - - - -## [26.5.2](https://github.com/waitingsong/midway-components/compare/v26.5.1...v26.5.2) (2024-05-09) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [26.5.1](https://github.com/waitingsong/midway-components/compare/v26.5.0...v26.5.1) (2024-04-25) - - -### Bug Fixes - -* **otel:** import assert {type} to import with {type} ([c788e6b](https://github.com/waitingsong/midway-components/commit/c788e6b0fd22a752979b9a6fb44f188a94278bf2)) - - - - - -# [26.5.0](https://github.com/waitingsong/midway-components/compare/v26.4.0...v26.5.0) (2024-04-24) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [26.4.0](https://github.com/waitingsong/midway-components/compare/v26.3.2...v26.4.0) (2024-04-24) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [26.3.2](https://github.com/waitingsong/midway-components/compare/v26.3.1...v26.3.2) (2024-04-24) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [26.3.1](https://github.com/waitingsong/midway-components/compare/v26.3.0...v26.3.1) (2024-04-23) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [26.3.0](https://github.com/waitingsong/midway-components/compare/v26.2.1...v26.3.0) (2024-04-23) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [26.2.0](https://github.com/waitingsong/midway-components/compare/v26.1.0...v26.2.0) (2024-04-22) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [26.1.0](https://github.com/waitingsong/midway-components/compare/v26.0.2...v26.1.0) (2024-04-22) - - -### Features - -* **otel:** update TraceInit span name for MidwayJs lifeCycle ([541c47c](https://github.com/waitingsong/midway-components/commit/541c47c11b8a541ed1e70cfca2fdf6f1792725f5)) - - - - - -## [26.0.2](https://github.com/waitingsong/midway-components/compare/v26.0.1...v26.0.2) (2024-04-22) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [26.0.0](https://github.com/waitingsong/midway-components/compare/v25.2.3...v26.0.0) (2024-04-21) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [25.2.3](https://github.com/waitingsong/midway-components/compare/v25.2.2...v25.2.3) (2024-04-14) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [25.2.2](https://github.com/waitingsong/midway-components/compare/v25.2.1...v25.2.2) (2024-04-09) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [25.2.1](https://github.com/waitingsong/midway-components/compare/v25.2.0...v25.2.1) (2024-04-09) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [25.2.0](https://github.com/waitingsong/midway-components/compare/v25.1.0...v25.2.0) (2024-04-09) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [25.1.0](https://github.com/waitingsong/midway-components/compare/v25.0.2...v25.1.0) (2024-04-09) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [25.0.2](https://github.com/waitingsong/midway-components/compare/v25.0.1...v25.0.2) (2024-04-08) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [25.0.1](https://github.com/waitingsong/midway-components/compare/v25.0.0...v25.0.1) (2024-04-08) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [25.0.0](https://github.com/waitingsong/midway-components/compare/v24.2.4...v25.0.0) (2024-04-08) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [24.2.4](https://github.com/waitingsong/midway-components/compare/v24.2.3...v24.2.4) (2024-04-08) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [24.2.3](https://github.com/waitingsong/midway-components/compare/v24.2.2...v24.2.3) (2024-04-08) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [24.2.2](https://github.com/waitingsong/midway-components/compare/v24.2.1...v24.2.2) (2024-04-07) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [24.2.1](https://github.com/waitingsong/midway-components/compare/v24.2.0...v24.2.1) (2024-04-05) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [24.2.0](https://github.com/waitingsong/midway-components/compare/v24.1.0...v24.2.0) (2024-04-05) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [24.1.0](https://github.com/waitingsong/midway-components/compare/v24.0.0...v24.1.0) (2024-04-05) - - -### Features - -* **otel:** update AttrNames ([d0362e2](https://github.com/waitingsong/midway-components/commit/d0362e2205f83e678156fdc508b31c137ed6836c)) - - - - - -# [24.0.0](https://github.com/waitingsong/midway-components/compare/v23.2.0...v24.0.0) (2024-04-03) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [23.1.0](https://github.com/waitingsong/midway-components/compare/v23.0.0...v23.1.0) (2024-04-02) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [23.0.0](https://github.com/waitingsong/midway-components/compare/v22.1.2...v23.0.0) (2024-03-27) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [22.1.2](https://github.com/waitingsong/midway-components/compare/v22.1.1...v22.1.2) (2024-03-08) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [22.1.0](https://github.com/waitingsong/midway-components/compare/v22.0.1...v22.1.0) (2024-03-05) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [22.0.1](https://github.com/waitingsong/midway-components/compare/v22.0.0...v22.0.1) (2024-02-26) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [22.0.0](https://github.com/waitingsong/midway-components/compare/v21.1.0...v22.0.0) (2024-02-25) - - -### Bug Fixes - -* **otel:** breaking change var type ..Decortaor.. to ..Decorator from @mwcp/share ([0984de2](https://github.com/waitingsong/midway-components/commit/0984de236e6bfd0eae705e5fb53015df01eca5bb)) - - - - - -# [21.0.0](https://github.com/waitingsong/midway-components/compare/v20.12.0...v21.0.0) (2024-02-25) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [20.12.0](https://github.com/waitingsong/midway-components/compare/v20.11.1...v20.12.0) (2024-02-25) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [20.11.0](https://github.com/waitingsong/midway-components/compare/v20.10.1...v20.11.0) (2024-02-22) - -**Note:** Version bump only for package @mwcp/otel - - - - - -## [20.10.1](https://github.com/waitingsong/midway-components/compare/v20.10.0...v20.10.1) (2024-02-03) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [20.10.0](https://github.com/waitingsong/midway-components/compare/v20.9.0...v20.10.0) (2024-02-02) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [20.9.0](https://github.com/waitingsong/midway-components/compare/v20.8.1...v20.9.0) (2024-01-27) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [20.8.0](https://github.com/waitingsong/midway-components/compare/v20.7.0...v20.8.0) (2024-01-26) - - -### Features - -* deleteRouter if enableDefaultRoute false ([bc4027e](https://github.com/waitingsong/midway-components/commit/bc4027ed6c4233ee906dee9bae97986ff9f5e1c2)) - - - - - -# [20.7.0](https://github.com/waitingsong/midway-components/compare/v20.6.0...v20.7.0) (2024-01-26) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [20.6.0](https://github.com/waitingsong/midway-components/compare/v20.5.0...v20.6.0) (2024-01-26) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [20.5.0](https://github.com/waitingsong/midway-components/compare/v20.4.0...v20.5.0) (2024-01-26) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [20.3.0](https://github.com/waitingsong/midway-components/compare/v20.2.0...v20.3.0) (2024-01-25) - -**Note:** Version bump only for package @mwcp/otel - - - - - -# [20.0.0](https://github.com/waitingsong/midway-components/compare/v19.2.5...v20.0.0) (2024-01-21) - -**Note:** Version bump only for package @mwcp/otel diff --git a/packages/otel/LICENSE b/packages/otel/LICENSE deleted file mode 100644 index 050e16851..000000000 --- a/packages/otel/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -The MIT License (MIT) - -Copyright (c) waiting - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/otel/README.md b/packages/otel/README.md deleted file mode 100644 index 9c00de1e3..000000000 --- a/packages/otel/README.md +++ /dev/null @@ -1,308 +0,0 @@ -# @mwcp/otel - -Open Telemetry Component for Midway.js - -[![GitHub tag](https://img.shields.io/github/tag/waitingsong/midway-components)]() -[![Version](https://img.shields.io/npm/v/@mwcp/otel.svg)](https://www.npmjs.com/package/midway-components) -[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) -[![](https://img.shields.io/badge/lang-TypeScript-blue.svg)]() -[![ci](https://github.com/waitingsong/midway-components/actions/workflows/nodejs.yml/badge.svg -)](https://github.com/waitingsong/midway-components/actions) -[![codecov](https://codecov.io/gh/waitingsong/midway-components/branch/main/graph/badge.svg?token=lbfTIGwu6t)](https://codecov.io/gh/waitingsong/midway-components) -[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) -[![lerna](https://img.shields.io/badge/maintained%20with-lerna-cc00ff.svg)](https://lernajs.io/) - - -## Note - -ESM build only, requires `@midwayjs >= 3.16` and set `"type": "module"` in `packages.json` - -## Support Schemes - -- HTTP -- [gRPC (Unary)] - -## Install - -```sh -npm i @mwcp/otel -``` - -## Configuration - -Update project `src/configuration.ts` -```ts -import { Configuration } from '@midwayjs/decorator' -import * as koa from '@midwayjs/koa' -import * as otel from '@mwcp/otel' - -@Configuration({ - imports: [ - koa, - otel, - ], - importConfigs: [join(__dirname, 'config')], -}) -export class ContainerConfiguration implements ILifeCycle { -} -``` - -## Usage - -- [Exporter][Exporter] -- [Exporter Configuration][Exporter Configuration] - -To try out the [OTLPTraceExporter][Exporter Configuration] quickly, you can run [Jaeger] in a docker container: -```sh -docker run -d --name jaeger \ - -e COLLECTOR_OTLP_ENABLED=true \ - -p 4317:4317 \ - -p 4318:4318 \ - -p 5778:5778 \ - -p 6831:6831/udp \ - -p 6832:6832/udp \ - -p 16686:16686 \ - jaegertracing/all-in-one:latest -``` - -Start project: -```sh -export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 -npm start -``` - -[Jaeger] Web UI address: -> http://localhost:16686/ - - -## `Trace` Decorator - -```ts -import { Trace } from '@mwcp/otel' - -@Controller('/') -export class FooController { - - @Inject() readonly svc: FooService - - /* span name will be `{class name}/{method name}` => "FooController/hello" */ - @Trace() - async hello(): Promise { - return 'hello' - } - - /* span name will be "hello" */ - @Trace('hello') - async world(): Promise { - return 'world' - } - - @Trace({ - spanName: 'hello' - }) - async world2(): Promise { - return 'world' - } -} -``` - -Pass `scope` to avoid the confusion of call chain relationship when async methods are called concurrently - -```ts -import { Trace } from '@mwcp/otel' - -@Controller('/') -export class FooController { - @Trace() - async hello(): Promise { - await Promise.all([ - this._simple1(), - this._simple2(), - ]) - return 'OK' - } - - @Trace({ scope: 'hello1' }) - async _hello1(): Promise { - return 'world' - } - - @Trace({ scope: 'hello2' }) - async _hello2(): Promise { - return 'world' - } - - @Trace({ scope: 'hello1' }) - async _hello1a(): Promise { - return 'world' - } - - @Trace({ scope: 'hello2' }) - async _hello2a(): Promise { - return 'world' - } -} -``` -![Trace Info](img/trace-scope.png) - - -Use `this` inner `before()` `after()` point to the decorated instance - -```ts -export class FooService { - foo = 1 - - @Trace({ - before([options], decoratorContext) { - assert(this instanceof FooService) // <--- this point to FooService - assert(this === decoratorContext.instance) - assert(this.foo === 1) - - return void 0 - }, - after([options], res, decoratorContext) { - assert(this instanceof FooService) - assert(this === decoratorContext.instance) - assert(this.foo === 1) - - return void 0 - }, - }) - async home(this: FooService, options: InputOptions): Promise { // <--- pass this type explicitly - const ret = await options.input - return ret - } -} -``` - - -## `TraceLog` Decorator - -Add trace attribute to the span through decorator before()/after() method return object, -no new span starting -- add trace tag/log to current active span -- add trace tag/log to root span - -Note return value of decorated method `before()` and `after()` should be type: -```ts -interface DecoratorTraceData { - attrs?: Attributes - events?: Attributes - rootAttrs?: Attributes - rootEvents?: Attributes -} -``` - - -```ts -import { TraceLog, DecoratorTraceData } from '@mwcp/otel' - -@Controller('/') -export class FooController { - - @Trace() - async hello(): Promise { - return 'hello' - } - - @TraceLog({ - before: async ([input], { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } as DecoratorTraceData - }, - after: ([input], res, { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - async world(): Promise { - return 'world' - } -} -``` - - -## `TraceInit` Decorator - -```ts -// src/configuration.ts -import { TraceInit } from '@mwcp/otel' - -export class AutoConfiguration implements ILifeCycle { - @TraceInit({ namespace: 'Foo' }) - async onReady(container: IMidwayContainer): Promise { - // some code - } -} -``` - - -## Decorator Generics -### Auto parameter type of keyGenerator from generics - -```ts -@Controller('/') -export class FooController { - - @Inject() readonly svc: FooService - - hello(): string { - // spanName should be 'foo-124-abc' - const msg = this.svc.concat(123, 'abc') - return msg - } -} - -@Provide() -export class FooService { - @Trace({ - spanName: ([v1, v2]) => `foo-${v1 + 1}-${v2}`, - }) - concat(v1: number, v2: string): string { - return `${v1.toString()}-${v2}` - } - - @Trace({ - spanName: (args) => `foo-${args[0] + 1}-${args[1]}`, - }) - concat2(v1: number, v2: string): string { - return `${v1.toString()}-${v2}` - } -} -``` - - -## License -[MIT](LICENSE) - - -### Languages -- [English](./README.md) -- [中文](./README.zh-CN.md) - -
- -[Exporter]: https://opentelemetry.io/docs/instrumentation/js/exporters/ -[Exporter Configuration]: https://opentelemetry.io/docs/reference/specification/protocol/exporter/#configuration-options -[Jaeger]: https://www.jaegertracing.io/ - -[gRPC (Unary)]: https://github.com/midwayjs/midway/tree/main/packages/grpc - diff --git a/packages/otel/README.zh-CN.md b/packages/otel/README.zh-CN.md deleted file mode 100644 index 000ae4ac5..000000000 --- a/packages/otel/README.zh-CN.md +++ /dev/null @@ -1,312 +0,0 @@ -# @mwcp/otel - -Open Telemetry Component for Midway.js - -[![GitHub tag](https://img.shields.io/github/tag/waitingsong/midway-components)]() -[![Version](https://img.shields.io/npm/v/@mwcp/otel.svg)](https://www.npmjs.com/package/midway-components) -[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) -[![](https://img.shields.io/badge/lang-TypeScript-blue.svg)]() -[![ci](https://github.com/waitingsong/midway-components/actions/workflows/nodejs.yml/badge.svg -)](https://github.com/waitingsong/midway-components/actions) -[![codecov](https://codecov.io/gh/waitingsong/midway-components/branch/main/graph/badge.svg?token=lbfTIGwu6t)](https://codecov.io/gh/waitingsong/midway-components) -[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) -[![lerna](https://img.shields.io/badge/maintained%20with-lerna-cc00ff.svg)](https://lernajs.io/) - - -## Note - -ESM build only, requires `@midwayjs >= 3.16` and set `"type": "module"` in `packages.json` - - -## 支持协议 - -- HTTP -- [gRPC (Unary)] - -## 安装依赖 - -```sh -npm i @mwcp/otel -``` - -## 更新配置 - -Update project `src/configuration.ts` -```ts -import { Configuration } from '@midwayjs/decorator' -import * as koa from '@midwayjs/koa' -import * as otel from '@mwcp/otel' - -@Configuration({ - imports: [ - koa, - otel, - ], - importConfigs: [join(__dirname, 'config')], -}) -export class ContainerConfiguration implements ILifeCycle { -} -``` - -## 使用 - -- [Exporter][Exporter] -- [Exporter Configuration][Exporter Configuration] - -使用 [Jaeger] 容器快速启动一个 [OTLPTraceExporter][Exporter Configuration] 服务: -```sh -docker run -d --name jaeger \ - -e COLLECTOR_OTLP_ENABLED=true \ - -p 4317:4317 \ - -p 4318:4318 \ - -p 5778:5778 \ - -p 6831:6831/udp \ - -p 6832:6832/udp \ - -p 16686:16686 \ - jaegertracing/all-in-one:latest -``` - -启动项目: -```sh -export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 -npm start -``` - -Jaeger Web UI address: -> http://localhost:16686/ - - -## `Trace` 装饰器 - -```ts -import { Trace } from '@mwcp/otel' - -@Controller('/') -export class FooController { - - @Inject() readonly svc: FooService - - /* span name will be `{class name}/{method name}` => "FooController/hello" */ - @Trace() - async hello(): Promise { - return 'hello' - } - - /* span name will be "hello" */ - @Trace('hello') - async world(): Promise { - return 'world' - } - - @Trace({ - spanName: 'hello' - }) - async world2(): Promise { - return 'world' - } -} -``` - -使用 `scope` 避免异步方法并发请求时调用链混乱 - -```ts -import { Trace } from '@mwcp/otel' - -@Controller('/') -export class FooController { - - @Trace() - async hello(): Promise { - await Promise.all([ - this._simple1(), - this._simple2(), - ]) - return 'OK' - } - - @Trace({ scope: 'hello1' }) - async _hello1(): Promise { - return 'world' - } - - @Trace({ scope: 'hello2' }) - async _hello2(): Promise { - return 'world' - } - - @Trace({ scope: 'hello1' }) - async _hello1a(): Promise { - return 'world' - } - - @Trace({ scope: 'hello2' }) - async _hello2a(): Promise { - return 'world' - } -} -``` - -![Trace Info](img/trace-scope.png) - - -在 `before()` `after()` 内使用指向被装饰类实例的 `this` - -```ts -export class FooService { - foo = 1 - - @Trace({ - before([options], decoratorContext) { - assert(this instanceof FooService) // <--- this point to FooService - assert(this === decoratorContext.instance) - assert(this.foo === 1) - - return void 0 - }, - after([options], res, decoratorContext) { - assert(this instanceof FooService) - assert(this === decoratorContext.instance) - assert(this.foo === 1) - - return void 0 - }, - }) - async home(this: FooService, options: InputOptions): Promise { // <--- pass this type explicitly - const ret = await options.input - return ret - } -} -``` - -## `TraceLog` 装饰器 - -通过装饰器的 `before()`/`after()` 方法返回对象给当前Span和根Span添加 tag/log 信息, -不会新建 Span - -装饰器参数 `before()` `after()` 返回类型应该是: -```ts -interface DecoratorTraceData { - attrs?: Attributes - events?: Attributes - rootAttrs?: Attributes - rootEvents?: Attributes -} -``` - - -```ts -import { TraceLog, DecoratorTraceData } from '@mwcp/otel' - -@Controller('/') -export class FooController { - - @Trace() - async hello(): Promise { - return 'hello' - } - - @TraceLog({ - before: async ([input], { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } as DecoratorTraceDataResp - }, - after: ([input], res, { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - async world(): Promise { - return 'world' - } -} -``` - - - -## `TraceInit` 装饰器 - -```ts -// src/configuration.ts -import { TraceInit } from '@mwcp/otel' - -export class AutoConfiguration implements ILifeCycle { - @TraceInit({ namespace: 'Foo' }) - async onReady(container: IMidwayContainer): Promise { - // some code - } -} -``` - - - - - -## 装饰器泛型参数 -### 从泛型参数自动获取方法调用参数类型 - -```ts -@Controller('/') -export class FooController { - - @Inject() readonly svc: FooService - - hello(): string { - // spanName should be 'foo-124-abc' - const msg = this.svc.concat(123, 'abc') - return msg - } -} - -@Provide() -export class FooService { - @Trace({ - spanName: ([v1, v2]) => `foo-${v1 + 1}-${v2}`, - }) - concat(v1: number, v2: string): string { - return `${v1.toString()}-${v2}` - } - - @Trace({ - spanName: (args) => `foo-${args[0] + 1}-${args[1]}`, - }) - concat2(v1: number, v2: string): string { - return `${v1.toString()}-${v2}` - } -} -``` - - -## License -[MIT](LICENSE) - - -### Languages -- [English](./README.md) -- [中文](./README.zh-CN.md) - -
- -[Exporter]: https://opentelemetry.io/docs/instrumentation/js/exporters/ -[Exporter Configuration]: https://opentelemetry.io/docs/reference/specification/protocol/exporter/#configuration-options -[Jaeger]: https://www.jaegertracing.io/ - -[gRPC (Unary)]: https://github.com/midwayjs/midway/tree/main/packages/grpc - diff --git a/packages/otel/bootstrap.js b/packages/otel/bootstrap.js deleted file mode 100644 index 01b9c2c35..000000000 --- a/packages/otel/bootstrap.js +++ /dev/null @@ -1,2 +0,0 @@ -import { Bootstrap } from '@midwayjs/bootstrap'; -await Bootstrap.run(); diff --git a/packages/otel/img/trace-scope.png b/packages/otel/img/trace-scope.png deleted file mode 100644 index 5ead1f15c73223d58e7195b07ca27eaed10c84fe..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 33633 zcmZU)2RK|`)Hf=PAV}26Nc0jt#E9Oa*Qn8x7z8tj-bD}5MrV|W-WiM*B&B@b_%+X2tv|NCOZbo`YswUpYY}D3BD&9>^ACT%g+*T70 z51mh)`7yR?YW^DviKm(B+xD}msj1A@=>n5OPfw3JJzHE{yzTR;d9mXYa_~nkjEag1 zi^Xc*&|Et_-rB0?i%t*DnH?D!adr5rnl^#T{zyfYtIp1rWhY@_Aa%9ffybnlKDzZN z>Pu8kx{6g`9=z=om4WB?qZi7MOGUM|bFj6w^}`Qu_X2xzGB@zWp=EMYMP1b)v-e}$ zNn-yc9UW+{I`$nk-uUMBEzi2&*;;T2^TO#_U}s+f3$su2HXB=Faq~DE8{0?RA0D0? zH0|)!+y*uJ-VE`^+A;ZgaD*GF3~Px*J~d&F5)OZfQ$0r!8ZV}6`c?0y9~D&z)D}`OT?|Ju z1jiYyt?J^QfgA5s6<WxG&f^x0GH%JU|j2ZZrrVq zV&U17C;#=l6AqTT{ck+5<66?|e%G>6-9U4SA_Bpknuz(bvn$JUf0B0V58h8N9^58* zh!*{saAck(#5~#R$k9$+QgAy2EWhY89BB=sU+$>~8`rN7+>28NlN;4<7wo^^`yKv_ z9{ruT zBseehV$}vCCC%w?Q$0buaTS~TV=v)YNuV!8`x13@@qQ>_^TadDR>|$f^Hq>wIR^o} z@1f()s5u<+7mctL9Vnc<0hjr~4kH;uQ1hdEXJwdRD-rksU}G+~ zjqpE^TPldKHXeF#5@jYM=ExDG#tDbS_F76IkDLcWv_s=#M1t(M{Gqk|unzx*a}_AW z+kX0Wd98no+;JTij=d%J-Zqp@&S;4%lRk;i)wpgX-{sf%GZFJ}w)6;^)0DEQbA_ZRdTRgY$b~SXWkAa=f)7}e=_zX7g5mgHSp$}0=g$xS}C^hYCryBdu`#%+4W{l}f zwlZ)Dp$|&&Qzz0k&*@zUVp=pshe#WEMrP0Bpi$QNG2n78rj_>iaVn)JV83&JL*d`2 zMho?i2jqA+z?UuHsiGqXqY3@HlZa6Borw%zK{=q)^pWFM3VO;rpG!%@Ao=-^UEgn& zdaJeed0SCy-cm5p{xvUI(_^>2wSfymHY+6+u$a(sUd(=|)GQS19+b7i;Tqj0ttEC9 z=W}_%ZyC4tuodheo}qE>vc?GeA^k-j?xt{1PeJPda`8@X@n+z+vB6 zIeyFJ=J-`+?vQKjRVt+py^t6(PH0TLcHqeZf1;&*&8=x_b4N?@i(q_1iu>s zpM&-leMUQcrlm_3G!|OzC??NH5YN14l*|DlQd4^?&ys~ozV}%%3!zDcLQUT*|It50 zrd-BHg%1{IAnL6%XegN<9rIwpA_o~Fppn>Y*4Be>lILKN30hgv$1#XWV8A=muP;{9dvAz#!LSf6p>a^ zzkIaMocjz$i3$j*7}0GL8($zLqe^EetHw^s*QEA>T%)qM6(XKWUV2pb76f71K7hn> ztzVpbI7T!j^W6}64steqRpdq-&84IY{4kZdQk4OS7E^!N>;jRmpMBHw648UOlXJXy z3erips|B2#p|`PRVZa!0SwnnO{72FABGNWRD?U!cZ^O@gnPC=k%?3vBU7Hd0!2swb z|D{2{!ThVYO`s%eM>>|RJORnLDS#`Cc254a*=jA6tg?(t> z6ituqT~1NB-X)(uv{Q&#SnXCL{cUcpjs9^?3g@i1teZLos~EoJv+< z7BMWWfT(p~=4pedS$5LsQ3!Zu;^u+?54x1qi5*7cXc>(zz68s?kIHPJI@h{Y+;=+Z zK}RU|3?@M%g+91laEM5b{y-$7(*?GeQc-6A1PAqG2>VbAwqOr(N4gguRtJE!Ud2Tz zz;{)ZlA7N4+^<%SF=9e*@5gUR=BF52uf;~m3C&OZfS@=zv9(Yv{or^ajKb0Mfe3jw zRj;N7aEY&UA=-IKqZeq^D@~=pbNVMtCw41Z^v)Vu`$5~=G*(QRSeqVAByF|5+f8)g zBRR6WUksAP1(xB7b7>U5%$PMGFrKh@?Y><~dHED-IT5znC6V9>T6n?&5E-cR96I&& zPNmtp*nfQPRwFuVnQM>CO^%25(M9eL=2@f*DI=+^pT>aO1f9Q|?8Wwn8If65XX$po z_k;I2o}s0Ig)dMF6;aI*VL(UGkecC;`@SRHl8LJD$ zoxQ#s_DcqPazyn8fF%t;9Lx1LGfE?w0j~Xq-CLed9{&z8e(WwP4LX&&ty{`gxF%2fEV{;nV7S*ww6*g({@QQzv-{QRb( zI;l*i7Agr(wO4{XZ78;OvHO-{_f&n@*dYlsQA=wTDHAxvjkZ!UB$kU-eJ%qme2rSZ z?yeeec1oPe#0}@1D0OAqCt=dCbF4B zD01X^H1zX?vaf=kW(?Rh(=%cEeLHlqI@9#$jkA!-Q>56h%PT=P1GqZeSElh}P*ZMk ze>GYOb&+($Xa!&n;yBPr^JMNZ7{9pidx#L{m zq^$XvcWfBGJR_(3Q*)VQ3&OPoX<&Nvef(bx?|;RsbG{4}MCbBa@Hbi=`J9l(k_0lu zLS7Vct-4cRJK3OHI2*@#TtG^z4ETj?{N<@C`tmBBdE;xr9cXjQs|LglDU}SZD zju5dv^v`E^-C8YwTQoEg_}Bf{H37AIGc*2Wi5v5Ox%?c~aO{(7mj4&^Zy*r(B^~v5 zRtAnYpmQ^hd)Glkz=KY3<<0+3O!0pO8-G3h|0q-}=$RXTLyN!C1`;KKTdxC#z%SBJ zlIzewM(c|U^Si$x$X_A8w6Ox<(Cc93AMt<1CD#hUN&jg1=YrDKQP0K(eV}}`!KTjP zVKVjLX^l_8<<;{Ag!Fw%yz3SH(@Wq>1br)o5_||%TI0;TzHx;}7q8PyX5;?NW9T4x z9F7Kmc=v8!^r>z*NU2!jXJozSg-D1b0;E_&j^ zzQuQM=FAUTc3{5Yk9hkL<+hC#KBN_RigNq&$7b5*$UD2m517evH;^bC+|F)QeTf;M zn7vuM*$P%4c&IW?u!}H_itquRML(wt8KY#H2L(31!Q*>)q2ctpl9GB(^<0aSNN{b zt$g*oKPqZFOt@#jK4gbt_O(aWNkkW=ru7Gj^zw|D6&QFck!D;M~ABpa!uuueNK8OEd0oUC=T^DSS3K(+<}( zd$dh}w*8j-*z~x$npC9Yby=wupTWJ_O259L?(GpfbOa5()8>?u3>E+w?X4mh%XGl0 zsKQb7Mmqs)wAfo6T9E#FvF2=JeLe~cx4rC(6O94e4m2@AM1{r`m!e*8tKKF-j@_^x9=9~yaTO{rp&8wMr^FPY^6KE^?Y@v7@9PHu7}Hjy=gk4a=3$fWEoQ9zjQnG(h;lU4g;4&r#l8wc+m)2;{9|H@b597kxH*e3 z_|UV}Er}Il1W93Ur9SH0Uq3>1JtFhzn-p=9q;DJr*IQYNqf0$qq3l_|h`qNC4O2<3 zF1gha4j74@!u@!j%TU|JRw3OPlACCJ7c+r!><&OCcB5F}uC7V_LD?Dt{UOuy8qzI^x!$%}Z?jz|nzt;nbfpvF9l> zrv4QP+)f{3D_O2UIyxF}Z-2121fp6KKuw+Z&gNApE%VM6RyJ;N&6Lu1yLk=wmb{4M z-PUf#-U0|0b3~k4ZuW*n4@OH|IZI~Qouehlio-KAGb_S9i=v3tq3jvIlv|568I1ex zG-A&H12pg=o>|>Go9wAhM5cSmxtosWK&R`ja6-bM_luPB2e|cRfXA@R#y1qeMFGTc z+LY1OqgNz6PVQS|PWo}hL|2{w|0e&$*7b@^7E;)L7!NVUxs8HJ+l>3HS@!J^61$nS z+zkqA7UMW>z?x1uD96qb4u+nAeAOS!ehR3;d4U?(+5M+lHHSK)9W5bV!txjF^y6+{ zE2BBQNWyBNTkmd1e?%9HEe>m3{x()iLTc`e(8|m;%Jaw@OmTF#1~ZCQO_PbIJHA_w zm@tt|GVyMS&bP=p`8})OeLfvpi5Z}Fms2Ke4*Q$f$OGyaJexkny&A+keVdZDBbYSL zEBPKMmVXEY@D-}N6hz;g>5i*=y|1oZ`k=eRw`(-cTtfxHLTh!7J7yY)#O$7svNK}t z5?G4FZrzEmfxQVAk==3o+(0caMbzxKz;=$rclVI+cUV*Xtcv$�dU$zueF!M(qbq z@o7cMkkW+;JRTr#WK6E( z$#0r%f5#k+rdJ+%tyWWsR>bsfy#Vo=0kh`)O}1_3VO)a6q-nc@RaqlH1`EzN$(f+Z z+Z1~Bo(>J)wEny~_62+zP2%+Y*@c6wp>ovaK9HuUZu`$kUdye)JnR+qs}lDoe#bU6 z=*-+@^OAs1T*|O_c}6RGf80d0u$=PmOBV78Wo38K z@u1ugas`0NPIpu}7rnM%I(AuL2V-&cygf&1o)qiVUz?zMisqcxeM9qMLG0GM9QG^n85oZ*bfm5 zu*KOW;(Hv#dSI1T*2rRFH8VqGrlrd^mM0ceqQ!urFMz{0Zm9t?-p5zHc_2qvk)R=F z`Y60s*z#4zUhc3)Z&6hG+n@xra`L_BXpZ;B`{TJSP<80{QRhLSHRdTM5eZSfy4Rg( z*#VJSC|MIIr%1KW{e~QHO^8|Cs}@?reFy#Rxm{F?KeO6?nFet0?c>=~hr%t1+vuAr zi1p|pv)u6)jX9zP7=xj)yYM?ua8r*cd6H{Fq8{a-{8UO~R+)u0JWp(=SV;~@TdB|a z*6^jb!jtEvbaOwH*#@=dZhLOp9WaO^)(-Kcn_uT%+^2J5)#VUva8$p+!WMZG~|JJaMqho$``W)mvFLvQZvip&eRGhzL<;VV&>91#V0oLAL zGrnn0{M4C~He$+mY#RA9St$cbX(vW%{?v|eqcgu%`k4$=3`|taDVfAwxyQ16-7?sf zT3*)2!g5$|eR3G2u?U#Wbc*X=Lm5kF>g5}*_Ei`b&&s@;eeiYjX!6L>2MEtJGuvBq z@||?yStsosXBgjMXt0ob1WzTQDL)-@R|CeGkvjjF$q@yh%ng(5FTzN6g-16e=vd%o zmyi5(-)Lct!#-cGkHg439Ky9*3~1<5oRC7*XsIpZ)s{^D zA82i64JnLa>+rde?rGA!n`kwgf^Jh|d|*G2BA{_eE=wKRlwDVU zYiI93y6lPi*<|h!-xL9yL zL+T<1;|fcAQ^T=6A!LV9VC*M}X`;9UP>u_TZgMyf!XUR9yj}VLd-@puLtn~&CGX9l z?C@lUIFtm9%x1?lki(<=Oi$QeJoL5K2UVZ;bdA0;_IjarTom8`*kCMW9a&_7;AJ#& zP16!&McX&jHmt)&*h7r@ygd#pu(PLoDhNNweB!dX`H(gIgRpU!d4%ivG4G-qSu@YgaX*0l6B6IA|C5-Ip8YTU2EX_E3&tih8HhR$!}Ajg+wY}@OrTU9@>@+~fn98Ux1+ByZ-JeW}F^pnAC!6-QUer=XC zXocn~o*W{~g_yAH{v`R2Bx3Z>pGh12LJ-A~ ziRGv<`&OU4^jIsc^QAL#R&_BM^15#~AZZuc8425WGuDJADlpq(Xzs~SaxeqNkqIUR zK#9Z1?UVD63Z$=q@RDvg!)Gwa!Xih?s>B}LOQ;e0er+&GGCPGDY=hFzcuJDyCJtM( z?ty~24kKAM4=#sUsXk0K!J=wrOnDNY@O%x6kGf|!-dXo`P(SG|VhU+hW76%Y-&Og5 znE$l>b?{bq&3b0a+gj!Oqeb=8(p@!UgP)!(`V8MP2v7iW$rv?c!e~*Lm zWK+pv_P807!of}G*rsWLxJvKs1pSOZvBW%5=v7@2KUJ?HFXMHih0otc7g}BF^H?!i zl1X#T&@5q70l@B*+$VJC(AEq0nicp~+h*})Mj$dGAy&C|YEH%CXY&Y@%eN!R?IG~E zDo-9GeNb(>&W2VyeIrZzHZ-LV9LH_dgO%xx0AGwl%Pa{&BfC^9FH^ykDXfgJh;Juq z@#gDy`6iut1#D23WhL0WP0Ec6Fv=PHy!qA?yY8F^>nktL2ESD#%F?xHcsfQe8 zMf&r$H^-*S=Tj7Qw2vjPsqUWYArg1`xIAlxMqf+E#EBh*N#kAPrBQ5}BZ|VgcNG zM%PjzPKYKqLh+%=@oNorQhF@lC|YeuZWh?-$J}CaF<)F9RQr|koj7+-8jJ({!S#YU zP+dat$7T3v{A0IOVWu$1?RYEz3Me`BW_ISAq8EjG8cs+aR8Q}%lkSto9T_`$5`_0x zsB>_g|7^Og?{zylLBn%tng4&V03aElj!#@Ln6M1z6M(Ujj2g%;YY#(badhxJP6Sa| zGIt$=u6=QqZS9?RBk^0B{y*oB(Qaz*>yc(SFzn5)!2nBvyz?P8m_^rlDN4 zqjWV{=j`DC3XuBb%VNxE^3n~LF~j8zXGkyh-XDR8>l~)r!h?@844XITL4a-0c>&eq z$Es5kgikhCJ(~KB^US}|oB8JE*xDLRdy}| z{d5lILVljlKY=h=Y2Xm&2dO2OVMbeNYN~GaswrS0MbKF1h5DLjRE1^%E6iqltC1gv zFQ9c$TxcLLE10zwbF{a}bf8D-r-Pa#S$~!DrGNIA-xZH5!~U^ZnUM0Vc_}A%Rr;%4 zpj%4D%HN5*O{z(~_55&|+n7kY6{vrm3o_4vP==LBE?2I8xe;&Vv0Ed*Zhp1|=e*PE z8THxZb_8_>m(kFN-B3pl!7b-H*?G<1UAU@1R^2TSAQVLGzR9OnNkWM}h!NbF1sX#9 zMpFIB1utnbQ^D~|>}h?4UA10U?5)egdrIALa&)$|?>^)zfJ)+|yb_rh^oAkhBHgzi zFH+fB&%@5DLANd*B60O;2IF!NaabMOD|s2ymrqdoXBC{X#r{O~3n!(0aa&8#x41meR&P_S zl4ibe;+(WQHUzGf`6735*a=+JwWNe-YyE^%87{A<7do)6OvG~a+Prm{Ty}W<^Tw(o z=Z5(?$8Jbl4O$j)hRbZFvl2yWYR|*5NoQwSA{lSG!M$!u-Dax&F#M_yxB!iftaw4W@ z%11zgomUV(MN;OP*F_27$>bG12eoPe4dwi^~`sT{-nA7iK{kd6)j2 zq1949T}Zl(xr4i5n)%~Zp>352QbmMqRtXd2zQXBG4|pwR&WiT?p>4m4?ExDM%|`&3Qa z(}lA#ZO&(pS)NP6s-ZOFtqqqlW^FRG&Hk!FyW1nw7Ro%)KIB;fu*v1|Elk=KNGpF>z#b-%eBqm(t%=sDVaYqwK7lpX)Ua z`a0xh7&||%$RmoYK4@aG>~O<*@#>bjVp^Dc*3Rdh_s}j*PJ|P%l;o41Vm_A_t@po} zQ=5j=ke zZcK^sZnKY1x|3rNFNiI+KP!;>p!wH-KUfJdG6AALJR8vS++kAo*`mf(Pbi{*0=#|K29wE%=TN&W%S zbiaeV>Hf}hQyw8Gb6x+z)tE~D^8Eg9mVdZ3PSF2Idt(^&k3Bz}@h>MvtLv)OzoJke zei+#QU#$pNBs%-jF1%P>D}OwDFJAV3LISu#6eKpq>;*PUDrfD1?D%P}I{WwLcUm$I z711Z2>Zf_mJ{Lqqz37Rn5f2;JsOw8DT6dN#f$4dFI`Auqyyw}(y`QABpeQPevqnUr zoZV;cwUZj}??l#(>b>sH`iLeGZ^08@+vw(#n&Ll#A^mnTR}9%|FPO(3m^EfqT!f~h z@_8W&!@wO$WB-S(l05s$*7e_Xf&D*YaZtC6=&aLdDJ$=_%hJakQ{DL-1U2u>4yQo< z-G}c);`=lor@<`p(=F#8`tsEMyxfE@zj!ft&c$bo%AZb?1E$t&)jsQ|gYy(hTCr)z zMsa@?xA&T?wuCdmB&qV@l5^wW$M7sM7bLp2qiS*o>-ebYv}*CjtZ-Q(-XhNk=}%3> z+I$en4{>&1(_KsyEKxV) z3b%`_s0*^!agWl#`}zd#YBFd0;ltM)#6)5th8$#|jrOGvg})vNP~+?XhpG_sWWxwt zb^R>RpwV0uYVRpts1DQk4b+ERG|)#LAeXm0*+G8>Z2_NDBOmYI07Get9{0Qip4XX! zJ`1)BFk*`QchOTQx04O5MpK4>(^)z3*LIT zLA(_++3eu>{x9)u@dlYB6)F6~Qd;46OcZMnn6`w$W#K7b#`Jz;MN>4?g|rEDnS3eY z4npRPxJdbTu{o+tT?mZq=e9!XLTB8W2+@(m<1Da+Twd#6Kxm<&=1+4tD zp(zH$0-$|$lhCLQ-|)@m2wT#Fx~Y6f{yhyVli107D-XY{5yHRIt%v7S>Xi#D63h6k zEU^-4uECa^fLF+Ia(W18{&++NeNQQAq+zadN z++B4jjlHvXk%^!qr(+}8heo+)F7SSGl?f9fxbnXE58?L#E$vRxL<&AYAExg7UyzfW z!6asMp>jpQMA4m7mFIb)bDU!&4>4&_uzOaYf`!hrYW?2$(gK!`dFhroCN4{AIajbW`Y z9xgb~AJ!#qbjP%FN;|%=n+AUn2DJo@QZGh)-BvX8`e|JBaER?jt0k5-;a~=i zRS*TuR~^yJ0hspIj!FY;7~D0t$_irNRW*=JlxGB{N%f^QFtE293rnpoz*L+==w-M!9BQVwnH8o6D#V7(TglnT-_pI?p zbbl&m*tKLn47q=M#DMqb5WS#YsgE?{jZVRPnJ~!X(COv8`bPs`T)D&1xwbZdrW;n0 zp0kw^06q(PK9Sjy%SvlmOFd4U_!s-H zw!0E-$Su;ZHG?LE1T|sLp-T23*tY%pEli}X6uMUcU~xL7Qbjb zG;PSv$}CEZwpv$=c7529$Ba>>rpz>`JK9CMy%0i^+u0j6I}N^sH#-=~-Xqrp_V=yb z_+i1h;4;@zGJ((RXsk{293N3-3h!~!GS|1bz85bN44U8DBl-iYnoK5$hK8Qcw!lhWqaLT|Do0d5?HL) zYfO$wk1eCdEa{zPCE@Dvk%QBk zn)`Go_a>5~UEzwGeJdwb30i=i&FzEgp;-P&bFw*V;BZ8f)E~v_chTDyfRgU=HSl6V z16>@mkbD#CzCe7G*!aQmO)2#9864{6ylwrN8TRbfG3)SaaZ`f$2=G9{^mX+?XCvFi7MEqyj~V^@!$ zFW_s)9FFkqY@mKc6StZpUbe zQS*_J{X^?-;9MukHsFr07LiJpSkLSLP<yGLuO_VK+fhaN=FSpHZ0&r4|-NzQfUuqR`$ziQ_wAvH7+0k zEbu{?cW=Fjj=|fYCSy?SctQwxG_DFt#4QILM8{@ z-S1QlomqO^@*}cyK?d9c&b@LvaSk?NxqT-AOn?3wZ{|?S`fjxf)g9aTh-|4g)rQu{ z)-3CcS$c|(xK}zrmIu(b4*3UR0ud+u#V~!5WyUBo0G{)E*$nzWqQp6cpO8lqf1y4^ zlxU5=PTl`O3;p|qLFP`0#6MrKKBesDHKOSzGn4Vde-~cN0;ShzmOF~w^#1>R%s^E{ z8X33w3~>o%{P_Ag)kvNF-rmyj^LFkKueu~Y^O-H2r9Pe&7IzNebo$i8_sltd3`uOg-O*n-San$j~C5$ z#@B3K^e{OlEwj~L+%T6TIx2m zqhQmz(KGdysP2$P&8X%m4%IWjW!@9cyQoQ|dVL{47|NBr%}Fq%i8D7DXS3u?@Jn2u72m1P`ay;tl`+G%k2(k zeM*qdcC0hY15f05u|IoBfkx-{fiHU~K?T2f-j)um^odHN&Vw~%xbN@Tb)%$_zV%KE z1Fhp8ACwj;6l)RXbN>AnkdhI$f5DIL=Zf)_Zjd;v&1`{ex*(4_Qf*LfPlk=;Wr2;y zi&UP_M&E51+xrb>qkAr_FWtZ-m#KDii_2y2~pw`DHMm)1TS#Z#}-_ z9}0G>EsNcU#T6 z3t6t3SkZyq<*_Wvew;lKs}+%RNY-m+m^Ti?D`6;wjn%H26T!Cb0iSM0fOX=UY7V3E zLrdu!492fpeo2S8bdNWJ&gC*7x2=TiiqZJ|3Bw3`lSF=_vN*IvMuLsUh;0 zBQmtR{LSb%9Z*=+-!~VPa#g~NW9tX5k7jo=Yw+}oi{%;K;xm*u9czuDFH&!wBu zCpVmVEYqi16&uwpXvSnZv!c8Rc_Q9e#8Jx?S#d=l`{5vdNny75WU$0_#HpL$gmQ~gL}1)@W={MHJ!)(yz#q@=%=yWv0Ni(4 zcszUY;d7`U$5w_ZzF3mBc!D`U+`SNa;BhmQ0gx$v_n5d1%jpH5UX8ZCh5oZBQ*VBM zn+A#hcZ_4}mz&JSCQ_K>?D?Tins)rZH**)+F){v|%oqrLV1%M^T^o+9<+l_SKG{IQ zocUR)?iA@3l?4XO5>v&H(tRYsak(G@5#yuh;ZXluR53tE;5F^rI-d;UO)SX{gAAE) z@cA7ZED4et31*Q*|4H~O0-Q=1?RO9ULq`@j?e*tM|Iu-p5@+3}0pr1Cxxe{QUSkX1NVyM7>pT^N1N5zi*|wK$|Dix#&!8d&h(Ni zcQ`y$rug1hB9B)2Suwr=+jXY^pZ>Y0jMs|7VP+USRB+1q3!b@~Nq$VsDGrzLqWB*< z3_cy$9`CrZo2m_5r<)Cwz$A899 zAsq`DcPxt%KbZMnq^+je$K^W=r&{0svjhX&_ecj-b1I0phl_pZP9F%bR~L9Dhu8@O zxBo_+%RrmgY5&pW5r4IT#Q&>~PheGZ&pUs$cdbV*X%Gg>fs;7^e7%bXvB)FBzgqr{ z(|5(kPH^=<#BD*aV=E3zYFHRWhp#!~eFd-ot6do^17>)~>^A()6$+*c3cT+2vJQycWkR<-2|MnO0_Gqz>_{_np?b<$Z5F_AJ=C?1c z)3^TJr^6WwJ2I4=jC1(>FuV05zN|+}L-U*(C@LA)N@BEV8BX=2P)J( z_PdTO&XnMHqQECq0GyfxM3lV@dvN;S?%iPj{{DYbmK& z;BUnN;;gzg$HaP9g=b-LP{tN3etPD^x_B7 zqeU9Xgvk&N0DJ6xVQMxHyA;si7s%v`jY1wVe+#;;`9!w{^tr_61n`h{fCicGLJ7i+ z#!Z-6@um~(J|Bhj*uy1;+V-h9;LU->{x}Q89UZ4Qf5I;~g+%i@lkCxg+s_;re0-?J;0bmsXU)oY^8Ns!O5uyF0C#m1bKkFKd z92jBRWNrE{y>??*`=8gM-+N^GKmN-T-)oQNZs7G~ivRLl(v1)PcZTh?@00(4&^71J zBLAk<0(0|dOerU?(`7ONL%0W0cI^Ihmi6^Ok~c}EeK#q-a~l$af_}HXrLK2OVSNL# z!$GQXS9f^ntO)gc5jZ&a|J;){5-lP4Kg~P1dH?J8R4Y61b|7(>A+BfAN9Yz6PT>Dq z3^q@3*lQfG036{u3-=#AaO~Cp+v&|;__oQ5-kUU})wfktaZCIEkGRQ(;lddYuE+O~ zc5d9&58OY;Ieua!K2?B%aHPiZ{l}{+0)#ZA@asEw6cA$P3Wya&A+oau-baTNQ@W5sKoz9G(w_F2wPd@G>m zWzv~H%)gzs(~E-6=fel>h)1)2)}46^%=!;BCXShZn>xPDS=kJ9o}`H}z5hs1tf0#% zY{|XqqU7!AhMSkQ%128DW0lIK2;hggJuTjLiD-hBm&}tNqFf<0;1hiI`3JoQ%OcCT z?D+EW!Oz1H>tHF4vI6Q_hz6|)vwi5o(LE4mzw4L|p0TgA+IW%PClZr>hFM=XmaX=U z$`aAM*`j5ikB{D?tmdhEuk)sfYs`vvDCrScrgJ{UXvpJpmWQ%RpD&0e0j+=uafb> z#xP6UA*G0=!ZGs=<`)EFmWxHL*u&zr;f3SxtRpV?hKxq@8|w`PWkhAP$FCm8l}ngI zZd<1?PYwt02u==vWzo-eg2Hj7wZ|TZjSUyGCDk- z(D#>8t+YS{(}7B8zF|APImU&san6A=*rWuoty?Nh^-~OGh2dfj{Z)nnGHIE%en=6q zj>;Ys65d#w9Bj;?DK`=hD*e;JY^%8hDPL%Iz~-=F7WJ}S&yS1qsU^t0-YhU@uPmdJ zGOrd>G)vFy>d2Rp26qnDn>2$n7xXoatIccq+uix)5yVT>Cf+WLo^{TWwdRj4uiDeV zwb_HUwiP=5Z6HkZ_GI($%>;?b;h?g{v+|{$rr|Fe~hq##8D=Urz!K|eu&)EkaP8y#$Wz9ro z-hOqi)KLiKfEqTt1>|M-D+r*E%8Ux=W{&y3P^~xGL-N}t!$6k2?|W_|5;mH?@o!42 z9J#JFn-3&{EhONUy+ZfI;AlRKE@M84f`8JGtbpMkiUd=(dG`Dd7U1LBSbID7Jy&7l=3WDUVU5);d4FVRjQ%+)X^*yk_mvd7IIHyy6@{XN zw1ww{YpY%sy^Z6859VHjDd5&;N+Oml{^QFYpTZ^K_6x|@dr}M4PfKFNFT68^bLt{P_z|kM&*{ce3vzSXb~1=2!hH@cxX^A$Bob4(tO02e#7hKqauLVKh8hUQz}i_y?^GRLz%!dA7=Xr9w)ndz4y zUO6Fb5LS|htBGXH(^ri}&5#BFXDFI<{~+)j7JPKmt=TfColm0zc!=;yqqin+siY-0 zD&PIsuXs}q9C%w3y=Fyay1S?Rtcn=7k%*QG>v_SaeSeUDY;%+nR~98p1wW0O*+Z+E zdTOm}`}p*+j#nxibCm36uunwXy)@y@jK4<188>VdG1OUN-1C)<^cFvzI+J zvQ_3w^BCyVeXQ?CPHoAhOA{%Wopu_IgDVUSyDAF<*wG}tagT)3+x-T|Wy1lU)zVGp z1|j(R#kx5N4%5Zn?1)TeGJAbJ!u&0VL)QiLX_FAmX7_-Bw2Vrk)k|Lz$K6{i9>(Iz z%1=*7X0Sn1UcdT~sX%}IdyOkLa?ij%4j0qTyUv**1@(GPbgZ)CrNo!saf@YdT!O5o zByxJsgc7GOyt~X@#E|dIw_7j{JXcl^*c2?h{6sTQ>AaF&UN=0J=ss1FjW@jkl}d6d z)G;mI_tS3%Y;-R4YB)fMgG$K_h8;_6D`%dpJ{*)m6ZvZhK90{#y=r!D>+$2|H_&sg z{dZLwoS76XV2k0UOej+Dch}7fBZCgFk4HxbbtO4`u%EWoFwauht-zimrVUu zezxZN(2rh*)LpjRz}G?5+5A_y%O+pf;rxKRLQiQRG@rFFU71nI=x9*DvFej+B>-Pl zr!(H9NnICmll!Vn0+GQl7VPnVe zZYVZg@mkbm#4Ymuo3EYLB1C?AX4;AOvokuiJJBJ6viPe=L@K4YaAWpgdV<}tJMAc- z6zS^b8_g`?mS#`uo9_p&<18O2JPY~eJv~Zp6rbBaBmoH=Z^*Fh^FQ7j>)X{1x7@s5 zuXyo!Rm0ZB9*)j{<=Va`(XW(HZk0Ly3rE}R^J@LGGs<$oE*+?T0Xy|1ms8hMc$0)5 zcuypZq;AdNin>J>LE&s%=aA)Ch#I4;$vV!T5S0w0V|PY zz=U8_#&myM2nZShhDC@hPdQE-CQ)!-M#|nM2ZBZT#c_Zh64pJOM2*U#6eiLDxtJQ)%pfC^wLLlfQE&$~a!slO8ky7K}t(O==e|_Y#L^2-v{he6_5(uoG{JrmG z+^PaF^smq}gazN9|2GmP8sKyVnCb738Sb0Ec;k1J3-AXNG{RR72)*y!--=eYk7%3v z-e`UPs<)5NTaw%ABhV01APV1(#;*dF{u+Xyiu?+H$@H5+SAh%g>mzYNydS_zeh132 zFwF(5?_E;g&|eXHp|LkJhU8aVtp1|5nG_NhITkVLrCp@CrYcT)5*UXJOLEx@uI)z8 zQUE6ba8)3NR)2v(1Dee5^QFT56f#1lK61Y+r9luS2qQ+QgM+2b66*#efrc%@UoOrT z*MFa1+K~)&?R_Ds%E^45?Bz~D7Pfja&Cx>u{}b8&fMw`3QucI(Ha?LBP;>4*$M_zs z3?3fAEbKzjN4fDBCArg;)Bp*1ahT%L#p$}ajUpYrR!u>TV_8}ndd;W(%m|!h`O@+0 z>!l@!pY5Klw6`qAt|jy}!PB%Rij1mYd)y+I65^d!=Nn5I?Fg*;50SjCv(`4_y8OvGXsS*{rnEt>`zKmGM^E%?f`<0!f8sVW z@438WqMww3A{~tbuBa=aRiYt0qWv8@s@A%%kk6j+7eyd4=|q*qf>n>xei%7Ol}Un2 zQSPF#-=1<3fjjs*M9rxSSK4Z4ze2y00jH4!tVSB?T!+xW5MolaAy7dY^DKIe$sH*%=f;c-evWn|2Sl@6BfHHSxLc(zKc%qcSiKeh}yw{PBU38*tCbL(=WD*k4giH{sv7>8>}V1r?ltaaUx>G6xo{(g0!daA%C^9K{K{K&YW+k6_v zx%fdY6;y^Kec6pt-u0%f!-H~*>~1asZ^nSV1@Mv-K+^y(9|d0Zl1v&hQ)*N|*&TuB z>vPHRGWLLi0b1ylHRNCiZHKI9jq-IUro>M2P+-AMw@9dFFVT}D4|#YcA|6aYp{C*+ z+_d)2aPXmlMQ`-JD&bcBS#CwkM$rh5Z^k|`(LiU?i0`oY?oHp8N1J|BN)XLlS?s!+ z8o2BRX{UJhBd}@1=SfCGmb(hxx97}qy)v6}dd4-hh4`J*hWdko-U*lQ#I-!pA!;OD zV+vt%IE4Z8J(4h^!(mXBeHM-}Cb_tQDUSS+tV^yO4tl6wckl)$=N4ECIFT_h7ZA07e@epm z_9Xt5Ifx6UKON>tL*6yl|2C4VA$^7MuZ>K}6~RXY{q7eComEB~{d2q`8c5##w&RRS z=Yi;Rz64lvWja}k96=)iE`#8E0YZhAus*?cj{!v+m7{_b5TG^6OI!4H=eEEm8Su@E z`@-gz&ups#aaK^WOEAtMWAer#5$=UV$r(zr(0#f(6Qs-PJyYacDT7XES#a49(uE1g z_AhbM)UI4~xi$uasN09>`rX*AbaZks9?KerQnc=gjjIjcQ>DWzj(i#xW;ZwJGFtlK z_7Zh>*z)b()>~=WdpGQ`BRl9`cGzmV>U}(2r76<(O3KQQY1}S=2r#%Y~*Ua?Td=@Oncyu zbixuDr#B^Q&1(~6EM_3SyS}s42{_LZCg$3`H)$&9 zaa6SNVva@dz3cv84Q8Df_%gYL3Rxu`hJ)lAk4-}--%m?d=;0-e=D}3j<)2IDUM2Ba z%jy=!Bzba}Y3gwc+9{)riw1$3VY!GhVlNwcf16wuK&0L2zC?e2MY*!JK#!(|*52Ej z7uP@1pG(}l!zvsPgRtN(kIG3^v%_5^qMVH!cg^?Tt{h5hCuS{HdTu_W31D`intV*o zDJNf>JJs%q)!rGEu=Um({5p4@lZG{m)Y~Y_E`1hXT(nTH3IFnxPSR3=or}RFxFH0@ zm%H!`bk!lunA6RC&|8VKUOT>YyC1F=2)kI|$xVhiCqAs@IfmIUAC_HV4u^S?)aV#( z)~Ia}n<`SgHoiVvkJZEmc zNG*U+#CN!xB0Z$>QXl0OA=8ySXY}fxx)d0Qa1MF)2x29)uHCxZyCX`ajCN2JD;sOt zAIxj3|9o8G$f8{Jf{Oh^mc_?GYSBg>Q}O5skAtC`bQ>(=HbakD)RJ^=$KA|S0L|RH z)TUw=ZK@T{e7!WDd*N0xT%{0Qyz|_bioyEPPFc3YJ8B}Y@cT{|nIVJrOePwpGCj+@ zq7+8dLJOu>x>}LXuF(@Td%}8*TQ^-J@WP`dZkiawVObMZ;!L?Ql9<`i#O`ZaIE>$; zoa1%anWBN@tRVeO1wpdznUpyJ=TEdwnO>H+4@`9)8^12PFi#Lbc(?0e`5lPtk z#K*bFPqhx2NwZD~=N0wy&uZ}0aUL6-n~EQj5T(1sdzH-uxxPMhjZ??b(XNWLp+!Dj zNXMQDYgl%}af-|9=cR=C%vsYR{zYjo^ON*Jq$IAXz;8t@J9elpIV(P>nICO~U^nyM zysf4bnHc<|fQSiiFe}2@fxo~uoX|ZYfXI*575tjyQZ^`qghAqB+2~&zeWeX~LQHb^ zp&EGqD+el+tKV#TQhB<)_A~4;ThOJ)?m5rc5pQ!sE+r@IxENc_!+RjCv#0nnjrnn7 z@+B4B44AJDRpx5-?4X*DaLt~+g#CsR088|fj0;pNUOz+V6J;gBYH`)p`1O`omrVRp zxS*ssC;11LAKN^WrWArq+gw_($9FQ1`8RVXz!oPni!-xrE|{2?5`Fh>l!glNw23D# zOm=p_niTb(vvjdiqxLXR8*p7zJkC4hl{y%~J~Lg)r~4ju35062zpuqQg3Epi6Ner+ z-P4`D(n})yFom(#H%_eM%qE%gRyz6&(&S7i3;^nT9TF*ODk28^M${R@Sxk@mvkduC z;;?jAwb#e}txkJDQuw(^^-C^xt=JDn&=ys7)#nw8@*e5M9v#7IC0+95Z!8Yvl?4~m zbhCn@?zL)3Ba(WCWSbz{tc{=ZYAH z4-MAfumXnnbHZPeDh4?ww{CtrpEy=TEn7x;2`MaWuHaq*+y~IJ_6HB%0S}0<3w%TA zZe`|0meiQ7&KoETKKwm1j>WG`Iy(Z8X+e%^L}5{@_~tL?{7< z$kb3QyyLn~z7`+;LP`<#F_6`kr=e(ar)u5mfdIC9inZC9Z^=5MhxnR ze)&*Z>)sccR0s;B=Og`6eDPLYl!@nUa*b0ch&K9S@C69ZWu)RDgn`frfd5*k36dSJ z$_aF8ltb4J5!$FUxSxmq#Z!iargi#B&;z8b`xMoQ{6C}V_VX+KU!Wrz=)W5bAo(v8 zqh>=stg;gLqyDSEO>S^hn;?mYqg zEvbKIVjBO!{RgpuEW;lgbgLl;XZQb30^iBnY9(R?S+<`2h3{QdNh|Re!~RYkebTAs zw^eZ0LxKPM$R(qjQ*XAqSc+#;4(qa<2ny*%PVR+?sTzmSEYPl$B1P!q6z=g-fu5t^Yl& z;o#5<{ee&8`A+i_-3Wu7`74zyWx4cSLT>b+;cE#T*J|cUp?-*ut4|Naizg_MvoHD1 zDx&#zTEKqZ-Y~sje4@8^w>SNph%i`EB24&UX0xFO$F z!?Pg48vRoBv9Tu-2pwkqGx)M8n9Nq2TB~P5T+GA(A4rVX*gj63a!)m_4!}}2xF=C; zEPcy&n<)(q@0&Yq#)3;YuGPAvo?JQy`tbJC^CpWB&9~)SRp)*5hT~3GjFu|gZEqQ! zp5!(vKks4*xB@*4hUL2&8)D*)t?_4ku>59CektZDI}RE9I;#uDusy+%RAB`nr+wV* z$e1tYvWfRGPzQgXbVux4rL_^RLB43tLt(4BWD7gy8=tAM9U(>wm{JaI#D`-ci6`z8 z+_yf^oEqpr(Oh+(Qs~zx$hG!B&2SE9eH2m}u^R7VTq;oH%O>UFR@dNJEpt%ShbIo$ zbPaNt#;WKFf){1%<*S_Z74O&R*!zsW8<=!ZEo2kR&+?0VDXnqvy+$%=fV4DKMAQEJ z$EVB73Gq#)E)D+> z8^S-zwr9Bv{0+O9ujcoFXky^e{_wAbp3eTU;AEjmF(JI#8>}k`mjgqs z?%9d~&l`IbY({gMBtQZb;`oV{%t5XsdaMVnE!}n<#WAq;-W;PuiUqJJLLQm^`F^!N zt~`w4n2b3k_y)%l(>dq<0*T?Q+IMfW`_xvjA=wH#htEKIvUF=N6J4+!P)g;Z{23na zaSq5k%F4^4OEmzV`Y?B09O_k@XnW@w3^h&yhp-l^Aal)#K_O2_8~n4?=|!paYV^jW zB=8#sgLzn`54mR;2j=ZCMbLsfiY%Jo52Csp{p^TB4SgZN*S?ZhQ152=)^1hT>TQ0- z2BXx)hqGyM3*SvqKZn~_M9Y;iM&FStWAK<>-;Cixk^$9D&TSs+Pde{2S5v-{ol)0r%UI zvY21;^likGLa|CwbNoVsy@q+4;c{9xa3x_04~|+Mq5YBU3-%~_$0g;G$$QE{Qb><$ zpPYdPf#_G|GM%VBGNnTZ-umvBHsoc(b1@=-Z%{rb05WlI8sLbOGir^!JGNCK;uek| z9d$57COh{4{FxGWwSYrM$%3X+ypcC)u1UnCo&}gp5!aUqQA3wg<_SQ?`bE_?H z+`sqphb_9?ZdoMz{E-M`Fu$1sH}iS!vF=L-G(>N6T%2K%k;T;JcE z=|EWpQoVL0Df1z&WVyp53}%vBaeETfXhNpc^7SV=A%QXySCf!%+R4BmYJwOzQ+Y5o zgohZZ`pLvDj6w(Kqq1L?)q}iKZO2N`4RgGw0WH)_CyDQ*wguQfOhrBC;Xm4GQo^I% z=CfM=X_x?{rDfTm2}LfyVVC+Q5?FilhcZJDBF=9Bx$rk>Jp&1x{imGZl;bWBP{;C{ z=`un8Dz9An$XuX|;#YlvjB27ip;Y3<3!s2zjS|uw`Iu79ofyR=7GgqTa(b-yFPsZv z_76|Jy2S8@xZ8dAS&4W1JIfiBix0afhoXVbW!0+{d63$@Vqc80jJq3-+sqZgkgVoCqYuND5jUH|XieZr$vY(MGoB z9!uWdcQ~{+SeV!KV~d5Ro}U=p-yn7TRU`cA!GoBcP#BkVc0H%z9T!WaJkWZY5G@dx zec&hB+&+UdPb{2RgrC!wk+Mwiqdqju(>zdII9IQ&pQ3j}A-0+=;b#Y~?ZY?4P)j60 z-rKP2@C}Sh6A#wpdq3xke(4y{BmqLQ!_tyrH6KZm_~?=ChUQ#=<`1~%!WTX*_c6YQ zX0tKI3Pq-8%LbBB!{M3b0Zm#^4)MNGQG|o&bIeYT9_eGfhZOGzxlQ5mT+|rDj8uGL zWv_g-YE(=?%mJXQ`mR5dM+1I^9h0WdtiAfx)-9zUpJ=X%!}O?w!`~TjKhb-!^uqBZ z%|L|viuGOerThe4+KZl^4St^10IU){`@u?Z6B71=ABK z@JtRgQbfhfl-T=nU*{5S2(4CpMbwlu`XRy4;5-t zj*S=Zb4+yM%GXvTYJ~fKogNW(Sv0q@C-Blwm&b<`Iv;#cD0(`y%#k(N4+ytgwAsU4 z#X~*ztXF1jb%mCq3Z9`b057eH|5@8=F%Q=a;qPU1JNbdBuK*0&tS5Ti`WDU@WTUat zWK(8YmuMbe&HFy1bKs)ueD-hwUgjFkCO^|4NG`ZxcVTwpeDe>>*+F%&W91WqeYxM? z?^x>6S73RSS%H$s=LdHlmpeYFkr-)Azi1$janvzWu;QI(WGQQ>+gC4O)9v434}!(2 zSjvDDXmh@moSDny;K;b6P`}Lg>Ai`@tta_)0?Y_;Q~hlIY}uD7l&Y6k=5FhKHAZU} zAbL-PCNL%LriK@`Nbl*dn-o}Tp%6;n>3DF(y^yuN)4#i{aADLO)A2}pw45gJYacD> zLRy~Ovmdl_9LG{)aML2QTFvh*nYMBUp6*7RwPnkxudgW%d#DeklOg@>P3Pe8iJhmo zlV8iBU5}Z&GZX?T3YuIn_PW)zL^|;%%2B#B8#zvqRUbN{#(bZF+x9wqeb z9fn`Y5mx;2cPT9%t*53~3nOy_et=64Bqvvd=%Ig}oscb0my-JNxGDXHg6@0%wooj|EI1m&JQZLq@u?~x22Rm%zCO$f;L zDBGr1N2gDiSaGkYUD8F|M|+*xI70qZ~+7xGB}y5Yadmt?m&Q(_IX7AlkF#gT4Sl>WuY(v@!K&VqV4R=-05 zdg^Wh;oC*Uvpv@=2nJ#WOi^=56MNSBE^0wPdtr&JnWxSESyZ7tcV$k6nP0o3xDPc@ z((cNct_-eAXztdKMsOf1!?u#+#lMw&>Rqyr7)|QtZOC-Mcy?#2b#`nkK(3*m;hKyxoRZn{7|S4%+H5k8YzQRm z=@SB;yI2%rUuSxF14A<*Zn&sUfEI?N)w+FO=1)J4!QGTDl@~qnNL*CNY?JQSHu(p* zGx1@14cD=`G84zZvUmLsSYA&R-H^OVxAyGZVOsoSLb{GXM)w-qAA0HP4p97;!6R&< z4en0Mc=$^Yzi{JZtt%7gzoI&o&RE1B{F3=gubJ>NeN2C$VX>kV(1Cc5*lHcdz>{z7HCzf+y4>(+FH%qG@A8|Wka z-AUzln)6q}^Q4;a=YrT@iwFVD{~pTjo^U!26FqJ1_IrSs2$|kqXeMHd%D2-o$@o7g#MUqDi5~{%~Bf%y+e?#l$W+VTwEND&R^teQR`j zrX1QXIX`#utzTHyYOL~F9A`3f2Xdh=x^}Uq9_&Ys(s`JUL6@*-aFFr+G-f7He$P2H z8-$0EflShqj`R_`?Wm14_30N@K*DhfvCDrR-r*H?Yf z+4Su=5|0+Jf41A%=eevV-mAjmOwE**1xw!cxnl`cw?7TsCbQA7&WX8RD?E`Ry5~&Y z=NK3FDJHXOY*8QGMhIUrtTWiO_(>r~f0JVNi?jB4<(r}}fO;0*RO-|bVz{E8mu+LY zvhJ2zZV(Qx3K2tcK_Hj>+2NXNSpvMvE3b3+KKJWGKEPqPcB_we=(q=NG#ENDWCV%! z>gkpYc+%E9Zw3{z?$YWLFT`DOaVUW|1C99Q{!@*=7>Ik8MSm#TIKFU^C9D2J?8ceL zwd>2_B<5l|!ZeORPJwq%Rit<`E_vHX)VovMQAgdrE#?FDU`#W&DRt^he(mRt+UOA$ z_|rH5d~to{R}C&1!-h<cx-Vy51fgWH-7!6Gnw>;P; zo7s%E_+~xf=8|PK8z{b=pqHtW6?CD;P{GzULS5S7yTMYIUfK7TY4XBKIRs3;{E($P zSv;XSVMsArJbRpsVm#|O-!U37MoV^ToP&FFCz@NUk7Ycshe+v)V5<|TjV(8#$dNUZ zgR*p?#3>nE@Pk*aV9~%h#TI{`dj!`-bj@Ce$4(v_KrnwRdja z?a)tZzq@2>hFq5;xmSOmyX>9tB=eBmLz1hy=tl(+AVK9=_ivwhE6PTOgmW|t&H&eP zLm8}eWu8$4S0=XS0Ce$z+)qg+P>YZh7jBv^Y9}j)mIU0jm1*OT?08sx2pdj?3l961 z_C|@xhM3=SexN=6z5ep$`is5jpy65vWU}W?*{H1m24pFNqgJv?O8iFrQ&n#)l#6D# zTa^j1M%7R4Me<~U3W zku8{9mQVx_LaxJJiK`^w#Aq2tQjd!cgEvo6o_-T`7Rq(+{|8Qd3hr`#QdW0%JKrE< z9i{pvDo{G(pssb)vQ# z67hJM(nai8X_gY9MtX}SJ)Kwum8Uzue0ZQBDuUZkYR)XbIGZR9Z8q(&9E|R>k_SsR z;gd8ITqtk0XIiU+MJ6j!awnMc*yk?zH$M?Q|CpOEFa^R|h4x7e>L_6%y@reY-kPi> zrUY>oGQpxx^N5Qpm8aIutcU|bp-V$@g1`X2>9PWAPMkc zf_a7hm`EeH-vkxF^Z%&o8Ps2W{P92OWyP03s`$5+gczY>r%`;2f*{`iD&*%6GR~Mi zw-$VS@r1ep#Y5;f>9gmyK3~wQoq9)%nvppP0w6qesFs}Th}~xOgdY84eIIXcb3%!} z?7MJSDuvq8!KkOgiaC57dMj;y3T7q_x=JT%KT%m!diR=YOW6n4NpsZ?4EeH3qc(-PS{%RC=HAK?`Gq`vE=;Obtur4Eoo zr5T>l4?dj`$k}U=LBY3$uFN}=$jVS-tg0XDy_@*Pd--Ozy*i7t>2vsPl^p{*+6>0YI#AP`WqHG=c45PH%m1%hmhAS!w!;pxIkPCSay&N4|-j2 zJ6O3B&IrIUzS`hz+)$;Y&)q0z)b`=~^$lrl^)WDhl6dx3MgUSa=rm>4c?xc+sZ)h; zp(yd*DCSfOI#W#KAtxubY~3do>hSop|LL>;66 z`tdz^JBs}+!&H8|663epPW03M;=IS^s(05toB{Z&tU^UmAs3uuT%Gc4CGA-B)SP^2 zJ}x-KB3SohJ}y4hTbx5(irWw<&DfUTcz6S{#EH|-Dk@RpWks%3L+*lw9t&KP;=Qdd z0FOVwIcddR48(SfQrS8I)mGbO54ViTyX3M0c#ppLPMBymQM^y)1DBb!b8bZi=2-G4 zR>!UxNVSG<1`G3fq%_N2iuc=HqhZ!6QEXCl(hsY6cDf<6h`!4rWojNo7A3D@}fuz|f!quv4WB|xMzylm!6rIv#Mjwkp|Oxbi=i2yBR z{bOx6JLpCtkv>as1Z@1cDjRh!e(A&4A7|(yAKwmnaY10J@UzWT`p9`D4OagvxgBv= z&2%|c3dO%T$(9j2#WhhuLT90G*;ew5C_IJ7@b%nX))$E0wn&&dQ0{W%JI0mlF|6(gtxf zRh)dJxQQ5;TCJWf`rRE3rLS!QU4@vP1@B}Rp}QlsU*X$o*DEBy8F!~Scv#wpJni~BP?!;{o|F8f*{hdn@XfO;-AEE;ojm6 z8d$n1nAB2{|pN=at z#&##vp?7YQu#eI;=J}w{PT}A!Lo{*8J?Uk@Vs(0X>dhjo9%!h9w=&Y(lE91RKIM4G(gly-a$(6Z z7zGc$=vgrZZ$SN@@MSPDBRGzPsgcDm*f%+9YYq{~?b!`{*=+KYAO@|=KS`J8(hu*C zkAkMXhAjfGj@4fQV|O49pDz0XYaW}{x&lloK&wOKrYI;Kc8>15YA=KoROrX_sqwy` zs?tt{VgUoHqVv^yd5w>(^a8&%)2wS^?QdV-3 zD5ik#fekWfKN)bi`&9bblSA8pJ!@|4=%;)gU7Baim6o#+GSCBGA! z?6@($yIp(37MLC2<$_(Dk!UNkNvM$;dO~Tk^r+|^xv0PQPrLDY6IO#&jt3KWj++)c z3=K72em=0~X@wd;zXP`1NLU2{W>%WrT4TR^(W(N9n|kB8yS_vsnQe=djDW4>z^=P+ zeb!>ef0ZlWPB~D5cJdY5tq%t`#cS4I(hgv(Xru{kOU;pTM_d%|A*Dv9Zg^fYE#Q}? z>S{ciDEI25h@i~znds<4`x>nZ<(wHf^InV7>{0cD#>BnNG*pj+)9Z(Xv$h7>a6_6! zsE}L}mQ}arO_El~Fhvf|k6qxf;KRV-OI^vOyO=vaQZK&ty6^Sf^sxDbD{h6Y&(wr& z^v+zx;kr*}Hg)YV;gMvXW?2mkg*^f)u&3_c5397uQY<2eSC~Pc9jDX3V+QUH4b+ad zFAZ`fr-iCSB(DL`l`;Vzz{7%&H!CMXt0Eo0)HPIJ%R|~7X-_eSmunB}JSV!xKarKr z6p_-f)-pMXLmn33Hv>8j@3&g1>8{@Q2^90l!&iD`ZkOg+7*qE`$9~qN%uwS)6X@Ul z#Aq(ER4;b)SeqM8#QJ`s&Wf00+zgw9#8p~^>APaGmtBGi!q{;phN2_m5gw$hh;doB zX>8xPC9RvneA)t}Za%v$I4@^g4`bYj*kKrY54$vWURRJf+07pw%d3480`e*!|n{&VK_*!6Bo@onD6q!&KoZ#1l=B#u!cA# z=!7=d#xux&7+k?gTpeSm7*nBG=8YNf%kDmFBL2CG5nFVQR;JLp?7Ow8EvaAMWXQP5 zxHPhYCSur=g0UWED2l+3G-L5Zc@6Fuurj24=Q&r4>z#DFi-4JZ;l9-GS8~Q!LD7{_ zur9TiDkak+j5kp1;v>fV?0Bg7TP~c6Gkp0O-RCO`a&HRfb(;#3(_^zcI=-#$7+H5D z0X-@&FdA->LA>sQvssfl5i=n6lyo>Bl+`EX@$09sc=j0IhSR}6%6|ms;pOSe&mytw zDrmLNIdLt)+Ph{1ldK@l;dYeHazG*H!ZQtcvUidUnuiIIh7C7SLr+uX-tiTgu9gA2 z(A9_|=sqoyc3?TGUbV8szxE{W@h+BqCP6xfet6#?Cq}?5qiyhIM`t$Of5tmTwXU^JKFI zK@MUU-Hd=&fqb9_(5yo(w z6))W%_Cb3fvvuubZwT%rs*Lw32T>p$uZfcRpqKMna{$`}^#l+qHsFwq0*+2hTKjI? zJOG)g5LP2OE|=2b2j4^J#t!wIw`p9N9a1d1lpfJks&c4cM(Up{1TLD2LA5!%EEljW z72)+~IdX{vv%ZZc0fwc-f1bFa?Yx`YDq@TF3EVMtRhT%9I~*JjfuVhk`!YpPD&Tsn zeTYM=LO-S7i%+vYiTU2930hdC%Fb76tv)iaU@)xd>|F_Etj{Szbe^56og@QSpiUr!N(yb&DbzbW> z`CHOo$VV99KMW(x@elC*gVLz?iE1prp!~P7w|`A}g3EuV1bo^bi=5#uv&9BK!R}M% z{|gBII}2$uznqxjfCu!zwEw{)zxj{xTdk`$bia<)s3U(Za^=Em^X^f~+b_eoSJRG6 zcs=0DxhUB9tHHO3k6F!cS7I%8S~e+HeFHzQt--Q`E!^_EH?Z2ne4xM;q0Ww;`f8x! z4P{YR*_-Yfi?JugELjK`r#f5z~ru#7|i3`Ies8=Ld=3Vq+2I5W#q`~6c9H{ejRmiC+F>RN*C5_gS8jLq*jQ2R^!^2?#4 zyFRia#=PnuRvh2lGm18uz(jz$EhoClB$eyUnkVJK!iA87>7@kLv?Ry&5GN1oL6?Ts ziNta=>Z#0J16fMo7kueYZ=J}SnnSy5kpydxa1~|7 zw|hJx1RJw$v<@Ecl3k8xUgc^bQ%Jv=0_*pY7UVdoL#=mpny+7bcm5o7iN%8vLMlIX zGwkW(w3FVbj`@i!?}|Jg?9S~K0#NM0MfHQ^8m2rpV}K^vBwk?eZExCp6oa!a=2i2{ z`t|;MoIa>+@Xw{9RPvZt{5dxcp`;(pjmlkHu5{F~svK2_G5OggRpRmff)d8@>Q``w z_T0~57*pwRj6OWG@Qb-29{1shv*}K)8TYoUgwi|VPbsN{r%Tjps@~Ua)g*gmw%ni# zXw=pyjeFPh9gt7(A}N|nuvY0ch!4`EurOWR)NH3XVHV`X>+Cq^0sJW5)p!lgE39Td zw&hpTHi~fdId>bIek5-$xbz%j(e0WGq{_mK6W3D6Imei#^EDRVf(K4j)~~ndQTTb6 zK4-GWTj)rveS19C)4;bTr^cLWJ~>jy%Ch~~{GON;wv2dgB9i4Mug<8$fktNg%P_G! zW(>G7r-){Y#xSRw>ST)Q6heFn!xx`Fd*DWJ@pmDhWhviVYN)qgo)>V&!=^<l1-ybv*p5hOP;-lpNNOqolr)MJoirG&5Ey1e;H$k zp`+-92p|?mQKMAb)~8mdoz`Bpe8OSgDG5>|Wzk&Bc&P77$9DFmRG@=#Urjn+|JOE8 zpoQfbe~-{XWHOv$c^6MW!ZDq9x}OH(lKIyaifRTwUwNmVB|xmYN8O+kM~ystc=ihE zg137HoUg5YWGR6Io5nv?x#4#|s=Vp`9Mnx2Y4E7}xJ1wpnV7jYhE~yB18O?Z8LarJ zRa;F7@t2Co1+P;g_-{-huumG`*^JxjSl`;Y9Afw7tFiASaJ44y7hw-%CEuRGjX6(L zPBRDlAMlX(K#DJ+B50(>Kp+}hw69$4DK`2jO*r3sSO7ID)p{or#+>c2?7ejb2fnpWfI&Bf`?-A>!3gYK?%tO) zy1qAjcm?l{jE?4CdFo&`6ElLN3%6I_&?Ug2Ro=#wD(d5$o=@&bY9S}GS3JX@sACaU zc&j}?oFYOrAcO9$6SC3ERFK>UtPP$7id_+xzZEPReZqBMebuu0k}6hjVE+=w{gEr$ zD7A8+HWJwbCzsyxL5qVHzSh1A8OFhjPyL{v#`uooFm7^On)?cA?4Sj_f?#>AOOY%B zUk97%`A%gfC@Tln+;@Czqb++-oZ{8>n!#i&8b6>axYe3Gr7)HA#x((ZaipSEK+0&m zuK4Z4SnCv+cBHSS_3kB1(ZQ>%;^FEkt=1PJ&d_9-D^bptMq0JbgL9tQ?y97%8hc!a@F zK!b~30@DTnjzAy(kU}2L-}FoNpRKz9Kl{T8e^bT3-~Wdt{}IVQcsZyD4yTfHNWkm} z$em{v7G;6TpJ!G8Qv+Za3Of({3jscd17z|%uv8OAC3hZ}1K2+XyAupk`xq1?v`&2r P_@k<*rBEq%KlFb9xZGl3 diff --git a/packages/otel/package.json b/packages/otel/package.json deleted file mode 100644 index 34f2a23c3..000000000 --- a/packages/otel/package.json +++ /dev/null @@ -1,94 +0,0 @@ -{ - "name": "@mwcp/otel", - "author": "waiting", - "version": "41.0.0", - "description": "midway component for open telemetry", - "keywords": [ - "midway", - "IoC", - "plugin", - "apm", - "jaeger", - "tracing", - "open-tracing", - "open-telemetry", - "ts" - ], - "type": "module", - "bin": {}, - "types": "dist/index.d.ts", - "imports": { - "#package.json": "./package.json", - "##/*": "./src/*", - "#@/*": "./test/*" - }, - "exports": { - ".": "./dist/index.js", - "./package.json": "./package.json" - }, - "bugs": { - "url": "https://github.com/waitingsong/midway-components/issues" - }, - "homepage": "https://github.com/waitingsong/midway-components/tree/main/packages/otel#readme", - "repository": { - "type": "git", - "url": "https://github.com/waitingsong/midway-components" - }, - "license": "MIT", - "dependencies": { - "@mwcp/share": "^41.0.0", - "@opentelemetry/resource-detector-alibaba-cloud": "^0.29.7", - "@opentelemetry/resource-detector-aws": "^1.10.0", - "@opentelemetry/resource-detector-container": "^0.5.3", - "@opentelemetry/resource-detector-gcp": "^0.32.0", - "@opentelemetry/sdk-node": "^0.57.1", - "@waiting/shared-core": "^23.25.5", - "undici": "*" - }, - "devDependencies": { - "@midwayjs/grpc": "^3.20.0", - "@midwayjs/grpc-helper": "^1.1.0" - }, - "engines": { - "node": ">=18.12.0", - "@midwayjs/core": ">=3.16.0" - }, - "files": [ - "README.*.md", - "Dockerfile", - "npm-shrinkwrap.json", - "tsconfig.json", - "tsconfig.base.json", - "asset", - "bin", - "database", - "dist", - "src", - "!**/*.spec.*" - ], - "publishConfig": { - "access": "public" - }, - "scripts": { - "build": "npm run tsc && tsc-alias", - "build:unit": "tsc -p test/tsconfig.json", - "clean": "npm run clean:lock && npm run clean:dist && npm run clean:log", - "clean:cache": "rm -rf .eslintcache .tsbuildinfo", - "clean:dist": "npm run clean:cache && rm -rf dist/*", - "clean:lock": "rm -f package-lock.json", - "clean:log": "rm -rf ./logs ./run", - "cov": "c8 --all npm run test -- --parallel=false", - "db:gen": "kmore gen --path ./src", - "dev": "cross-env MIDWAY_SERVER_ENV=local mwtsc --watch --run @midwayjs/mock/app", - "lint": "eslint --fix --cache src test", - "lint:nofix": "eslint --cache src test", - "predev": "npm run build && npm run prepareShare", - "pretest": "npm run test:tsproto && npm run build:unit && npm run prepareShare", - "prepareShare": "tsx test/prepare.mts", - "start": "cross-env NODE_ENV=production node ./bootstrap.js", - "test": "cross-env MIDWAY_SERVER_ENV=unittest TS_NODE_PROJECT=test/tsconfig.json mocha --parallel=false", - "test:deb": "npm run test", - "test:tsproto": "tsproto --path test/grpc --output test/domain && eslint --fix --cache test/domain", - "tsc": "tsc -b" - } -} diff --git a/packages/otel/src/app/default.controller.ts b/packages/otel/src/app/default.controller.ts deleted file mode 100644 index 458705efb..000000000 --- a/packages/otel/src/app/default.controller.ts +++ /dev/null @@ -1,50 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, - Logger, - Post, -} from '@midwayjs/core' -import { ILogger } from '@midwayjs/logger' -import { MConfig } from '@mwcp/share' - - -import { Trace, TraceService } from '##/lib/index.js' -import { Config, ConfigKey, Msg } from '##/lib/types.js' - -import { DefaultOtelComponentService } from './default.service.js' - - -@Controller(`/_${ConfigKey.namespace}`) -export class DefaultOtelComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly svc: DefaultOtelComponentService - @Inject() readonly traceSvc: TraceService - - @Logger() logger: ILogger - - @Trace(`/_${ConfigKey.namespace}/hello`) - @Get('/hello') - @Post('/hello') - async hello(): Promise { - this.validateRoute() - const traceId = this.traceSvc.getTraceId() - assert(traceId, 'traceId is empty') - const msg = await this.svc.hello(Msg.hello) - const ret = `${msg}: ${traceId}` - return ret - } - - validateRoute(): void { - /* c8 ignore next 3 */ - if (! this.config.enableDefaultRoute) { - throw new Error('route is not enabled') - } - } - -} - diff --git a/packages/otel/src/app/default.service.ts b/packages/otel/src/app/default.service.ts deleted file mode 100644 index dfb8c35dc..000000000 --- a/packages/otel/src/app/default.service.ts +++ /dev/null @@ -1,22 +0,0 @@ -import assert from 'node:assert' - -import { Provide } from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { Trace } from '##/lib/index.js' -import { Config, ConfigKey } from '##/lib/types.js' - - -@Provide() -export class DefaultOtelComponentService { - - @MConfig(ConfigKey.config) readonly config: Config - - @Trace({ startActiveSpan: false }) - async hello(input: string): Promise { - assert(typeof this.config.enable !== 'undefined') - return input - } - -} - diff --git a/packages/otel/src/app/index.controller.ts b/packages/otel/src/app/index.controller.ts deleted file mode 100644 index e0d1838cd..000000000 --- a/packages/otel/src/app/index.controller.ts +++ /dev/null @@ -1,4 +0,0 @@ - -export * from './default.controller.js' -export * from './default.service.js' - diff --git a/packages/otel/src/config/config.default.ts b/packages/otel/src/config/config.default.ts deleted file mode 100644 index 6707fff0b..000000000 --- a/packages/otel/src/config/config.default.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { - initOtlpGrpcExporterConfig, - initTracerIgnoreArray, - initialConfig, - initialMiddlewareConfig, -} from '##/lib/config.js' -import type { Config, InitTraceOptions, MiddlewareConfig } from '##/lib/types.js' - - -export const koa = { - port: 7001, -} - -export const otelConfig: Config = { - ...initialConfig, - enableDefaultRoute: true, -} - -export const otelMiddlewareConfig: Readonly> = { - ...initialMiddlewareConfig, - ignore: [...initTracerIgnoreArray], -} - -// export const jaegerExporterConfig: InitTraceOptions['jaegerExporterConfig'] = { -// host: exporterAgentHost, -// } - - -export const otlpGrpcExporterConfig: InitTraceOptions['otlpGrpcExporterConfig'] = { - ...initOtlpGrpcExporterConfig, -} - -export const asyncContextManager = { - enable: true, -} - diff --git a/packages/otel/src/config/config.local.ts b/packages/otel/src/config/config.local.ts deleted file mode 100644 index 0414f3fd7..000000000 --- a/packages/otel/src/config/config.local.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - initTracerIgnoreArray, - initialConfig, - initialMiddlewareConfig, -} from '##/lib/config.js' -import { SpanExporterList } from '##/lib/types.js' -import type { Config, MiddlewareConfig } from '##/lib/types.js' - - -export const keys = Date.now().toString() - -export const otelConfig: Config = { - ...initialConfig, - enableDefaultRoute: true, - exporters: [ - // SpanExporterList.jaeger, - // SpanExporterList.console, - SpanExporterList.otlpGrpc, - ], -} - -export const otelMiddlewareConfig: Readonly> = { - ...initialMiddlewareConfig, - ignore: [ - ...initTracerIgnoreArray, - '/untraced_path_string', - new RegExp('/untraced_path_reg_exp$', 'u'), - ], -} - - diff --git a/packages/otel/src/config/config.unittest.ts b/packages/otel/src/config/config.unittest.ts deleted file mode 100644 index 43b735164..000000000 --- a/packages/otel/src/config/config.unittest.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { join } from 'node:path' - -import type { DefaultConfig as GClientConfig, IMidwayGRPFrameworkOptions } from '@midwayjs/grpc' -import { isFileExists, retrieveDirname } from '@waiting/shared-core' - -import { - initOtlpGrpcExporterConfig, - initTracerIgnoreArray, - initialConfig, - initialMiddlewareConfig, -} from '##/lib/config.js' -// import { processCustomFailure } from '##/lib/tracer.js' -import { PropagatorList, SpanExporterList } from '##/lib/types.js' -import type { Config, InitTraceOptions, MiddlewareConfig } from '##/lib/types.js' - - -export const keys = Date.now().toString() - -export const otelConfig: Config = { - ...initialConfig, - enableDefaultRoute: true, - exporters: [ - // SpanExporterList.console, - SpanExporterList.otlpGrpc, - ], - propagators: [ - PropagatorList.w3cTraceContext, - ], -} - -export const otelMiddlewareConfig: Readonly> = { - ...initialMiddlewareConfig, - enableMiddleware: true, - ignore: [ - ...initTracerIgnoreArray, - '/untraced_path_string', - new RegExp('/untraced_path_reg_exp$', 'u'), - ], -} - - -export const otlpGrpcExporterConfig: InitTraceOptions['otlpGrpcExporterConfig'] = { - ...initOtlpGrpcExporterConfig, -} -console.info({ otlpGrpcExporterConfig }) - - -const configDir = retrieveDirname(import.meta) -export const APP_BASE_DIR = join(configDir, '../..') -// 调试、单测时指向src目录,其余指向dist目录 -export const APP_DIST_DIR = join(configDir, '../') -console.info({ APP_BASE_DIR, APP_DIST_DIR }) - - -const protoPath = join(APP_BASE_DIR, 'test/grpc', 'helloworld.proto') -export const grpcServer: IMidwayGRPFrameworkOptions = { - // url: 'localhost:6565', -} -export const grpc: GClientConfig = { services: [] } -const rpcBaseConfig = { protoPath, package: 'helloworld' } - -if (await isFileExists(protoPath)) { - grpcServer.services = [{ ...rpcBaseConfig }] - grpc.services.push({ ...rpcBaseConfig, url: 'localhost:6565' }) -} - - diff --git a/packages/otel/src/configuration.ts b/packages/otel/src/configuration.ts deleted file mode 100644 index 0820491b8..000000000 --- a/packages/otel/src/configuration.ts +++ /dev/null @@ -1,139 +0,0 @@ -import assert from 'node:assert' - -import { - App, - Configuration, - ILifeCycle, - Inject, - Logger, - MidwayEnvironmentService, - MidwayFrameworkService, - MidwayInformationService, - MidwayWebRouterService, -} from '@midwayjs/core' -import { Application as RpcApp } from '@midwayjs/grpc' -import { ILogger } from '@midwayjs/logger' -import { - Application, - IMidwayContainer, - MConfig, - deleteRouter, - registerMiddleware, -} from '@mwcp/share' -import { sleep } from '@waiting/shared-core' - -import * as DefaultConfig from './config/config.default.js' -import * as LocalConfig from './config/config.local.js' -import * as UnittestConfig from './config/config.unittest.js' -import { useComponents } from './imports.js' -import { OtelComponent } from './lib/component.js' -import { TraceInit } from './lib/index.js' -import { AutoRegister } from './lib/reg-decorator.js' -import { - Config, - ConfigKey, - MiddlewareConfig, -} from './lib/types.js' -import { - TraceMiddleware, - TraceMiddlewareGRpc, - TraceMiddlewareInner, - TraceMiddlewareInnerGRpc, -} from './middleware/index.middleware.js' - - -@Configuration({ - namespace: ConfigKey.namespace, - importConfigs: [ - { - default: DefaultConfig, - local: LocalConfig, - unittest: UnittestConfig, - }, - ], - imports: useComponents, -}) -export class AutoConfiguration implements ILifeCycle { - - @App() readonly app: Application - @App('gRPC') readonly grpcApp: RpcApp | undefined - - @MConfig(ConfigKey.config) protected readonly config: Config - @MConfig(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig - - @Inject() protected readonly environmentService: MidwayEnvironmentService - @Inject() protected readonly informationService: MidwayInformationService - @Inject() protected readonly webRouterService: MidwayWebRouterService - @Inject() protected readonly frameworkService: MidwayFrameworkService - - @Inject() Reg: AutoRegister - @Inject() otel: OtelComponent - - @Logger() logger: ILogger - - async onConfigLoad(): Promise { - if (! this.config.enableDefaultRoute) { - await deleteRouter(`/_${ConfigKey.namespace}`, this.webRouterService) - } - // else if (this.mwConfig.ignore) { - // this.mwConfig.ignore.push(new RegExp(`/_${ConfigKey.namespace}/.+`, 'u')) - // } - } - - @TraceInit({ namespace: ConfigKey.componentName }) - async onReady(container: IMidwayContainer): Promise { - void container - assert( - this.app, - 'this.app undefined. If start for development, please set env first like `export MIDWAY_SERVER_ENV=local`', - ) - registerMiddleware(this.app, TraceMiddlewareInner, 'last') - - const grpcFramework = this.frameworkService.getFramework('gRPC') - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (grpcFramework) { - const rpcApp = grpcFramework.getApplication() as unknown as Application | undefined - if (rpcApp) { - registerMiddleware(rpcApp, TraceMiddlewareInnerGRpc, 'last') - } - } - } - - @TraceInit({ namespace: ConfigKey.componentName }) - async onServerReady(container: IMidwayContainer): Promise { - void container - if (this.config.enable) { - registerMiddleware(this.app, TraceMiddleware, 'first') - - const grpcFramework = this.frameworkService.getFramework('gRPC') - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (grpcFramework) { - const rpcApp = grpcFramework.getApplication() as unknown as Application | undefined - if (rpcApp) { - registerMiddleware(rpcApp, TraceMiddlewareGRpc, 'first') - } - } - - void setTimeout(async () => { - const mwNames = this.app.getMiddleware().getNames() - this.otel.addAppInitEvent({ - event: `${ConfigKey.componentName}.onServerReady.end`, - mwNames: JSON.stringify(mwNames), - }) - this.otel.endAppInitEvent() - }, 0) - } - - } - - async onStop(container: IMidwayContainer): Promise { - this.logger.info('[otel] onStop()') - if (this.config.enable) { - const otel = await container.getAsync(OtelComponent) - await otel.shutdown() - await sleep(100) - } - } - -} - diff --git a/packages/otel/src/helper/index.opentelemetry.ts b/packages/otel/src/helper/index.opentelemetry.ts deleted file mode 100644 index b9877487f..000000000 --- a/packages/otel/src/helper/index.opentelemetry.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from './trace.telemetry.js' - diff --git a/packages/otel/src/helper/resource.detector.ts b/packages/otel/src/helper/resource.detector.ts deleted file mode 100644 index 714a66ef6..000000000 --- a/packages/otel/src/helper/resource.detector.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { alibabaCloudEcsDetector } from '@opentelemetry/resource-detector-alibaba-cloud' -import { awsEc2Detector, awsEksDetector } from '@opentelemetry/resource-detector-aws' -import { containerDetector } from '@opentelemetry/resource-detector-container' -import { gcpDetector } from '@opentelemetry/resource-detector-gcp' -import { resources } from '@opentelemetry/sdk-node' - - -const detectors = [ - containerDetector, - resources.envDetectorSync, - resources.hostDetectorSync, - resources.osDetectorSync, - resources.processDetectorSync, - - alibabaCloudEcsDetector, - // Ordered AWS Resource Detectors as per: - // https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/resourcedetectionprocessor/README.md#ordering - awsEksDetector, - awsEc2Detector, - gcpDetector, -] - - -export const detectorResources = resources.detectResourcesSync({ - detectors, -}) - diff --git a/packages/otel/src/helper/trace.telemetry.ts b/packages/otel/src/helper/trace.telemetry.ts deleted file mode 100644 index 1cc31f204..000000000 --- a/packages/otel/src/helper/trace.telemetry.ts +++ /dev/null @@ -1,137 +0,0 @@ -import type { TextMapPropagator } from '@opentelemetry/api' -import { CompositePropagator, W3CTraceContextPropagator } from '@opentelemetry/core' -import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc' -import { JaegerPropagator } from '@opentelemetry/propagator-jaeger' -import { node, resources } from '@opentelemetry/sdk-node' -import { - ATTR_SERVICE_NAME, - ATTR_SERVICE_VERSION, -} from '@opentelemetry/semantic-conventions' - -import { PropagatorList, SpanExporterList } from '##/lib/types.js' -import type { InitTraceOptions } from '##/lib/types.js' - -import { detectorResources } from './resource.detector.js' - - - -interface InitTraceReturnType { - provider: node.NodeTracerProvider - processors: node.SpanProcessor[] -} - -export function initTrace(options: InitTraceOptions): InitTraceReturnType { - const { otelConfig } = options - - const resource = new resources.Resource({ - [ATTR_SERVICE_NAME]: otelConfig.serviceName, - [ATTR_SERVICE_VERSION]: otelConfig.serviceVersion, - }) - const resourceDefault = resources.Resource.default() - const resourceFull = resourceDefault.merge(resource).merge(detectorResources) - - - const processors: node.SpanProcessor[] = [] - otelConfig.exporters.forEach((exporter) => { - const processor = genExporterInstrumentation(options, exporter, options.isDevelopmentEnvironment) - processors.push(processor) - }) - - const provider = new node.NodeTracerProvider({ - resource: resourceFull, - spanLimits: { - linkCountLimit: 127, - }, - spanProcessors: processors, - }) - - const propagators = genPropagators(otelConfig.propagators) - provider.register({ - propagator: new CompositePropagator({ propagators }), - }); - ['SIGINT', 'SIGTERM'].forEach((signal) => { - process.on(signal, () => { - provider.shutdown().catch(console.error) - }) - }) - - // const globalProvider = trace.getTracerProvider() - // console.info({ globalProvider }) - // const spanProcessor = provider.activeSpanProcessor - // const spanProcessor2 = provider.getActiveSpanProcessor() - // void spanProcessor - // void spanProcessor2 - - const ret = { provider, processors } - return ret -} - -function genPropagators(list: PropagatorList[]): TextMapPropagator[] { - - const propagators: TextMapPropagator[] = [] - - list.forEach((propagator) => { - switch (propagator) { - /* c8 ignore next 4 */ - case PropagatorList.jaeger: { - propagators.push(new JaegerPropagator()) - break - } - - case PropagatorList.w3cTraceContext: { - propagators.push(new W3CTraceContextPropagator()) - break - } - - /* c8 ignore next 4 */ - default: { - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - throw new Error(`Propagator ${propagator} not implemented. Use registerInstrumentations() manually.`) - } - } - }) - return propagators -} - - -function genExporterInstrumentation( - options: InitTraceOptions, - exporterName: SpanExporterList, - isDevelopmentEnvironment: boolean, -): node.SpanProcessor { - - switch (exporterName) { - /* c8 ignore start :local test */ - case SpanExporterList.console: { - const exporter: node.SpanExporter = new node.ConsoleSpanExporter() - // const processor = isDevelopmentEnvironment - // ? new node.SimpleSpanProcessor(exporter) - // : new node.BatchSpanProcessor(exporter) - const processor = new node.BatchSpanProcessor(exporter) - return processor - } - /* c8 ignore stop */ - - // case SpanExporterList.jaeger: { - // const exporter: SpanExporter = new JaegerExporter(options.jaegerExporterConfig) - // const processor = new BatchSpanProcessor(exporter) - // provider.addSpanProcessor(processor) - // return processor - // } - - case SpanExporterList.otlpGrpc: { - const exporter: node.SpanExporter = new OTLPTraceExporter(options.otlpGrpcExporterConfig) - const processor = isDevelopmentEnvironment - ? new node.SimpleSpanProcessor(exporter) - : new node.BatchSpanProcessor(exporter) - return processor - } - - /* c8 ignore next 3 */ - default: - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - throw new TypeError(`Exporter ${exporterName} not implemented`) - - } -} - diff --git a/packages/otel/src/imports.ts b/packages/otel/src/imports.ts deleted file mode 100644 index a83178064..000000000 --- a/packages/otel/src/imports.ts +++ /dev/null @@ -1,30 +0,0 @@ -import * as grpc from '@midwayjs/grpc' -import * as info from '@midwayjs/info' -import * as koa from '@midwayjs/koa' -import * as swagger from '@midwayjs/swagger' -import * as share from '@mwcp/share' - - -/* c8 ignore next 4 */ -const CI = !! (process.env['MIDWAY_SERVER_ENV'] === 'unittest' - || process.env['MIDWAY_SERVER_ENV'] === 'local' - || process.env['NODE_ENV'] === 'unittest' - || process.env['NODE_ENV'] === 'local' -) - -export const useComponents: IComponentInfo[] = [] -if (CI) { - useComponents.push(koa) - useComponents.push(info) - useComponents.push(swagger) - useComponents.push(grpc) -} - -useComponents.push(share) - - -export interface IComponentInfo { - Configuration: unknown - [key: string]: unknown -} - diff --git a/packages/otel/src/index.ts b/packages/otel/src/index.ts deleted file mode 100644 index 9586f2f0c..000000000 --- a/packages/otel/src/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -import type { Config, ConfigKey, InitTraceOptions, MiddlewareConfig, middlewareEnableCacheKey } from './lib/types.js' - - -export { AutoConfiguration as Configuration } from './configuration.js' -export * from './app/index.controller.js' -export * from './lib/index.js' -export * from './middleware/index.middleware.js' -export * from './util/common.js' -export { - type AttributeValue, - type Attributes, - type Context, - type Context as TraceContext, - type Span, - type SpanContext, - type SpanOptions, - SpanKind, - SpanStatusCode, -} from '@opentelemetry/api' - -export { SemanticAttributes } from '@opentelemetry/semantic-conventions' - - -declare module '@midwayjs/core/dist/interface.js' { - interface MidwayConfig { - [ConfigKey.config]?: Partial - [ConfigKey.middlewareConfig]?: Partial - [ConfigKey.otlpGrpcExporterConfig]?: Partial - } -} -declare module '@midwayjs/koa/dist/interface.js' { - interface Context { - [middlewareEnableCacheKey]?: true - } -} - - diff --git a/packages/otel/src/lib/attrnames.types.ts b/packages/otel/src/lib/attrnames.types.ts deleted file mode 100644 index 82d3378c9..000000000 --- a/packages/otel/src/lib/attrnames.types.ts +++ /dev/null @@ -1,105 +0,0 @@ - -export enum AttrNames { - otel_status_code = 'otel.status_code', - otel_status_description = 'otel.status_description', - exception_message = 'exception.message', - - HTTP_ERROR_NAME = 'http.error_name', - HTTP_ERROR_MESSAGE = 'http.error_message', - HTTP_ERROR_CAUSE = 'http.error_cause', - HTTP_STATUS_TEXT = 'http.status_text', - - ServiceName = 'service.name', - ServiceVersion = 'service.version', - - Incoming_Request_data = 'incoming.request.data', - Outgoing_Request_data = 'outgoing.request.data', - Incoming_Response_data = 'incoming.response.data', - Outgoing_Response_data = 'outgoing.response.data', - - Http_Response_Code = 'http.response.code', - Http_Request_Body = 'http.request.body', - Http_Request_Query = 'http.request.query', - Http_Response_Body = 'http.response.body', - - CallerClass = 'caller.class', - CallerMethod = 'caller.method', - - reqId = 'reqId', - traceId = 'traceId', - ServicePid = 'service.pid', - ServicePpid = 'service.ppid', - ServiceMemoryUsage = 'service.memory.usage', - ServiceCpuUsage = 'service.cpu.usage', - - LogLevel = 'log.level', - LogThrottleMs = 'log.throttle', - IsTraced = '__isTraced__', - TopException = 'top-exception', - - Error = 'error', - Message = 'message', - Exception = 'exception', - Exception_Cause = 'exception.cause', - Exception_Type = 'exception.type', - - RequestStartTime = 'request.start.time', - RequestEndTime = 'request.end.time', - RequestBegin = 'request.begin', - RequestEnd = 'request.end', - PreProcessFinish = 'pre.process.finish', - PostProcessBegin = 'post.process.begin', - - FetchStart = 'fetch.start', - FetchFinish = 'fetch.finish', - FetchException = 'fetch.exception', - - QueryResponse = 'query.response', - QueryError = 'query.error', - QueryStart = 'query.start', - QueryFinish = 'query.finish', - QueryRowCount = 'row.count', - QueryCost = 'query.cost', - /** - * @deprecated use QueryCostThrottleInSec instead - */ - QueryCostThottleInSec = 'query.cost.thottle.in.sec', - QueryCostThrottleInSec = 'query.cost.throttle.in.sec', - /** - * @deprecated use QueryCostThrottleInMS instead - */ - QueryCostThottleInMS = 'query.cost.thottle.in.ms', - QueryCostThrottleInMS = 'query.cost.throttle.in.ms', - TransactionStart = 'transaction.start', - TransactionCommit = 'transaction.commit', - TransactionRollback = 'transaction.rollback', - - TransactionalRegister = 'Transactional.register', - TransactionalStart = 'Transactional.start', - TransactionalEnd = 'Transactional.end', - /** top, child, save-point */ - TransactionalEntryType = 'Transactional.entry', - - TrxPropagated = 'trx.propagated', - TrxPropagationType = 'trx.propagation.type', - TrxPropagationClass = 'trx.propagation.class', - TrxPropagationIsolationLevel = 'trx.propagation.isolation.level', - TrxPropagationFunc = 'trx.propagation.func', - TrxPropagationMethod = 'trx.propagation.method', - TrxPropagationPath = 'trx.propagation.path', - /** Setting value */ - TrxPropagationReadRowLockLevel = 'trx.propagation.read.rowlock.level', - /** Setting value */ - TrxPropagationWriteRowLockLevel = 'trx.propagation.write.rowlock.level', - /** Runtime level on builder */ - TrxPropagationRowLockLevel = 'trx.propagation.rowlock.level', - - ResponseMsg = 'response.msg', - // ErrMsg = 'err.msg', - // ErrStack = 'err.stack', - - ProcCpuinfo = 'proc.cpuinfo', - ProcDiskstats = 'proc.diskstats', - ProcMeminfo = 'proc.meminfo', - ProcStat = 'proc.stat', -} diff --git a/packages/otel/src/lib/component.ts b/packages/otel/src/lib/component.ts deleted file mode 100644 index 6fb3736d5..000000000 --- a/packages/otel/src/lib/component.ts +++ /dev/null @@ -1,624 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unnecessary-condition */ -import assert from 'node:assert' - -import { - App, - ApplicationContext, - Init, - Inject, - Logger, - MidwayDecoratorService, - MidwayEnvironmentService, - MidwayInformationService, - Singleton, -} from '@midwayjs/core' -import { ILogger } from '@midwayjs/logger' -import { - Application, - IMidwayContainer, - MConfig, -} from '@mwcp/share' -import { - Attributes, - Context as TraceContext, - Span, - SpanKind, - SpanOptions, - SpanStatus, - SpanStatusCode, - TimeInput, - context, - trace, -} from '@opentelemetry/api' -import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks' -import { node } from '@opentelemetry/sdk-node' -import { ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE } from '@opentelemetry/semantic-conventions' -import { genISO8601String, humanMemoryUsage } from '@waiting/shared-core' -import type { NpmPkg } from '@waiting/shared-types' - -import { initTrace } from '##/helper/index.opentelemetry.js' - -import { initSpanStatusOptions } from './config.js' -import { - AddEventOptions, - AttrNames, - Config, - ConfigKey, - InitTraceOptions, - SpanStatusOptions, - TraceScopeType, -} from './types.js' -import { getSpan, isSpanEnded, normalizeHeaderKey, setSpan } from './util.js' - -import PKG from '#package.json' with { type: 'json' } - - -/** OpenTelemetry Component */ -@Singleton() -export class OtelComponent { - - @App() readonly app: Application - @ApplicationContext() readonly applicationContext: IMidwayContainer - - @MConfig(ConfigKey.config) protected readonly config: Config - - // @MConfig(ConfigKey.jaegerExporterConfig) - // protected readonly jaegerExporterConfig: InitTraceOptions['jaegerExporterConfig'] - - @MConfig(ConfigKey.otlpGrpcExporterConfig) - protected readonly otlpGrpcExporterConfig: InitTraceOptions['otlpGrpcExporterConfig'] - - @Inject() protected readonly decoratorService: MidwayDecoratorService - @Inject() protected readonly environmentService: MidwayEnvironmentService - - @Logger() protected readonly logger: ILogger - - /** Active during Midway Lifecycle between onReady and onServerReady */ - appInitProcessContext: TraceContext | undefined - /** Active during Midway Lifecycle between onReady and onServerReady */ - appInitProcessSpan: Span | undefined - - otelLibraryName: string - otelLibraryVersion: string - /* request|response -> Map */ - readonly captureHeadersMap = new Map>() - // ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap - readonly traceContextMap = new WeakMap() - - protected traceProvider: node.NodeTracerProvider | undefined - protected spanProcessors: node.SpanProcessor[] = [] - - instId = Symbol(Date.now()) - - // constructor(options?: { name: string, version: string }) { - // super() - // if (options?.name) { - // const { name, version } = options - // this.otelLibraryName = name - // this.otelLibraryVersion = version ?? '' - // } - // } - - @Init() - async init(): Promise { - const key = `_${ConfigKey.componentName}` - // @ts-ignore - if (typeof this.app[key] === 'undefined') { - // @ts-ignore - this.app[key] = this - } - /* c8 ignore start */ - // @ts-ignore - else if (this.app[key] !== this) { - // @ts-ignore - const id = (this.app[key] as OtelComponent).instId.toString() - const currentId = this.instId.toString() - throw new Error(`this.app.${key} not equal to otel, id: ${id}, currentId: ${currentId}. - Check if you have multiple otel instances in your project.`) - } - /* c8 ignore stop */ - - const contextManager = new AsyncHooksContextManager() - contextManager.enable() - context.setGlobalContextManager(contextManager) // it seems no effect - - await this._init() - await this._app_init_start() - } - - getActiveContext(): TraceContext { - return context.active() - } - - getActiveSpan(traceContext?: TraceContext): Span | undefined { - /* c8 ignore next */ - if (! this.config.enable) { return } - return trace.getSpan(traceContext ?? context.active()) - } - - getTraceId(): string | undefined { - /* c8 ignore next */ - if (! this.config.enable) { return } - return this.getActiveSpan()?.spanContext().traceId - } - - // #region startScopeActiveSpan - - /** - * Starts a new {@link Span}. Start the span without setting it on context. - * This method do NOT modify the current Context. - */ - startSpan(name: string, options?: SpanOptions, traceContext?: TraceContext): { span: Span, traceContext: TraceContext } { - const ret = this.startSpanContext(name, options, traceContext) - return ret - } - - /** - * Starts a new {@link Span}. Start the span without setting it on context. - */ - startSpanContext(name: string, options?: SpanOptions, traceContext?: TraceContext): { span: Span, traceContext: TraceContext } { - assert(name, 'name must be set') - const tracer = trace.getTracer(this.otelLibraryName, this.otelLibraryVersion) - const opts: SpanOptions = { - kind: SpanKind.CLIENT, - ...options, - } - const span = tracer.startSpan(name, opts, traceContext) - const ctx = setSpan(traceContext ?? context.active(), span) - return { span, traceContext: ctx } - } - - // #region startScopeActiveSpan - - /** - * Starts a new {@link Span} and calls the given function passing it the created span as first argument. - * Additionally the new span gets set in context and this context is activated - * for the duration of the function call. - */ - startActiveSpan ReturnType>( - name: string, - callback: F, - options?: SpanOptions, - traceContext?: TraceContext, - ): ReturnType { - - assert(name, 'name must be set') - - const tracer = trace.getTracer(this.otelLibraryName, this.otelLibraryVersion) - const opts: SpanOptions = { - kind: SpanKind.CLIENT, - // startTime: Date.now(), - ...options, - } - const cb = (span: Span) => { - const activeCtx = context.active() - return callback(span, activeCtx) - } - const ret = traceContext - ? tracer.startActiveSpan(name, opts, traceContext, cb) - : tracer.startActiveSpan(name, opts, cb) - return ret - } - - async flush(): Promise { - const pms: Promise[] = [] - this.spanProcessors.forEach(proc => pms.push(proc.forceFlush())) - await Promise.allSettled(pms) - await this.traceProvider?.forceFlush() - } - - /* c8 ignore start */ - async shutdown(): Promise { - try { - const currSpan = this.getActiveSpan() - if (currSpan) { - currSpan.end() - } - } - catch (ex) { - this.logger.warn(ex) - } - await this.flush() - // await this.traceProvider?.shutdown() - } - /* c8 ignore stop */ - - - /** - * Adds an event to the given span. - */ - addEvent( - span: Span, - input: Attributes, - options?: AddEventOptions, - ): void { - - /* c8 ignore next */ - if (! this.config.enable) { return } - if (options?.traceEvent === false || ! this.config.traceEvent) { return } - - const eventName = typeof input['event'] === 'string' || typeof input['event'] === 'number' - ? String(input['event']) - : 'default' - const name = options?.eventName ?? eventName - delete input['event'] - - if (options?.logMemoryUsage ?? this.config.logMemoryUsage) { - input[AttrNames.ServiceMemoryUsage] = JSON.stringify(humanMemoryUsage(), null, 2) - } - if (options?.logCpuUsage ?? this.config.logCpuUsage) { - input[AttrNames.ServiceCpuUsage] = JSON.stringify(process.cpuUsage(), null, 2) - } - - span.addEvent(name, input, options?.startTime) - } - - addSpanEventWithError(span: Span, error?: Error): void { - /* c8 ignore next */ - if (! this.config.enable) { return } - /* c8 ignore next */ - if (! error) { return } - - const { cause } = error - // @ts-ignore - if (cause instanceof Error || error[AttrNames.IsTraced]) { - return // avoid duplicated logs for the same error on the root span - } - - const { name, message, stack } = error - const attrs: Attributes = { - [ATTR_EXCEPTION_TYPE]: 'exception', - [ATTR_EXCEPTION_MESSAGE]: message, - } - if (stack) { - attrs[ATTR_EXCEPTION_STACKTRACE] = stack - } - this.addEvent(span, attrs, { - eventName: `${name} Cause`, - }) // Error Cause - } - - - /** - * Sets the attributes to the given span. - */ - setAttributes(span: Span, input: Attributes): void { - /* c8 ignore next */ - if (! this.config.enable) { return } - span.setAttributes(input) - } - - setAttributesLater(span: Span, input: Attributes): void { - /* c8 ignore next */ - if (! this.config.enable) { return } - - setTimeout(() => { - try { - this.setAttributes(span, input) - } - catch (ex) { - console.error(ex) - } - }) - } - - - /** - * Sets the span with the error passed in params, note span not ended. - */ - setSpanWithError( - rootSpan: Span | undefined, - span: Span, - error: Error | undefined, - eventName?: string, - ): void { - - /* c8 ignore next */ - if (! this.config.enable) { return } - - const time = genISO8601String() - const attrs: Attributes = { - time, - } - if (eventName) { - attrs['event'] = eventName - } - - if (error) { - attrs[AttrNames.HTTP_ERROR_NAME] = error.name - attrs[AttrNames.HTTP_ERROR_MESSAGE] = error.message - span.setAttributes(attrs) - - // this.addSpanEventWithError(span, error) - - // @ts-ignore - IsTraced - if (error.cause instanceof Error || error[AttrNames.IsTraced]) { - if (rootSpan && span !== rootSpan) { - // error contains cause, then add events only - attrs[ATTR_EXCEPTION_MESSAGE] = 'skipping' - this.addEvent(span, attrs) - } - } - else { // if error contains no cause, add error stack to span - span.recordException(error) - } - - Object.defineProperty(error, AttrNames.IsTraced, { value: true }) - } - - span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message ?? 'unknown error' }) - } - - /** - * - ends the given span - * - set span with error if error passed in params - * - set span status - * - call span.end(), except span is root span - */ - endSpan( - rootSpan: Span | undefined, - span: Span, - spanStatusOptions: SpanStatusOptions = initSpanStatusOptions, - endTime?: TimeInput, - ): void { - - /* c8 ignore next */ - if (! this.config.enable) { return } - - const opts: SpanStatusOptions = { - ...initSpanStatusOptions, - ...spanStatusOptions, - } - const { code } = opts - if (code === SpanStatusCode.ERROR) { - this.setSpanWithError(rootSpan, span, spanStatusOptions.error) - } - else { // OK, UNSET - const status: SpanStatus = { - code, - } - if (opts.message) { - status.message = opts.message - } - span.setStatus(status) - } - - // root span not end here - if (! rootSpan || span !== rootSpan) { - span.end(endTime) - } - } - - endRootSpan( - rootSpan: Span, - spanStatusOptions: SpanStatusOptions = initSpanStatusOptions, - endTime?: TimeInput, - ): void { - - /* c8 ignore next */ - if (! this.config.enable) { return } - this.endSpan(rootSpan, rootSpan, spanStatusOptions, endTime) - rootSpan.end(endTime) - } - - addAppInitEvent( - input: Attributes, - options?: AddEventOptions, - /** if omit, use this.appInitProcessSpan */ - span?: Span, - ): void { - - const spanToUse = span ?? this.appInitProcessSpan - - if (spanToUse) { - const addEventOptions = { - traceEvent: true, - logCpuUsage: true, - logMemoryUsage: true, - ...options, - } - this.addEvent(spanToUse, input, addEventOptions) - } - } - - /** Called when onServerReady */ - endAppInitEvent(): void { - if (this.appInitProcessSpan) { - this.endRootSpan(this.appInitProcessSpan) - this.appInitProcessContext = void 0 - this.appInitProcessSpan = void 0 - } - } - - // #region traceContextMap - - getScopeRootTraceContext(scope: TraceScopeType): TraceContext | undefined { - /* c8 ignore next */ - if (! this.config.enable) { return } - - const tp = typeof scope - assert(tp === 'object' || tp === 'symbol', 'scope must be an object or symbol') - - const arr = this.traceContextMap.get(scope) - if (arr?.length) { - return arr[0] - } - } - - getScopeActiveContext(scope: TraceScopeType): TraceContext | undefined { - /* c8 ignore next */ - if (! this.config.enable) { return } - - const tp = typeof scope - assert(tp === 'object' || tp === 'symbol', 'scope must be an object or symbol') - - const arr = this.traceContextMap.get(scope) - if (arr?.length) { - return this.getActiveContextFromArray(arr) - } - } - - setScopeActiveContext(scope: TraceScopeType, ctx: TraceContext): void { - /* c8 ignore next */ - if (! this.config.enable) { return } - - const currCtx = this.getScopeActiveContext(scope) - if (currCtx === ctx) { return } - - const arr = this.traceContextMap.get(scope) - if (arr?.length) { - if (arr.at(-1) !== ctx) { - arr.push(ctx) - } - return - } - this.traceContextMap.set(scope, [ctx]) - } - - emptyScopeActiveContext(scope: TraceScopeType): void { - /* c8 ignore next */ - if (! this.config.enable) { return } - - const tp = typeof scope - assert(tp === 'object' || tp === 'symbol', 'scope must be an object or symbol') - - const arr = this.traceContextMap.get(scope) - if (arr) { - arr.length = 0 - } - this.traceContextMap.delete(scope) - } - - getRootSpan(scope: TraceScopeType): Span | undefined { - const rootTraceContext = this.getScopeRootTraceContext(scope) - if (! rootTraceContext) { return } - return getSpan(rootTraceContext) - } - - spanIsRootSpan(scope: TraceScopeType, span: Span): boolean { - const rootSpan = this.getRootSpan(scope) - return rootSpan === span - } - - - // #region protected - - /** - * Inactive context will be removed from the array - */ - protected getActiveContextFromArray(input: TraceContext[]): TraceContext | undefined { - const len = input.length - if (len === 0) { return } - - for (let i = len - 1; i >= 0; i -= 1) { - if (! input.length) { break } - - const traceContext = input.at(-1) - if (traceContext) { - const span = getSpan(traceContext) - if (! span) { - input.pop() - continue - } - const ended = isSpanEnded(span) - if (! ended && span.spanContext()) { - return traceContext - } - } - - input.pop() - } - } - - protected prepareCaptureHeaders(type: 'request' | 'response', headersKey: string[]) { - const keys = normalizeHeaderKey(headersKey) - this.captureHeadersMap.set(type, keys) - } - - protected async _init(): Promise { - assert( - this.app, - 'this.app undefined. If start for development, please set env first like `export MIDWAY_SERVER_ENV=local`', - ) - - let pkg: NpmPkg | undefined - const informationService = await this.app.getApplicationContext().getAsync(MidwayInformationService) - - if (informationService) { - pkg = informationService.getPkg() as NpmPkg - } - let serviceName = this.config.serviceName - ? this.config.serviceName - : pkg?.name ?? `unknown-${new Date().toLocaleDateString()}` - serviceName = serviceName.replace('@', '').replace(/\//ug, '-') - - const ver = this.config.serviceVersion - ? this.config.serviceVersion - : pkg?.version ?? '' - - // for registerDecoratorHandler - this.config.serviceName = serviceName - this.config.serviceVersion = ver - - if (! this.otelLibraryName) { - // const otelPkgPath = join(__dirname, '../../package.json') - // const otelPkgPath = join(__dirname, '../../package.json') - try { - // const { name, version } = await import(otelPkgPath) as NpmPkg - if (PKG.name) { - this.otelLibraryName = PKG.name - } - if (PKG.version) { - this.otelLibraryVersion = PKG.version - } - } - /* c8 ignore next 4 */ - catch { - // this.logger.warn('Failed to load package.json: %s', otelPkgPath) - this.logger.warn('Failed to load package.json') - } - } - } - - protected async _app_init_start(): Promise { - const isDevelopmentEnvironment = this.environmentService.isDevelopmentEnvironment() - && ! process.env['CI_BENCHMARK'] - - const { processors, provider } = initTrace({ - otelConfig: this.config, - // jaegerExporterConfig: this.jaegerExporterConfig, - otlpGrpcExporterConfig: this.otlpGrpcExporterConfig, - isDevelopmentEnvironment, - }) - this.traceProvider = provider - this.spanProcessors = processors - - const opts: SpanOptions = { - root: true, - kind: SpanKind.INTERNAL, - } - const spanName = 'APP INIT' - const traceCtx = this.getActiveContext() - - // this.appInitProcessSpan = this.startSpan(spanName, opts) - this.startActiveSpan(spanName, (span) => { - this.appInitProcessSpan = span - const ctxWithSpanSet = setSpan(traceCtx, span) - this.appInitProcessContext = ctxWithSpanSet - }, opts) - - // const span = this.getGlobalCurrentSpan(this.appInitProcessContext) - // void traceCtx - // void span - - this.prepareCaptureHeaders('request', this.config.captureRequestHeaders) - this.prepareCaptureHeaders('response', this.config.captureRequestHeaders) - - this.addAppInitEvent({ - event: `${ConfigKey.componentName}.init.end`, - }) - } -} - diff --git a/packages/otel/src/lib/config.ts b/packages/otel/src/lib/config.ts deleted file mode 100644 index c20d0711f..000000000 --- a/packages/otel/src/lib/config.ts +++ /dev/null @@ -1,92 +0,0 @@ -import type { IncomingHttpHeaders } from 'node:http' - -import { SpanStatusCode } from '@opentelemetry/api' -import { CompressionAlgorithm } from '@opentelemetry/otlp-exporter-base' -import type { OTLPGRPCExporterConfigNode } from '@opentelemetry/otlp-grpc-exporter-base' -import type { KnownKeys } from '@waiting/shared-types' - -import { AttrNames, HeadersKey, PropagatorList, SpanExporterList } from './types.js' -import type { Config, MiddlewareConfig, MiddlewareOptions, SpanStatusOptions } from './types.js' - -/** - * Initial config, contains: - * - authorization - * - host - * - user-agent - */ -// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -export const initCaptureRequestHeaders: (string | KnownKeys)[] = [ - HeadersKey.authorization, - HeadersKey.contentType, - HeadersKey.userAgent, - AttrNames.ServiceName, - AttrNames.ServiceVersion, -] - -const enableTrace = typeof process.env['DISABLE_OTEL_TRACE'] === 'undefined' - ? true - // @ts-expect-error - : ! (process.env['DISABLE_OTEL_TRACE'] === true || process.env['DISABLE_OTEL_TRACE'] === 'true') - -export const initialConfig: Readonly> = { - enable: enableTrace, - traceEvent: true, - logCpuUsage: false, - logMemoryUsage: false, - captureIncomingQuery: true, - captureRequestHeaders: [...initCaptureRequestHeaders], - captureResponseBody: true, - exporters: [SpanExporterList.otlpGrpc], - propagators: [ - PropagatorList.w3cTraceContext, - // PropagatorList.jaeger, - ], -} -export const initMiddlewareOptions: MiddlewareOptions = { -} -export const initialMiddlewareConfig: Readonly> = { - enableMiddleware: true, -} - -export const initTracerIgnoreArray: readonly (string | RegExp)[] = [ - '/favicon.ico', - '/favicon.png', - '/ping', - '/metrics', - '/untracedPath', - /\/unitTest[\d.]+/u, -] - -export const initSpanStatusOptions: SpanStatusOptions = { - /** - * The status code of this message. - * @default {@link SpanStatusCode.OK} - */ - code: SpanStatusCode.OK, - /** A developer-facing error message. */ - message: '', -} - -/** - * env: OTEL_EXPORTER_OTLP_ENDPOINT - * https://opentelemetry.io/docs/reference/specification/protocol/exporter/#configuration-options - * https://www.npmjs.com/package/@opentelemetry/exporter-trace-otlp-grpc - * @default http://localhost:4317 - * @example http://127.0.0.1:4317 - */ -export const exporterEndpoint = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] ?? 'http://localhost:4317' -/** - * https://www.npmjs.com/package/@opentelemetry/exporter-trace-otlp-grpc - * https://opentelemetry.io/docs/reference/specification/protocol/exporter/#configuration-options - */ -export const initOtlpGrpcExporterConfig: OTLPGRPCExporterConfigNode = { - /* url is optional and can be omitted - default is http://localhost:4317 */ - url: exporterEndpoint, - compression: CompressionAlgorithm.GZIP, -} - - -export const KEY_Trace = 'decorator:key_Trace' -export const METHOD_KEY_TraceInit = 'decorator:method_key_TraceInit' -export const METHOD_KEY_TraceLog = 'decorator:method_key_TraceLog' - diff --git a/packages/otel/src/lib/decorator-handler-trace-base.ts b/packages/otel/src/lib/decorator-handler-trace-base.ts deleted file mode 100644 index d895c80b6..000000000 --- a/packages/otel/src/lib/decorator-handler-trace-base.ts +++ /dev/null @@ -1,81 +0,0 @@ -import assert from 'node:assert' - -import { - type AsyncContextManager, - ASYNC_CONTEXT_KEY, - ASYNC_CONTEXT_MANAGER_KEY, - ApplicationContext, - IMidwayContainer, - Inject, -} from '@midwayjs/core' -import { type Context, DecoratorHandlerBase } from '@mwcp/share' -import { SpanStatusCode, context } from '@opentelemetry/api' - -import { type DecoratorExecutorParam, TraceService } from './trace.service/index.trace.service.js' -import { AttrNames } from './types.js' -import { isSpanEnded } from './util.js' - -/** - * Span will be ended if `autoEndSpan` is true when afterReturn() or afterThrow() - */ -export class DecoratorHandlerTraceBase extends DecoratorHandlerBase { - - @ApplicationContext() readonly applicationContext: IMidwayContainer - @Inject() protected readonly traceService: TraceService - - getWebContext(): Context | undefined { - try { - const contextManager: AsyncContextManager = this.applicationContext.get( - ASYNC_CONTEXT_MANAGER_KEY, - ) - const ctx = contextManager.active().getValue(ASYNC_CONTEXT_KEY) as Context | undefined - return ctx - } - catch (ex) { - // throw new Error('DecoratorHandlerTraceBase.getWebContext() failed. The trigger may not a request (eg. TraceInit())', { cause: ex }) - void ex - } - } - - override around(options: DecoratorExecutorParam): unknown { - if (options.traceContext) { - return context.with(options.traceContext, () => { - assert(typeof options.method === 'function', 'options.method should be a function') - return options.method(...options.methodArgs) - }) - } - assert(typeof options.method === 'function', 'options.method should be a function') - return options.method(...options.methodArgs) - } - - isEnable(options: DecoratorExecutorParam): boolean { - const { config } = options - /* c8 ignore next 3 */ - if (! config.enable) { - return false - } - return true - } - - traceError(options: DecoratorExecutorParam, error: Error, endSpan = true): void { - const { span, traceService } = options - if (! this.isEnable(options) || ! span) { return } - // @ts-ignore - IsTraced - else if (error[AttrNames.IsTraced] && isSpanEnded(span)) { return } - - const webCtx = options.webContext ?? this.getWebContext() ?? this.app - - if (endSpan) { - traceService.endSpan({ - span, - spanStatusOptions: { code: SpanStatusCode.ERROR, error }, - scope: options.traceScope ?? webCtx, - }) - } - else { - traceService.setSpanWithError(span, error, void 0, options.traceScope ?? webCtx) - } - // traceService.setRootSpanWithError(error, 'DecoratorHandlerTraceBase.traceError()', webCtx) - } -} - diff --git a/packages/otel/src/lib/decorator.helper.async.ts b/packages/otel/src/lib/decorator.helper.async.ts deleted file mode 100644 index 5339eb45b..000000000 --- a/packages/otel/src/lib/decorator.helper.async.ts +++ /dev/null @@ -1,83 +0,0 @@ -import assert from 'node:assert' - -import { processDecoratorSpanData } from './decorator.helper.base.js' -import type { - DecoratorContext, - DecoratorExecutorParam, - DecoratorTraceDataResp, - TraceDecoratorOptions, -} from './trace.service/index.trace.service.js' -import { getSpan, isSpanEnded } from './util.js' - -// #region processDecoratorBeforeAfterAsync - -/** - * @description options.{traceContext|span} may be modified with `traceContext` returned by `before()` or `after()` - */ -export async function processDecoratorBeforeAfterAsync( - type: 'before' | 'after' | 'afterThrow', - options: DecoratorExecutorParam, -): Promise { - - const { mergedDecoratorParam, span, traceService } = options - // not check traceService due to TraceInit decorator - assert(span, 'span is required') - - const func = mergedDecoratorParam?.[type] - if (typeof func === 'function') { - assert(! isSpanEnded(span), 'span is ended after method call') - const decoratorContext: DecoratorContext = { - webApp: options.webApp, - webContext: options.webContext, - traceService: options.traceService, - traceContext: options.traceContext, - traceSpan: span, - traceScope: options.traceScope, - /** Caller Class name */ - instanceName: options.instanceName, - /** Caller method name */ - methodName: options.methodName, - instance: options.instance, - } - - // const funcBind = isArrowFunction(func) ? func : func.bind(decoratorContext.instance) // sometimes not work detect arrow function - const funcBind = func.bind(decoratorContext.instance) - - let data: DecoratorTraceDataResp - if (type === 'before') { - const func2 = funcBind - // @ts-expect-error param type - data = await func2(options.methodArgs, decoratorContext) - } - else if (type === 'after') { - const func2 = funcBind - // @ts-expect-error param type - data = await func2(options.methodArgs, options.methodResult, decoratorContext) - } - else { - const func2 = funcBind - assert(options.error, 'options.error is required') - // @ts-expect-error param type - data = await func2(options.methodArgs, options.error, decoratorContext) - } - - if (data && Object.keys(data).length) { - const eventName = type - if (data.events && ! data.events['event']) { - data.events['event'] = eventName - } - - if (data.traceContext) { - options.traceContext = data.traceContext - options.span = getSpan(options.traceContext) - } - assert(options.span, `processDecoratorBeforeAfterAsync(): span is required with new traceContext returned by "${type}()"`) - - processDecoratorSpanData(options.rootTraceContext, traceService, options.span, data) - return data - } - - return null - } -} - diff --git a/packages/otel/src/lib/decorator.helper.base.ts b/packages/otel/src/lib/decorator.helper.base.ts deleted file mode 100644 index 2b47ca2ee..000000000 --- a/packages/otel/src/lib/decorator.helper.base.ts +++ /dev/null @@ -1,70 +0,0 @@ -import type { Span } from '@opentelemetry/api' - -import type { - DecoratorTraceDataResp, - TraceService, -} from './trace.service/index.trace.service.js' -import type { Attributes, TraceContext, TraceScopeParamType } from './types.js' -import { getSpan } from './util.js' - - -export function processDecoratorSpanData( - rootTraceContext: TraceContext, - traceService: TraceService, - span: Span, - info: DecoratorTraceDataResp | undefined, -): void { - - if (info && Object.keys(info).length > 0) { - const { attrs, events, rootAttrs, rootEvents } = info - if (! attrs && ! events && ! rootAttrs && ! rootEvents) { return } - - const rootSpan = getSpan(rootTraceContext) - processEvents(traceService, span, events) - processEvents(traceService, rootSpan, rootEvents) - - processAttrs(traceService, span, attrs) - processAttrs(traceService, rootSpan, rootAttrs) - } -} - -function processAttrs( - traceService: TraceService, - span: Span | undefined, - attrs: Attributes | undefined, -): void { - - if (! attrs || ! span || ! Object.keys(attrs).length) { return } - traceService.setAttributes(span, attrs) -} - -function processEvents( - traceService: TraceService, - span: Span | undefined, - events: Attributes | undefined, -): void { - - if (! events || ! span || ! Object.keys(events).length) { return } - traceService.addEvent(span, events) -} - -export function isTraceScopeParamType(input: TraceScopeParamType | undefined): input is TraceScopeParamType { - if (! input) { - return false - } - - switch (typeof input) { - case 'string': - return true - - case 'symbol': - return true - - case 'object': - return true - - default: - return false - } -} - diff --git a/packages/otel/src/lib/decorator.helper.sync.ts b/packages/otel/src/lib/decorator.helper.sync.ts deleted file mode 100644 index 8380b4f3d..000000000 --- a/packages/otel/src/lib/decorator.helper.sync.ts +++ /dev/null @@ -1,91 +0,0 @@ -import assert from 'node:assert' -import { isPromise } from 'node:util/types' - -import { processDecoratorSpanData } from './decorator.helper.base.js' -import type { - DecoratorContext, - DecoratorExecutorParam, - DecoratorTraceDataResp, - TraceDecoratorOptions, -} from './trace.service/index.trace.service.js' -import { AttrNames } from './types.js' -import { getSpan, isSpanEnded } from './util.js' - - -// #region processDecoratorBeforeAfterSync - -export function processDecoratorBeforeAfterSync( - type: 'before' | 'after' | 'afterThrow', - options: DecoratorExecutorParam, -): DecoratorTraceDataResp { - - const { mergedDecoratorParam, span, traceService } = options - // not check traceService due to TraceInit decorator - assert(span, 'span is required') - - const func = mergedDecoratorParam?.[type] - if (typeof func === 'function') { - assert(! isSpanEnded(span), 'span is ended after method call') - const decoratorContext: DecoratorContext = { - webApp: options.webApp, - webContext: options.webContext, - traceService: options.traceService, - traceContext: options.traceContext, - traceSpan: span, - traceScope: options.traceScope, - /** Caller Class name */ - instanceName: options.instanceName, - /** Caller method name */ - methodName: options.methodName, - instance: options.instance, - } - - // const funcBind = isArrowFunction(func) ? func : func.bind(decoratorContext.instance) // sometimes not work detect arrow function - const funcBind = func.bind(decoratorContext.instance) - - let data: DecoratorTraceDataResp - if (type === 'before') { - const func2 = funcBind - // @ts-expect-error param type - data = func2(options.methodArgs, decoratorContext) - } - else if (type === 'after') { - const func2 = funcBind - // @ts-expect-error param type - data = func2(options.methodArgs, options.methodResult, decoratorContext) - } - else { - const func2 = funcBind - assert(options.error, 'options.error is required') - // @ts-expect-error param type - data = func2(options.methodArgs, options.error, decoratorContext) - } - - if (data && Object.keys(data).length) { - if (isPromise(data)) { - const err = new Error(`processDecoratorBeforeAfterSync() decorator ${type}() return value is a promise, - class: ${options.callerAttr[AttrNames.CallerClass]}, method: ${options.callerAttr[AttrNames.CallerMethod]}`) - console.error(err) - return - } - - const eventName = type - if (data.events && ! data.events['event']) { - data.events['event'] = eventName - } - - if (data.traceContext) { - options.traceContext = data.traceContext - options.span = getSpan(options.traceContext) - } - assert(options.span, `processDecoratorBeforeAfterSync(): span is required with new traceContext returned by "${type}()"`) - - processDecoratorSpanData(options.rootTraceContext, traceService, options.span, data) - return data - } - - return null - } - -} - diff --git a/packages/otel/src/lib/decorator.trace-init/trace-init.decorator-handler.ts b/packages/otel/src/lib/decorator.trace-init/trace-init.decorator-handler.ts deleted file mode 100644 index e9605cd9b..000000000 --- a/packages/otel/src/lib/decorator.trace-init/trace-init.decorator-handler.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { Inject, Singleton } from '@midwayjs/core' -import { DecoratorExecutorParamBase, DecoratorHandlerBase, MConfig, genError } from '@mwcp/share' -import { SpanStatusCode } from '@opentelemetry/api' - -import { OtelComponent } from '../component.js' -import { genDecoratorExecutorOptions } from '../trace.helper.js' -import type { DecoratorExecutorParam, GenDecoratorExecutorOptions, TraceDecoratorOptions } from '../trace.service/index.trace.service.js' -import { TraceService } from '../trace.service/index.trace.service.js' -import { AttrNames, Config, ConfigKey } from '../types.js' -import { isSpanEnded } from '../util.js' - -import { afterReturn, before } from './trace-init.helper.async.js' - - -@Singleton() -export class DecoratorHandlerTraceInit extends DecoratorHandlerBase { - @MConfig(ConfigKey.config) protected readonly config: Config - - @Inject() protected readonly otelComponent: OtelComponent - @Inject() protected readonly traceService: TraceService - - isEnable(options: DecoratorExecutorParam): boolean { - /* c8 ignore next 3 */ - if (! options.config.enable) { - return false - } - const traceCtx = this.otelComponent.appInitProcessContext - /* c8 ignore next 3 */ - if (! this.otelComponent.appInitProcessSpan || ! traceCtx) { - return false - } - return true - } - - override genExecutorParam(options: DecoratorExecutorParamBase) { - const optsExt: GenDecoratorExecutorOptions = { - config: this.config, - traceService: this.traceService, - } - const ret = genDecoratorExecutorOptions(options, optsExt) - return ret - } - - override async before(options: DecoratorExecutorParam) { - /* c8 ignore next */ - if (! this.isEnable(options)) { return } - return before(options) - } - - /** - * Span will be ended if `autoEndSpan` is true when afterReturn() or afterThrow() - */ - override async afterReturn(options: DecoratorExecutorParam): Promise { - /* c8 ignore next 3 */ - if (! this.isEnable(options)) { - return options.methodResult - } - return afterReturn(options) - } - - /* c8 ignore start */ - /* tested via test/../configuration.ts#onConfigLoad() manually */ - override afterThrow(options: DecoratorExecutorParam): void { - const error = genError({ - error: options.error, - throwMessageIfInputUndefined: `[@mwcp/${ConfigKey.namespace}] TraceInit() afterThrow error is undefined`, - altMessage: `[@mwcp/${ConfigKey.namespace}] TraceInit() decorator afterThrow error`, - }) - this.traceError(options, error) - throw error - } - - // #region private methods - - private traceError(options: DecoratorExecutorParam, error: Error): void { - const { span } = options - if (! this.isEnable(options) || ! span) { return } - // @ts-ignore - IsTraced - else if (error[AttrNames.IsTraced] && isSpanEnded(span)) { return } - - this.otelComponent.endSpan(this.otelComponent.appInitProcessSpan, span, { code: SpanStatusCode.ERROR, error }) - } - /* c8 ignore stop */ -} - diff --git a/packages/otel/src/lib/decorator.trace-init/trace-init.helper.async.ts b/packages/otel/src/lib/decorator.trace-init/trace-init.helper.async.ts deleted file mode 100644 index 3f83a9924..000000000 --- a/packages/otel/src/lib/decorator.trace-init/trace-init.helper.async.ts +++ /dev/null @@ -1,90 +0,0 @@ -import assert from 'node:assert' - -import { SpanKind, context } from '@opentelemetry/api' -import type { Attributes, SpanOptions } from '@opentelemetry/api' - -import { processDecoratorBeforeAfterAsync } from '../decorator.helper.async.js' -import type { DecoratorExecutorParam, TraceDecoratorOptions } from '../trace.service/index.trace.service.js' - - -export async function before(options: DecoratorExecutorParam): Promise { - const { webApp, methodIsAsyncFunction } = options - assert(webApp, 'webApplication is required') - assert(methodIsAsyncFunction === true, 'decorated method must be AsyncFunction') - - const { - callerAttr, - spanName, - spanOptions, - mergedDecoratorParam, - traceService, - } = options - - options.traceScope = options.webApp - - const traceCtx = traceService.otel.appInitProcessContext - const spanOpts: SpanOptions = { - ...spanOptions, - kind: SpanKind.INTERNAL, - } - const { span, traceContext } = traceService.otel.startSpan(spanName, spanOpts, traceCtx) - options.span = span - options.traceContext = traceContext - - span.setAttributes(callerAttr) - const events: Attributes = { - event: `${spanName}.begin`, - } - const addEventOptions = { - traceEvent: true, - logCpuUsage: true, - logMemoryUsage: true, - } - traceService.otel.addEvent(span, events, addEventOptions) - - if (mergedDecoratorParam) { - await context.with(traceContext, async () => { - await processDecoratorBeforeAfterAsync('before', options) - }) - } -} - -export async function afterReturn(options: DecoratorExecutorParam): Promise { - const { span } = options - /* c8 ignore next 3 */ - if (! span) { - return options.methodResult - } - - const { webApp, methodIsAsyncFunction } = options - assert(webApp, 'webApplication is required') - assert(methodIsAsyncFunction === true, 'decorated method must be AsyncFunction') - - const { - spanName, - mergedDecoratorParam, - traceService, - } = options - - if (mergedDecoratorParam) { - const traceContext = traceService.getActiveContext() - await context.with(traceContext, async () => { - await processDecoratorBeforeAfterAsync('after', options) - }) - } - - const events2: Attributes = { - event: `${spanName}.end`, - } - const addEventOptions = { - traceEvent: true, - logCpuUsage: true, - logMemoryUsage: true, - } - traceService.otel.addEvent(span, events2, addEventOptions) - traceService.otel.endSpan(traceService.otel.appInitProcessSpan, span) - - return options.methodResult -} - - diff --git a/packages/otel/src/lib/decorator.trace-init/trace-init.ts b/packages/otel/src/lib/decorator.trace-init/trace-init.ts deleted file mode 100644 index 04f748dc3..000000000 --- a/packages/otel/src/lib/decorator.trace-init/trace-init.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { customDecoratorFactory } from '@mwcp/share' -import type { MethodTypeUnknown } from '@waiting/shared-types' - -import { METHOD_KEY_TraceInit } from '../config.js' -import type { TraceDecoratorOptions, TraceOptions } from '../trace.service/index.trace.service.js' - -import { DecoratorHandlerTraceInit } from './trace-init.decorator-handler.js' - - -/** - * 声明式中间件初始化装饰器 - * Declarative Trace init Decorator - * - * @description 可用于 AutoConfiguration 类中 - * @example ```ts - * export class AutoConfiguration implements ILifeCycle { - * \@TraceInit('INIT Foo.onReady') OR \@TraceInit({ namespace: 'Foo' }) - * async onReady(container: IMidwayContainer): Promise { - * // some code - * } - * } - * ``` - */ -export function TraceInit(options?: TraceOptions): MethodDecorator & ClassDecorator { - - const opts: Partial> = typeof options === 'string' - ? { spanName: options } - : options ?? {} - - if (! opts.spanNameDelimiter) { - opts.spanNameDelimiter = '.' - } - - return customDecoratorFactory({ - decoratorArgs: opts, - decoratorKey: METHOD_KEY_TraceInit, - enableClassDecorator: false, - classIgnoreIfMethodDecoratorKeys: [], - methodIgnoreIfMethodDecoratorKeys: [], - decoratorHandlerClass: DecoratorHandlerTraceInit, - }) -} - diff --git a/packages/otel/src/lib/decorator.trace-log/trace-log.decorator-handler.ts b/packages/otel/src/lib/decorator.trace-log/trace-log.decorator-handler.ts deleted file mode 100644 index 3efe273fd..000000000 --- a/packages/otel/src/lib/decorator.trace-log/trace-log.decorator-handler.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { Singleton } from '@midwayjs/core' -import { DecoratorExecutorParamBase, MConfig, genError } from '@mwcp/share' - -import { DecoratorHandlerTraceBase } from '../decorator-handler-trace-base.js' -import { genDecoratorExecutorOptions } from '../trace.helper.js' -import type { DecoratorExecutorParam, GenDecoratorExecutorOptions } from '../trace.service/index.trace.service.js' -import { TraceDecoratorOptions } from '../trace.service/index.trace.service.js' -import { Config, ConfigKey } from '../types.js' - -import { afterReturnAsync, afterThrowAsync as afterThrowAsync, beforeAsync } from './trace-log.helper.async.js' -import { afterReturnSync, afterThrowSync, beforeSync } from './trace-log.helper.sync.js' - - -@Singleton() -export class DecoratorHandlerTraceLog extends DecoratorHandlerTraceBase { - @MConfig(ConfigKey.config) protected readonly config: Config - - override genExecutorParam(options: DecoratorExecutorParamBase) { - const optsExt: GenDecoratorExecutorOptions = { - config: this.config, - traceService: this.traceService, - } - const ret = genDecoratorExecutorOptions(options, optsExt) - return ret - } - - override before(options: DecoratorExecutorParam) { - /* c8 ignore next */ - if (! this.isEnable(options)) { return } - if (! options.webContext) { - options.webContext = this.getWebContext() - } - - // Do NOT use isAsyncFunction(options.method), result may not correct - if (options.methodIsAsyncFunction) { - return beforeAsync(options) - } - beforeSync(options) - } - - override afterReturn(options: DecoratorExecutorParam): unknown { - /* c8 ignore next 3 */ - if (! this.isEnable(options)) { - return options.methodResult - } - - if (options.methodIsAsyncFunction) { - return afterReturnAsync(options) - } - return afterReturnSync(options) - } - - override afterThrow(options: DecoratorExecutorParam, errorExt?: unknown): never | Promise { - const error = genError({ - error: errorExt ?? options.error, - throwMessageIfInputUndefined: `[@mwcp/${ConfigKey.namespace}] Trace() afterThrow error is undefined`, - altMessage: `[@mwcp/${ConfigKey.namespace}] Trace() decorator afterThrow error`, - }) - options.error = error - - if (options.methodIsAsyncFunction) { - return afterThrowAsync(options).then(() => { - this.traceError(options, error, false) - throw error - }) - } - afterThrowSync(options) - this.traceError(options, error, false) - throw error - } - -} - diff --git a/packages/otel/src/lib/decorator.trace-log/trace-log.helper.async.ts b/packages/otel/src/lib/decorator.trace-log/trace-log.helper.async.ts deleted file mode 100644 index 6890860ad..000000000 --- a/packages/otel/src/lib/decorator.trace-log/trace-log.helper.async.ts +++ /dev/null @@ -1,75 +0,0 @@ -import assert from 'node:assert' - -import { context } from '@opentelemetry/api' - -import { processDecoratorBeforeAfterAsync } from '../decorator.helper.async.js' -import { endTraceSpan } from '../trace.helper.js' -import type { DecoratorExecutorParam, DecoratorTraceDataResp } from '../trace.service/index.trace.service.js' -import { ConfigKey } from '../types.js' - - -export async function beforeAsync(options: DecoratorExecutorParam): Promise { - const { traceService } = options - - const type = 'before' - if (! options.traceContext || ! options.span) { - const info = traceService.getActiveTraceInfo() - options.span = info.span - options.traceContext = info.traceContext - } - - await context.with(options.traceContext, async () => { - const res: DecoratorTraceDataResp = await processDecoratorBeforeAfterAsync(type, options) - if (res?.endSpanAfterTraceLog) { - assert(options.span, 'span is required') - if (Array.isArray(res.endSpanAfterTraceLog)) { - endTraceSpan(traceService, res.endSpanAfterTraceLog, res.spanStatusOptions) - } - else { - endTraceSpan(traceService, [options.span], res.spanStatusOptions) - } - } - }) -} - -export async function afterReturnAsync(options: DecoratorExecutorParam): Promise { - const { span, traceService } = options - /* c8 ignore next 3 */ - if (! span) { - return options.methodResult - } - - assert(! options.error, `[@mwcp/${ConfigKey.namespace}] options.error is not undefined in afterReturnAsync(). - Error: ${options.error?.message}`) - - if (! options.traceContext || ! options.span) { - const info = traceService.getActiveTraceInfo() - options.span = info.span - options.traceContext = info.traceContext - } - await context.with(options.traceContext, async () => { - const res: DecoratorTraceDataResp = await processDecoratorBeforeAfterAsync('after', options) - if (res?.endSpanAfterTraceLog) { - if (Array.isArray(res.endSpanAfterTraceLog)) { - endTraceSpan(traceService, res.endSpanAfterTraceLog, res.spanStatusOptions) - } - else { - endTraceSpan(traceService, [span], res.spanStatusOptions) - } - } - }) - - return options.methodResult -} - -export async function afterThrowAsync(options: DecoratorExecutorParam): Promise { - const { span } = options - if (! span) { return } - - assert(options.error, `[@mwcp/${ConfigKey.namespace}] options.error is undefined in afterThrowAsync().`) - const traceContext = options.traceContext ?? options.traceService.getActiveContext() - await context.with(traceContext, async () => { - await processDecoratorBeforeAfterAsync('afterThrow', options) - }) -} - diff --git a/packages/otel/src/lib/decorator.trace-log/trace-log.helper.sync.ts b/packages/otel/src/lib/decorator.trace-log/trace-log.helper.sync.ts deleted file mode 100644 index c8af6f779..000000000 --- a/packages/otel/src/lib/decorator.trace-log/trace-log.helper.sync.ts +++ /dev/null @@ -1,88 +0,0 @@ -import assert from 'node:assert' -import { isAsyncFunction } from 'node:util/types' - -import { ConfigKey } from '@mwcp/share' -import { context } from '@opentelemetry/api' - -import { processDecoratorBeforeAfterSync } from '../decorator.helper.sync.js' -import { endTraceSpan } from '../trace.helper.js' -import type { DecoratorExecutorParam, DecoratorTraceDataResp } from '../trace.service/index.trace.service.js' -import { AttrNames } from '../types.js' - - -export function beforeSync(options: DecoratorExecutorParam): void { - const { callerAttr, spanName, traceService } = options - const type = 'before' - - const func = options.mergedDecoratorParam?.[type] - assert( - ! func || ! isAsyncFunction(func), - `[@mwcp/${ConfigKey.namespace}] Trace() ${type}() is a AsyncFunction, but decorated method is sync function, class: ${callerAttr[AttrNames.CallerClass]}, method: ${callerAttr[AttrNames.CallerMethod]}`, - ) - assert(spanName, 'spanName is empty') - - if (! options.traceContext || ! options.span) { - const info = traceService.getActiveTraceInfo() - options.span = info.span - options.traceContext = info.traceContext - } - - context.with(options.traceContext, () => { - const res: DecoratorTraceDataResp = processDecoratorBeforeAfterSync(type, options) - if (res?.endSpanAfterTraceLog) { - assert(options.span, 'span is required') - if (Array.isArray(res.endSpanAfterTraceLog)) { - endTraceSpan(traceService, res.endSpanAfterTraceLog, res.spanStatusOptions) - } - else { - endTraceSpan(traceService, [options.span], res.spanStatusOptions) - } - } - }) - -} - - -export function afterReturnSync(options: DecoratorExecutorParam): unknown { - const { span, traceService } = options - /* c8 ignore next 3 */ - if (! span) { - return options.methodResult - } - - assert(! options.error, `[@mwcp/${ConfigKey.namespace}] options.error is not undefined in afterReturnSync(). - Error: ${options.error?.message}`) - - if (! options.traceContext || ! options.span) { - const info = traceService.getActiveTraceInfo() - options.span = info.span - options.traceContext = info.traceContext - } - context.with(options.traceContext, () => { - const res: DecoratorTraceDataResp = processDecoratorBeforeAfterSync('after', options) - if (res?.endSpanAfterTraceLog) { - if (Array.isArray(res.endSpanAfterTraceLog)) { - endTraceSpan(traceService, res.endSpanAfterTraceLog, res.spanStatusOptions) - } - else { - endTraceSpan(traceService, [span], res.spanStatusOptions) - } - } - }) - - return options.methodResult -} - - -export function afterThrowSync(options: DecoratorExecutorParam): void { - const { span } = options - if (! span) { return } - - assert(options.error, `[@mwcp/${ConfigKey.namespace}] options.error is undefined in afterThrowAsync().`) - const type = 'afterThrow' - const traceContext = options.traceContext ?? options.traceService.getActiveContext() - context.with(traceContext, () => { - processDecoratorBeforeAfterSync(type, options) - }) -} - diff --git a/packages/otel/src/lib/decorator.trace-log/trace-log.ts b/packages/otel/src/lib/decorator.trace-log/trace-log.ts deleted file mode 100644 index b52cb6427..000000000 --- a/packages/otel/src/lib/decorator.trace-log/trace-log.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { customDecoratorFactory } from '@mwcp/share' -import type { MethodTypeUnknown } from '@waiting/shared-types' - -import { METHOD_KEY_TraceLog } from '../config.js' -import type { TraceOptions } from '../trace.service/index.trace.service.js' - -import { DecoratorHandlerTraceLog } from './trace-log.decorator-handler.js' - - -/** - * Declarative TraceLog Decorator, - * add trace attribute to the span through decorator before()/after() method return object, - * no new span starting - * - add trace tag/log to current active span - * - add trace tag/log to root span - * @note return value of decorated method `before()` and `after()` should be type: - * ```ts - * interface DecoratorTraceData { - * attrs?: Attributes - * events?: Attributes - * rootAttrs?: Attributes - * rootEvents?: Attributes - * } - * ``` - */ -export function TraceLog(options?: TraceOptions): MethodDecorator { - - const opts = typeof options === 'string' - ? { spanName: options } - : options - - return customDecoratorFactory({ - decoratorArgs: opts, - decoratorKey: METHOD_KEY_TraceLog, - enableClassDecorator: false, - classIgnoreIfMethodDecoratorKeys: [], - methodIgnoreIfMethodDecoratorKeys: [], - decoratorHandlerClass: DecoratorHandlerTraceLog, - }) -} - diff --git a/packages/otel/src/lib/decorator.trace/trace.decorator-handler.ts b/packages/otel/src/lib/decorator.trace/trace.decorator-handler.ts deleted file mode 100644 index 03cca4c94..000000000 --- a/packages/otel/src/lib/decorator.trace/trace.decorator-handler.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { Singleton } from '@midwayjs/core' -import { DecoratorExecutorParamBase, MConfig, genError } from '@mwcp/share' - -import { DecoratorHandlerTraceBase } from '../decorator-handler-trace-base.js' -import { genDecoratorExecutorOptions } from '../trace.helper.js' -import type { DecoratorExecutorParam, GenDecoratorExecutorOptions, TraceDecoratorOptions } from '../trace.service/index.trace.service.js' -import { Config, ConfigKey } from '../types.js' - -import { afterReturnAsync, afterThrowAsync, beforeAsync } from './trace.helper.async.js' -import { afterReturnSync, afterThrowSync, beforeSync } from './trace.helper.sync.js' - - -@Singleton() -export class DecoratorHandlerTrace extends DecoratorHandlerTraceBase { - @MConfig(ConfigKey.config) protected readonly config: Config - - override genExecutorParam(options: DecoratorExecutorParamBase) { - const optsExt: GenDecoratorExecutorOptions = { - config: this.config, - traceService: this.traceService, - } - if (! options.webContext) { - options.webContext = this.getWebContext() - } - const ret = genDecoratorExecutorOptions(options, optsExt) - return ret - } - - override before(options: DecoratorExecutorParam) { - /* c8 ignore next */ - if (! this.isEnable(options)) { return } - - // Do NOT use isAsyncFunction(options.method), result may not correct - if (options.methodIsAsyncFunction) { - return beforeAsync(options) - } - beforeSync(options) - } - - /** - * Span will be ended if `autoEndSpan` is true when afterReturn() or afterThrow() - */ - override afterReturn(options: DecoratorExecutorParam): unknown { - /* c8 ignore next 3 */ - if (! this.isEnable(options)) { - return options.methodResult - } - - if (options.methodIsAsyncFunction) { - return afterReturnAsync(options) - } - return afterReturnSync(options) - } - - override afterThrow(options: DecoratorExecutorParam, errorExt?: unknown): never | Promise { - const error = genError({ - error: errorExt ?? options.error, - throwMessageIfInputUndefined: `[@mwcp/${ConfigKey.namespace}] Trace() afterThrow error is undefined`, - altMessage: `[@mwcp/${ConfigKey.namespace}] Trace() decorator afterThrow error`, - }) - options.error = error - - if (options.methodIsAsyncFunction) { - return afterThrowAsync(options).then(() => { - this.traceError(options, error, true) - throw error - }) - } - afterThrowSync(options) - this.traceError(options, error, true) - throw error - } - -} - diff --git a/packages/otel/src/lib/decorator.trace/trace.helper.async.ts b/packages/otel/src/lib/decorator.trace/trace.helper.async.ts deleted file mode 100644 index cd2847f87..000000000 --- a/packages/otel/src/lib/decorator.trace/trace.helper.async.ts +++ /dev/null @@ -1,80 +0,0 @@ -import assert from 'node:assert' - -import { context } from '@opentelemetry/api' - -import { processDecoratorBeforeAfterAsync } from '../decorator.helper.async.js' -import type { DecoratorExecutorParam } from '../trace.service/index.trace.service.js' -import { ConfigKey } from '../types.js' - - -export async function beforeAsync(options: DecoratorExecutorParam): Promise { - const { - callerAttr, - spanName, - startActiveSpan, - spanOptions, - traceService, - } = options - - const type = 'before' - const traceContext = options.traceContext ?? traceService.getActiveContext() - - if (startActiveSpan) { - const info = traceService.startScopeSpan({ name: spanName, spanOptions, traceContext, scope: options.traceScope }) - options.span = info.span - options.span.setAttributes(callerAttr) - options.traceContext = info.traceContext - await context.with(info.traceContext, async () => { - await processDecoratorBeforeAfterAsync(type, options) - }) - return - } - else { - // it's necessary to cost a little time to prevent next span.startTime is same as previous span.endTime - const rndStr = Math.random().toString(36).slice(7) - void rndStr - const info = traceService.startSpan(spanName, spanOptions, traceContext, options.traceScope) - options.span = info.span - options.span.setAttributes(callerAttr) - options.traceContext = info.traceContext - await context.with(info.traceContext, async () => { - await processDecoratorBeforeAfterAsync(type, options) - }) - return - } -} - -export async function afterReturnAsync(options: DecoratorExecutorParam): Promise { - const { span, traceService } = options - - assert(! options.error, `[@mwcp/${ConfigKey.namespace}] options.error is not undefined in afterReturnAsync(). - Error: ${options.error?.message}`) - - /* c8 ignore next 3 */ - if (! span) { - return options.methodResult - } - const type = 'after' - const traceContext = options.traceContext ?? traceService.getActiveContext() - await context.with(traceContext, async () => { - await processDecoratorBeforeAfterAsync(type, options) - }) - - const autoEndSpan = !! options.mergedDecoratorParam?.autoEndSpan - autoEndSpan && traceService.endSpan({ span, scope: options.webContext }) - - return options.methodResult -} - -export async function afterThrowAsync(options: DecoratorExecutorParam): Promise { - const { span } = options - if (! span) { return } - - assert(options.error, `[@mwcp/${ConfigKey.namespace}] options.error is undefined in afterThrowAsync().`) - const type = 'afterThrow' - const traceContext = options.traceContext ?? options.traceService.getActiveContext() - await context.with(traceContext, async () => { - await processDecoratorBeforeAfterAsync(type, options) - }) -} - diff --git a/packages/otel/src/lib/decorator.trace/trace.helper.sync.ts b/packages/otel/src/lib/decorator.trace/trace.helper.sync.ts deleted file mode 100644 index dc26fa2a5..000000000 --- a/packages/otel/src/lib/decorator.trace/trace.helper.sync.ts +++ /dev/null @@ -1,87 +0,0 @@ -import assert from 'node:assert' -import { isAsyncFunction } from 'node:util/types' - -import { ConfigKey } from '@mwcp/share' -import { context } from '@opentelemetry/api' - -import { processDecoratorBeforeAfterSync } from '../decorator.helper.sync.js' -import type { DecoratorExecutorParam } from '../trace.service/index.trace.service.js' -import { AttrNames } from '../types.js' - - -export function beforeSync(options: DecoratorExecutorParam): void { - const { - callerAttr, - spanName, - startActiveSpan, - spanOptions, - traceService, - } = options - - const type = 'before' - const traceContext = options.traceContext ?? traceService.getActiveContext() - - const func = options.mergedDecoratorParam?.[type] - assert( - ! func || ! isAsyncFunction(func), - `[@mwcp/${ConfigKey.namespace}] Trace() ${type}() is a AsyncFunction, but decorated method is sync function, class: ${callerAttr[AttrNames.CallerClass]}, method: ${callerAttr[AttrNames.CallerMethod]}`, - ) - assert(spanName, 'spanName is empty') - - if (startActiveSpan) { - const info = traceService.startScopeSpan({ name: spanName, spanOptions, traceContext, scope: options.traceScope }) - options.span = info.span - options.span.setAttributes(callerAttr) - options.traceContext = info.traceContext - context.with(info.traceContext, () => { - processDecoratorBeforeAfterSync(type, options) - }) - } - else { - // it's necessary to cost a little time to prevent next span.startTime is same as previous span.endTime - const rndStr = Math.random().toString(36).slice(7) - void rndStr - const info = traceService.startSpan(spanName, spanOptions, traceContext, options.traceScope) - options.span = info.span - options.span.setAttributes(callerAttr) - options.traceContext = info.traceContext - context.with(info.traceContext, () => { - processDecoratorBeforeAfterSync(type, options) - }) - } -} - -export function afterReturnSync(options: DecoratorExecutorParam): unknown { - const { span, traceService } = options - - assert(! options.error, `[@mwcp/${ConfigKey.namespace}] options.error is not undefined in afterReturnSync(). - Error: ${options.error?.message}`) - - /* c8 ignore next 3 */ - if (! span) { - return options.methodResult - } - const type = 'after' - const traceContext = options.traceContext ?? options.traceService.getActiveContext() - context.with(traceContext, () => { - processDecoratorBeforeAfterSync(type, options) - }) - - const autoEndSpan = !! options.mergedDecoratorParam?.autoEndSpan - autoEndSpan && traceService.endSpan({ span, scope: options.traceScope }) - - return options.methodResult -} - -export function afterThrowSync(options: DecoratorExecutorParam): void { - const { span } = options - if (! span) { return } - - assert(options.error, `[@mwcp/${ConfigKey.namespace}] options.error is undefined in afterThrowAsync().`) - const type = 'afterThrow' - const traceContext = options.traceContext ?? options.traceService.getActiveContext() - context.with(traceContext, () => { - processDecoratorBeforeAfterSync(type, options) - }) -} - diff --git a/packages/otel/src/lib/decorator.trace/trace.ts b/packages/otel/src/lib/decorator.trace/trace.ts deleted file mode 100644 index 0fd12b6d1..000000000 --- a/packages/otel/src/lib/decorator.trace/trace.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { customDecoratorFactory } from '@mwcp/share' -import type { MethodTypeUnknown } from '@waiting/shared-types' - -import { KEY_Trace } from '../config.js' -import type { TraceOptions } from '../trace.service/index.trace.service.js' - -import { DecoratorHandlerTrace } from './trace.decorator-handler.js' - - -/** - * Declarative Trace Decorator - */ -export function Trace(options?: TraceOptions): MethodDecorator { - - const opts = typeof options === 'string' - ? { spanName: options } - : options - - return customDecoratorFactory({ - decoratorArgs: opts, - decoratorKey: KEY_Trace, - enableClassDecorator: false, - classIgnoreIfMethodDecoratorKeys: [], - methodIgnoreIfMethodDecoratorKeys: [], - decoratorHandlerClass: DecoratorHandlerTrace, - }) -} - diff --git a/packages/otel/src/lib/http.types.ts b/packages/otel/src/lib/http.types.ts deleted file mode 100644 index 5d3432ea4..000000000 --- a/packages/otel/src/lib/http.types.ts +++ /dev/null @@ -1,112 +0,0 @@ -/* c8 ignore start */ -/* - * 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 type * as http from 'node:http' -import type * as https from 'node:https' -import type * as url from 'node:url' - -import type { Attributes, Span } from '@opentelemetry/api' -import type { InstrumentationConfig } from '@opentelemetry/instrumentation' - - -export type IgnoreMatcher = string | RegExp | ((url: string) => boolean) -export type HttpCallback = (res: http.IncomingMessage) => void -export type RequestFunction = typeof http.request -export type GetFunction = typeof http.get - -export type HttpCallbackOptional = HttpCallback | undefined - -// from node 10+ -export type RequestSignature = [http.RequestOptions, HttpCallbackOptional] & - HttpCallback - -export type HttpRequestArgs = (HttpCallbackOptional | RequestSignature)[] - -export type ParsedRequestOptions = - | (http.RequestOptions & Partial) - | http.RequestOptions -export type Http = typeof http -export type Https = typeof https -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export type Func = (...args: any[]) => T -export type ResponseEndArgs = - | [((() => void) | undefined)?] - | [unknown, ((() => void) | undefined)?] - | [unknown, string, ((() => void) | undefined)?] - -export type HttpCustomAttributeFunction = ( - span: Span, - request: http.ClientRequest | http.IncomingMessage, - response: http.IncomingMessage | http.ServerResponse -) => void - -export type IgnoreIncomingRequestFunction = (request: http.IncomingMessage) => boolean - -export type IgnoreOutgoingRequestFunction = (request: http.RequestOptions) => boolean - -export type HttpRequestCustomAttributeFunction = (span: Span, request: http.ClientRequest | http.IncomingMessage) => void - -export type HttpResponseCustomAttributeFunction = (span: Span, response: http.IncomingMessage | http.ServerResponse) => void - -export type StartIncomingSpanCustomAttributeFunction = (request: http.IncomingMessage) => Attributes - -export type StartOutgoingSpanCustomAttributeFunction = (request: http.RequestOptions) => Attributes - -/** - * Options available for the HTTP instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-instrumentation-http#http-instrumentation-options)) - */ -export interface HttpInstrumentationConfig extends InstrumentationConfig { - /** - * Not trace all incoming requests that match paths - * @deprecated use `ignoreIncomingRequestHook` instead - */ - ignoreIncomingPaths?: IgnoreMatcher[] - /** Not trace all incoming requests that matched with custom function */ - ignoreIncomingRequestHook?: IgnoreIncomingRequestFunction - /** Not trace all outgoing requests that matched with custom function */ - ignoreOutgoingRequestHook?: IgnoreOutgoingRequestFunction - /** Function for adding custom attributes after response is handled */ - applyCustomAttributesOnSpan?: HttpCustomAttributeFunction - /** Function for adding custom attributes before request is handled */ - requestHook?: HttpRequestCustomAttributeFunction - /** Function for adding custom attributes before response is handled */ - responseHook?: HttpResponseCustomAttributeFunction - /** Function for adding custom attributes before a span is started in incomingRequest */ - startIncomingSpanHook?: StartIncomingSpanCustomAttributeFunction - /** Function for adding custom attributes before a span is started in outgoingRequest */ - startOutgoingSpanHook?: StartOutgoingSpanCustomAttributeFunction - /** The primary server name of the matched virtual host. */ - serverName?: string - /** Require parent to create span for outgoing requests */ - requireParentforOutgoingSpans?: boolean - /** Require parent to create span for incoming requests */ - requireParentforIncomingSpans?: boolean - /** Map the following HTTP headers to span attributes. */ - headersToSpanAttributes?: { - client?: { requestHeaders?: string[], responseHeaders?: string[] }, - server?: { requestHeaders?: string[], responseHeaders?: string[] }, - } -} - -// export interface Err extends Error { -// errno?: number -// code?: string -// path?: string -// syscall?: string -// stack?: string -// } - -/* c8 ignore stop */ diff --git a/packages/otel/src/lib/index.ts b/packages/otel/src/lib/index.ts deleted file mode 100644 index 14fbec8c2..000000000 --- a/packages/otel/src/lib/index.ts +++ /dev/null @@ -1,59 +0,0 @@ - -export * from './config.js' -export { OtelComponent } from './component.js' -export { DecoratorHandlerTrace } from './decorator.trace/trace.decorator-handler.js' -export { DecoratorHandlerTraceInit } from './decorator.trace-init/trace-init.decorator-handler.js' -export { DecoratorHandlerTraceLog } from './decorator.trace-log/trace-log.decorator-handler.js' - -export * from './trace.logger.js' -export * from './trace.service/index.trace.service.js' -export * from './decorator.trace/trace.js' -export * from './decorator.trace-init/trace-init.js' -export * from './decorator.trace-log/trace-log.js' -export * from './reg-decorator.js' -export { - addSpanEventWithOutgoingResponseData, - deleteSpan, - genAttributesFromHeader, - genRequestSpanName, - getIncomingRequestAttributesFromWebContext, - getSpan, - normalizeHeaderKey, - parseResponseStatus, - propagateHeader, - propagateOutgoingHeader, - setResponseContentLengthAttribute, - setSpan, - setSpanWithRequestHeaders, -} from './util.js' - -export { - type AddEventOptions, - - type Attributes, - type AttributesMap, - type Config as OtelConfig, - type InitTraceOptions, - type JaegerTraceInfo, - type JaegerTraceInfoLog, - type JaegerTraceInfoLogField, - type JaegerTraceInfoReferences, - type JaegerTraceInfoSpan, - type MiddlewareConfig as OtelMiddlewareConfig, - type MiddlewareOptions as OtelMiddlewareOptions, - type SpanHeaderInit, - type SpanStatusOptions, - type TraceError, - type TraceLogType as LogInfo, - type TraceScopeParamType, - type TraceScopeType, - ConfigKey as OtelConfigKey, - HeadersKey, - Msg as TracerMsg, - SpanExporterList, -} from './types.js' - - -export { genDecoratorExecutorOptions } from './trace.helper.js' -export { AttrNames } from './attrnames.types.js' - diff --git a/packages/otel/src/lib/reg-decorator.ts b/packages/otel/src/lib/reg-decorator.ts deleted file mode 100644 index 2d15d02cc..000000000 --- a/packages/otel/src/lib/reg-decorator.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - App, - Autoload, - Init, - Inject, - MidwayDecoratorService, - Singleton, -} from '@midwayjs/core' -import { - Application, - registerDecoratorHandlers, -} from '@mwcp/share' - -import { KEY_Trace, METHOD_KEY_TraceInit } from './config.js' - - -/** Auto register trace decorator */ -@Autoload() -@Singleton() -export class AutoRegister { - @App() protected readonly app: Application - - @Inject() protected readonly decoratorService: MidwayDecoratorService - - @Init() - async init(): Promise { - await registerDecoratorHandlers(this.app, this.decoratorService, [METHOD_KEY_TraceInit, KEY_Trace]) - } -} - diff --git a/packages/otel/src/lib/trace.helper.ts b/packages/otel/src/lib/trace.helper.ts deleted file mode 100644 index 3df3dfcbd..000000000 --- a/packages/otel/src/lib/trace.helper.ts +++ /dev/null @@ -1,244 +0,0 @@ -import assert from 'node:assert' - -import type { DecoratorExecutorParamBase } from '@mwcp/share' -import { context } from '@opentelemetry/api' -import type { Span } from '@opentelemetry/api' -import { isArrowFunction } from '@waiting/shared-core' - -import type { SpanStatusOptions, TraceContext } from '##/lib/types.js' - -import type { - DecoratorContext, - DecoratorExecutorParam, - GenDecoratorExecutorOptions, - KeyGenerator, - TraceDecoratorOptions, -} from './trace.service/index.trace.service.js' -import type { TraceServiceSpan } from './trace.service/trace.service.span.js' -import { AttrNames } from './types.js' - - -const configNameList = [ - 'AutoConfiguration', - 'ContainerConfiguration', -] - -interface GenKeyOptions extends Partial { - methodArgs: unknown[] - decoratorContext: DecoratorContext - callerClass: string - callerMethod: string - instance: DecoratorExecutorParam['instance'] -} - -function genKey(options: GenKeyOptions): string { - const { - methodArgs, - decoratorContext, - spanName, - spanNameDelimiter, - instance, - } = options - - const delimiter = spanNameDelimiter - ? spanNameDelimiter - : '/' - - switch (typeof spanName) { - case 'string': { - if (spanName.length > 0) { - return spanName - } - break - } - - case 'undefined': { - let name = genEventKeyWhenSpanNameEmpty(options) - if (! name) { - name = `${options.callerClass.toString()}${delimiter}${options.callerMethod.toString()}` - } - return name - } - - case 'function': { - assert(instance, 'options.instance is required') - const funcBind: KeyGenerator = isArrowFunction(spanName) ? spanName : spanName.bind(instance) - const keyStr = funcBind(methodArgs as [], decoratorContext) - assert( - typeof keyStr === 'string' || typeof keyStr === 'undefined', - 'keyGenerator function must return a string or undefined', - ) - if (keyStr) { - return keyStr - } - break - } - - /* c8 ignore next 3 */ - default: { - assert(false, 'spanName must be a string or a function') - } - } - - const name = `${options.callerClass.toString()}${delimiter}${options.callerMethod.toString()}` - return name -} - -/** - * For TraceInit used on AutoConfiguration - */ -function genEventKeyWhenSpanNameEmpty(options: GenKeyOptions): string { - const { - callerClass, - callerMethod, - namespace, - spanName, - } = options - - assert(! spanName, 'spanName is not empty') - - let name = '' - - if (namespace && configNameList.includes(callerClass)) { - switch (callerMethod) { - /* c8 ignore next 4 */ - case 'onConfigLoad': { - name = `TraceInit ${namespace}.${options.callerMethod.toString()}` - break - } - - case 'onReady': { - name = `TraceInit ${namespace}.${options.callerMethod.toString()}` - break - } - - case 'onServerReady': { - name = `TraceInit ${namespace}.${options.callerMethod.toString()}` - break - } - - /* c8 ignore next 4 */ - case 'onStop': { - name = `TraceInit ${namespace}.${options.callerMethod.toString()}` - break - } - - /* c8 ignore next 4 */ - case 'onHealthCheck': { - name = `TraceInit ${namespace}.${options.callerMethod.toString()}` - break - } - - /* c8 ignore next 2 */ - default: - break - } - } - - return name -} - - -export function genDecoratorExecutorOptions( - optionsBase: DecoratorExecutorParamBase, - optionsExt: GenDecoratorExecutorOptions, -): DecoratorExecutorParam { - - const { methodArgs } = optionsBase - - const { traceService } = optionsExt - assert(traceService, 'traceService is required') - - const { mergedDecoratorParam } = optionsBase - assert(mergedDecoratorParam, 'mergedDecoratorParam is undefined') - - if (typeof mergedDecoratorParam.startActiveSpan !== 'boolean') { - mergedDecoratorParam.startActiveSpan = true - } - - if (typeof mergedDecoratorParam.autoEndSpan !== 'boolean') { - mergedDecoratorParam.autoEndSpan = true - } - - // DO NOT set traceContext - // if (! mergedDecoratorParam.traceContext) { - // mergedDecoratorParam.traceContext = traceService?.getActiveContext() - // } - - const decoratorContext: DecoratorContext = { - webApp: optionsBase.webApp, - webContext: optionsBase.webContext, - traceService, - traceContext: mergedDecoratorParam.traceContext, - traceSpan: void 0, - traceScope: void 0, - /** Caller Class name */ - instanceName: optionsBase.instanceName, - /** Caller method name */ - methodName: optionsBase.methodName, - instance: optionsBase.instance, - } - - const keyOpts: GenKeyOptions = { - ...mergedDecoratorParam, - callerClass: optionsBase.instanceName, - callerMethod: optionsBase.methodName, - decoratorContext, - methodArgs, - instance: optionsBase.instance, - } - const spanName = genKey(keyOpts) - assert(spanName, 'spanName is undefined') - - const callerAttr = { - [AttrNames.CallerClass]: optionsBase.instanceName, - [AttrNames.CallerMethod]: optionsBase.methodName, - } - - let rootTraceContext: TraceContext - if (optionsBase.webContext) { - rootTraceContext = optionsBase.webContext.getAttr('rootTraceContext') - } - else { - rootTraceContext = context.active() - } - if (optionsExt.config.enable) { - assert(rootTraceContext, 'rootTraceContext is undefined') - } - - const ret: DecoratorExecutorParam = { - ...optionsBase, - ...optionsExt, - rootTraceContext, - callerAttr, - spanName, - spanOptions: mergedDecoratorParam, - startActiveSpan: mergedDecoratorParam.startActiveSpan, - traceContext: mergedDecoratorParam.traceContext, - traceService, - traceScope: void 0, - span: void 0, - } - Object.defineProperty(ret, 'rootTraceContext', { - writable: false, - value: rootTraceContext, - }) - - return ret -} - - -export function endTraceSpan(traceService: TraceServiceSpan, span: Span[], spanStatusOptions: SpanStatusOptions | undefined): void { - const revertArr = span.slice().reverse() - revertArr.forEach((span) => { - _endTraceSpan(traceService, span, spanStatusOptions) - }) -} -function _endTraceSpan(traceService: TraceServiceSpan, span: Span, spanStatusOptions: SpanStatusOptions | undefined): void { - if (spanStatusOptions) { - traceService.endSpan({ span, spanStatusOptions }) - } - else { - traceService.endSpan({ span }) - } -} diff --git a/packages/otel/src/lib/trace.logger.ts b/packages/otel/src/lib/trace.logger.ts deleted file mode 100644 index 9bc1f366e..000000000 --- a/packages/otel/src/lib/trace.logger.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { - Inject, - Logger, - Provide, - Singleton, -} from '@midwayjs/core' -import { ILogger } from '@midwayjs/logger' -import { Context } from '@mwcp/share' -import type { Attributes, Span } from '@opentelemetry/api' - -import { OtelComponent } from './component.js' -import { TraceService } from './trace.service/index.trace.service.js' -import { AttrNames, TraceLogType } from './types.js' - - -/** - * 集成链路追踪 AppLogger - * - 打印日志同时会在链路上报日志级别和内容 - * - 生产环境应设置合理采样率避免过多的日志随链路上报 - */ -@Singleton() -export class TraceAppLogger implements ILogger { - - @Inject() protected readonly otel: OtelComponent - - @Logger() protected readonly logger: ILogger - - debug(msg: unknown, span: Span | undefined | false, ...args: unknown[]): void { - this.log({ level: 'debug', msg, args }, span) - } - - info(msg: unknown, span: Span | undefined | false, ...args: unknown[]): void { - this.log({ level: 'info', msg, args }, span) - } - - warn(msg: unknown, span: Span | undefined | false, ...args: unknown[]): void { - this.log({ level: 'warn', msg, args }, span) - } - - error(msg: unknown, span: Span | undefined | false, ...args: unknown[]): void { - this.log({ level: 'error', msg, args }, span) - } - - write(msg: unknown, span: Span | undefined | false, ...args: unknown[]): void { - this.log({ level: 'write', msg, args }, span) - } - - verbose(msg: unknown, span: Span | undefined | false, ...args: unknown[]): void { - this.log({ level: 'verbose', msg, args }, span) - } - - /** - * 打印日志同时会在链路上报日志级别和内容 - * @param span - * - undefined: 使用请求rootSpan - * - false: 仅打印日志,不上报 - */ - log( - input: TraceLogType, - span?: Span | false, - logger?: ILogger, - ): void { - - if (span !== false) { - traceAppLogger(input, this.otel, span) - } - origLogger(input, logger ?? this.logger) - } - -} - - -/** - * 集成链路追踪 Context Logger - * - 打印日志同时会在链路上报日志级别和内容 - * - 生产环境应设置合理采样率避免过多的日志随链路上报 - */ -@Provide() -export class TraceLogger implements ILogger { - - @Inject() readonly ctx: Context - @Inject() protected readonly logger: ILogger - @Inject() protected readonly traceSvc: TraceService - @Inject() protected readonly traceAppLogger: TraceAppLogger - - debug(msg: unknown, ...args: unknown[]): void { - this.log({ - level: 'debug', - msg, - args, - }) - } - - info(msg: unknown, ...args: unknown[]): void { - this.log({ - level: 'info', - msg, - args, - }) - } - - warn(msg: unknown, ...args: unknown[]): void { - this.log({ - level: 'warn', - msg, - args, - }) - } - - error(msg: unknown, ...args: unknown[]): void { - this.log({ - level: 'error', - msg, - args, - }) - } - - - write(msg: unknown, ...args: unknown[]): void { - this.log({ - level: 'write', - msg, - args, - }) - } - - verbose(msg: unknown, ...args: unknown[]): void { - this.log({ - level: 'verbose', - msg, - args, - }) - } - - /** - * 打印日志同时会在链路上报日志级别和内容 - * @param span - * - undefined: 使用请求rootSpan - * - false: 仅打印日志,不上报 - */ - log(input: TraceLogType, span?: Span | false): void { - const isStarted = this.traceSvc.isStartedMap.get(this.ctx) - if (isStarted) { - const currSpan = span ?? this.traceSvc.getRootSpan(this.ctx) - if (currSpan) { - this.traceAppLogger.log(input, currSpan, this.logger) - return - } - } - // log w/o trace - this.traceAppLogger.log(input, false, this.logger) - } - -} - -function traceAppLogger( - input: TraceLogType, - otel: OtelComponent, - span: Span | undefined, -): void { - - const currSpan = span ?? otel.getActiveSpan() - if (! currSpan) { return } - - const { msg, args } = input - const level = input.level ?? 'info' - - const name = input['event'] && typeof input['event'] === 'string' - ? input['event'] - : 'trace.log' - const event: Attributes = { - event: name, - [AttrNames.LogLevel]: level, - } - if (typeof msg !== 'undefined') { - event[AttrNames.Message] = typeof msg === 'string' ? msg : JSON.stringify(msg) - } - if (typeof args !== 'undefined') { - event['log.detail'] = JSON.stringify(args) - } - otel.addEvent(currSpan, event) -} - - -function origLogger( - input: TraceLogType, - logger: ILogger, -): void { - - const { msg, args } = input - const level = input.level ?? 'info' - - if (typeof msg === 'undefined') { - logger[level](input) - } - else if (Array.isArray(args)) { - - logger[level](msg, ...args) - } - else { - logger[level](msg) - } -} - - -// interface ILogger extends IMidwayLogger { -// info(msg: unknown, ...args: unknown[]): void -// debug(msg: unknown, ...args: unknown[]): void -// error(msg: unknown, ...args: unknown[]): void -// warn(msg: unknown, ...args: unknown[]): void -// } diff --git a/packages/otel/src/lib/trace.service/index.trace.service.ts b/packages/otel/src/lib/trace.service/index.trace.service.ts deleted file mode 100644 index 43a02f3bf..000000000 --- a/packages/otel/src/lib/trace.service/index.trace.service.ts +++ /dev/null @@ -1,5 +0,0 @@ - -export type { TraceOptions as TraceDecoratorArg } from './trace.service.js' -export * from './trace.service.js' -export type * from './trace.service.types.js' - diff --git a/packages/otel/src/lib/trace.service/trace.service.base.ts b/packages/otel/src/lib/trace.service/trace.service.base.ts deleted file mode 100644 index b478eb82d..000000000 --- a/packages/otel/src/lib/trace.service/trace.service.base.ts +++ /dev/null @@ -1,163 +0,0 @@ -import assert from 'node:assert' - -import { - type AsyncContextManager, - type IMidwayContainer, - ASYNC_CONTEXT_KEY, - ASYNC_CONTEXT_MANAGER_KEY, -} from '@midwayjs/core' -import { - type Application, - type Context, - type RouterInfoLite, - genISO8601String, - getRouterInfo, -} from '@mwcp/share' -import type { Context as TraceContext, Span } from '@opentelemetry/api' - -import type { OtelComponent } from '../component.js' -import type { Config, TraceScopeType } from '../types.js' -import { getSpan } from '../util.js' - - -export class TraceServiceBase { - declare app: Application - declare applicationContext: IMidwayContainer - declare config: Config - declare otel: OtelComponent - - readonly isStartedMap = new WeakMap () - readonly instanceId = Symbol(Date.now()) - readonly startTime = genISO8601String() - - // @FIXME - readonly routerInfoMap = new WeakMap() - - getWebContext(): Context | undefined { - try { - const contextManager: AsyncContextManager = this.applicationContext.get( - ASYNC_CONTEXT_MANAGER_KEY, - ) - const ctx = contextManager.active().getValue(ASYNC_CONTEXT_KEY) as Context | undefined - return ctx - } - catch (ex) { - void ex - // console.warn(new Error('getWebContext() failed', { cause: ex })) - return void 0 - } - } - - getWebContextThenApp(): Context | Application { - try { - const webContext = this.getWebContext() - assert(webContext, 'getActiveContext() webContext should not be null, maybe this calling is not in a request context') - return webContext - } - catch (ex) { - console.warn('getWebContextThenApp() failed', ex) - return this.app - } - } - - async addRequestRouterInfo(webCtx: Context): Promise { - const routerInfo = await getRouterInfo(webCtx) - // assert(routerInfo, new MidwayHttpError(`Path not found: "${webCtx.path}"`, 404)) - routerInfo && this.routerInfoMap.set(webCtx, routerInfo) - } - - getRequestRouterInfo(webCtx: TraceScopeType): RouterInfoLite | undefined { - const routerInfo = this.routerInfoMap.get(webCtx) - return routerInfo - } - - - // #region context methods - - getRootTraceContext(scope: TraceScopeType): TraceContext | undefined { - return this.otel.getScopeRootTraceContext(scope) - } - - setRootContext(scope: TraceScopeType, traceContext: TraceContext): void { - const rootCtx = this.getRootTraceContext(scope) - if (rootCtx && rootCtx === traceContext) { return } - assert(! rootCtx, 'TraceService.setRootContext() failed, scope root trace context exists already') - this.otel.setScopeActiveContext(scope, traceContext) - } - - - getActiveContext(): TraceContext { - const traceCtx = this.otel.getActiveContext() - return traceCtx - } - - - setActiveContext(traceContext: TraceContext, scope: TraceScopeType): void { - if (! this.config.enable) { return } - const obj = scope - this.otel.setScopeActiveContext(obj, traceContext) - } - - delActiveContext(scope?: TraceScopeType): void { - if (! this.config.enable) { return } - const obj = scope ?? this.getWebContext() - if (obj) { - this.otel.emptyScopeActiveContext(obj) - } - } - - retrieveContextBySpanId(scope: TraceScopeType, spanId: string): TraceContext | undefined { - assert(scope, 'getActiveContext() scope should not be null') - assert(spanId, 'retrieveContextBySpanId() spanId should not be empty') - - const arr = this.otel.traceContextMap.get(scope) - const len = arr?.length - if (! len) { return } - - for (let i = len - 1; i >= 0; i -= 1) { - const traceContext = arr.at(i) - if (traceContext) { - const span = getSpan(traceContext) - if (span && span.spanContext().spanId === spanId) { - return traceContext - } - } - continue - } - } - - retrieveTraceInfoBySpanId(spanId: string, scope: TraceScopeType | undefined): TraceInfo | undefined { - const scope2 = scope ?? this.getWebContext() - assert(scope2, 'retrieveTraceInfoBySpanId() scope should not be null') - - const traceContext = this.retrieveContextBySpanId(scope2, spanId) - if (traceContext) { - const span = getSpan(traceContext) - assert(span, 'retrieveTraceInfoBySpanId() span should not be null') - return { span, traceContext } - } - } - - retrieveParentTraceInfoBySpan(span: Span, scope?: TraceScopeType): TraceInfo | undefined { - // @ts-expect-error - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const pid = span.parentSpanId - assert(pid, 'retrieveParentTraceInfoBySpan() span.parentSpanId should not be null') - assert(typeof pid === 'string', 'retrieveParentTraceInfoBySpan() parentSpanId should be string') - const info = this.retrieveTraceInfoBySpanId(pid, scope) - return info - } - - - async flush(): Promise { - if (! this.config.enable) { return } - await this.otel.flush() - } - -} - - -export interface TraceInfo { - span: Span - traceContext: TraceContext -} diff --git a/packages/otel/src/lib/trace.service/trace.service.span.ts b/packages/otel/src/lib/trace.service/trace.service.span.ts deleted file mode 100644 index 5bffff573..000000000 --- a/packages/otel/src/lib/trace.service/trace.service.span.ts +++ /dev/null @@ -1,220 +0,0 @@ -import assert from 'node:assert' - -import type { Application, Context, GrpcContext } from '@mwcp/share' -import type { - Attributes, - Context as TraceContext, - Span, - SpanOptions, - TimeInput, -} from '@opentelemetry/api' -import { context as contextFunc } from '@opentelemetry/api' - -import { initSpanStatusOptions } from '../config.js' -import type { AddEventOptions, SpanStatusOptions, TraceScopeType } from '../types.js' -import { getSpan } from '../util.js' - -import { type TraceInfo, TraceServiceBase } from './trace.service.base.js' -import type { EndSpanOptions, StartScopeActiveSpanOptions } from './trace.service.types.js' - - -export class TraceServiceSpan extends TraceServiceBase { - - getTraceId(): string { - return this.otel.getTraceId() ?? '' - } - - getRootSpan(scope: TraceScopeType): Span | undefined { - const rootSpan = this.otel.getRootSpan(scope) - return rootSpan - } - - - /** - * Get span from the given scope, if not exists, get span from the request context or application. - */ - getActiveSpan(): Span | undefined { - return this.getActiveTraceInfo().span - } - - getActiveTraceInfo(): TraceInfo { - const traceCtx = this.getActiveContext() - const span = getSpan(traceCtx) - assert(span, 'getActiveTraceInfo() span should not be null') - return { span, traceContext: traceCtx } - } - - /** - * Starts a new {@link Span}. Start the span **without** setting it on context. - * This method do NOT modify the current Context. - * @default scope is `request ctx` - */ - startSpan( - name: string, - options?: SpanOptions, - traceContext?: TraceContext, - scope?: TraceScopeType, - ): TraceInfo { - - let traceCtx = traceContext - if (! traceCtx) { - const scope2 = scope ?? this.getWebContext() - assert(scope2, 'startSpan() scope should not be null') - traceCtx = this.getActiveContext() - } - - const ret = this.otel.startSpan(name, options, traceCtx) - return ret - } - - /** - * Starts a new {@link Span}. Start the span **without** setting it on context. - * @default scope is `request ctx` - */ - startScopeSpan(options: StartScopeActiveSpanOptions): TraceInfo { - const parentCtx = options.traceContext ?? this.getActiveContext() - const ret = this.otel.startSpanContext(options.name, options.spanOptions, parentCtx) - // const cb = (span: Span, ctx: TraceContext) => { return { span, traceContext: ctx } } - // const ret: TraceInfo = this.otel.startActiveSpan(options.name, cb, options.spanOptions, parentCtx) - assert(ret, 'startScopeActiveSpan() ret should not be null') - - const scope = options.scope ?? this.getWebContext() - if (scope) { - this.setActiveContext(ret.traceContext, scope) - } - return ret - } - - /** - * Starts a new {@link Span} and calls the given function passing it the created span as first argument. - * Additionally the new span gets set in context and this context is activated - * for the duration of the function call. - * - * @default scope is `this.ctx` - * @CAUTION: the span returned by this method is NOT ended automatically, - * you must to call `this.endSpan()` manually instead of span.edn() directly. - */ - startActiveSpan ReturnType>( - name: string, - callback: F, - options?: SpanOptions, - traceContext?: TraceContext, - scope?: TraceScopeType, - ): ReturnType { - - const scope2 = scope ?? this.getWebContext() - const { span, traceContext: traceCtx } = this.startScopeSpan({ - name, - spanOptions: options, - traceContext, - scope: scope2, - }) - return contextFunc.with(traceCtx, callback, void 0, span, traceCtx) - } - - /** - * Do following steps: - * - ends the given span - * - set span with error if error passed in params - * - set span status - * - call span.end(), except span is root span - */ - endSpan(options: EndSpanOptions): void { - const { span, spanStatusOptions, endTime, scope } = options - if (! this.config.enable) { return } - - const scope2 = scope ?? this.getWebContext() - const rootSpan = scope2 ? this.getRootSpan(scope2) : void 0 - const statusOpts = spanStatusOptions ?? initSpanStatusOptions - const isRootSpan = scope2 ? this.otel.spanIsRootSpan(scope2, span) : true // true? - if (isRootSpan) { - this.otel.endRootSpan(span, spanStatusOptions, endTime) - } - else { - this.otel.endSpan(rootSpan, span, statusOpts, endTime) - } - } - - endRootSpan( - spanStatusOptions: SpanStatusOptions = initSpanStatusOptions, - endTime?: TimeInput, - scope?: TraceScopeType, - ): void { - - if (! this.config.enable) { return } - assert(scope, 'scope should not be null') - - const rootSpan = this.getRootSpan(scope) - assert(rootSpan, 'traceService.endRootSpan(): rootSpan should not be null') - this.otel.endRootSpan(rootSpan, spanStatusOptions, endTime) - } - - - /** - * Sets the span with the error passed in params, note span not ended. - */ - setSpanWithError( - span: Span, - error: Error | undefined, - eventName?: string, - scope?: TraceScopeType, - ): void { - - if (! this.config.enable) { return } - - const scope2 = scope ?? this.getWebContext() - const rootSpan = scope2 ? this.getRootSpan(scope2) : void 0 - this.otel.setSpanWithError(rootSpan, span, error, eventName) - } - - /** - * Sets the span with the error passed in params, note span not ended. - */ - setRootSpanWithError( - error: Error | undefined, - eventName?: string, - scope?: Application | Context | GrpcContext, - ): void { - - if (! this.config.enable) { return } - - const scope2 = scope ?? this.getWebContext() - const rootSpan = scope2 ? this.getRootSpan(scope2) : void 0 - if (rootSpan) { - this.otel.setSpanWithError(rootSpan, rootSpan, error, eventName) - } - } - - /** - * Adds an event to the given span. - */ - addEvent( - span: Span, - input: Attributes, - options?: AddEventOptions, - ): void { - - if (! this.config.enable) { return } - this.otel.addEvent(span, input, options) - } - - /** - * Sets the attributes to the given span. - */ - setAttributes(span: Span | undefined, input: Attributes): void { - if (! this.config.enable) { return } - - let target = span - if (! target) { - const webCtx = this.getWebContext() - assert(webCtx, 'setAttributes() webCtx should not be null, maybe this calling is not in a request context') - const rootSpan = this.getRootSpan(webCtx) - assert(rootSpan, 'rootSpan should not be null') - target = rootSpan - } - this.otel.setAttributes(target, input) - } - -} - - diff --git a/packages/otel/src/lib/trace.service/trace.service.ts b/packages/otel/src/lib/trace.service/trace.service.ts deleted file mode 100644 index 8308def7e..000000000 --- a/packages/otel/src/lib/trace.service/trace.service.ts +++ /dev/null @@ -1,329 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import assert from 'node:assert' - -import { - App, - ApplicationContext, - IMidwayContainer, - Init, - Inject, - Singleton, -} from '@midwayjs/core' -import { - type ClzInstance, - type Context, - type DecoratorExecutorParamBase, - type GrpcContext, - Application, - MConfig, - retrieveRequestProtocolFromCtx, -} from '@mwcp/share' -import { - Attributes, - Context as TraceContext, - ROOT_CONTEXT, - Span, - SpanKind, - SpanOptions, - SpanStatusCode, - TimeInput, - propagation, -} from '@opentelemetry/api' -import { genISO8601String } from '@waiting/shared-core' -import type { MethodTypeUnknown } from '@waiting/shared-types' - -import { OtelComponent } from '../component.js' -import { initSpanStatusOptions } from '../config.js' -import { - type Config, - type MiddlewareConfig, - type SpanStatusOptions, - AttrNames, - ConfigKey, - TraceScopeType, - middlewareEnableCacheKey, -} from '../types.js' -import { - genRequestSpanName, - getIncomingRequestAttributesFromWebContext, - getSpan, - setSpanWithRequestHeaders, -} from '../util.js' - -import { TraceServiceSpan } from './trace.service.span.js' -import type { DecoratorTraceDataResp, DecoratorTraceDataRespAsync } from './trace.service.types.js' - - -@Singleton() -export class TraceService extends TraceServiceSpan { - @App() declare readonly app: Application - @ApplicationContext() declare readonly applicationContext: IMidwayContainer - - @MConfig(ConfigKey.config) declare readonly config: Config - @MConfig(ConfigKey.middlewareConfig) readonly mwConfig: MiddlewareConfig - - @Inject() declare readonly otel: OtelComponent - - @Init() - async init(): Promise { - await this.startOnInit(this.app) - } - - async startOnRequest(webCtx: Context): Promise { - if (! this.config.enable) { return } - if (webCtx.getAttr(middlewareEnableCacheKey) !== 'true') { return } - if (this.isStartedMap.get(webCtx) === true) { - return this.getActiveContext() - } - - await this.addRequestRouterInfo(webCtx) - - const traceContext = this.initRootSpan(webCtx) - this.isStartedMap.set(webCtx, true) - - const events: Attributes = { - event: AttrNames.RequestBegin, - time: this.startTime, - } - const rootSpan = getSpan(traceContext) - // const rootSpan = this.getRootSpan(webCtx) - // assert(rootSpan === rootSpan, 'span should be equal to rootSpan') - if (rootSpan) { - this.addEvent(rootSpan, events) - setSpanWithRequestHeaders( - rootSpan, - this.otel.captureHeadersMap.get('request'), - (key) => { - if (typeof webCtx.get === 'function') { - return webCtx.get(key) - } - }, - ) - } - - Promise.resolve() - .then(async () => { - const attrs = await getIncomingRequestAttributesFromWebContext(webCtx, this.config) - attrs[AttrNames.RequestStartTime] = this.startTime - this.setAttributes(rootSpan, attrs) - }) - .catch((err: Error) => { - this.setRootSpanWithError(err, void 0, webCtx) - console.error(err) - }) - - return traceContext - } - - - /** - * Finish the root span and clean the context. - */ - finish( - webCtx: Application | Context | GrpcContext, - spanStatusOptions: SpanStatusOptions = initSpanStatusOptions, - endTime?: TimeInput, - ): void { - - if (! this.config.enable) { return } - - if (! this.isStartedMap.get(webCtx)) { return } - - const time = genISO8601String() - - const events: Attributes = { - time, - event: AttrNames.RequestEnd, - } - - const rootSpan = this.getRootSpan(webCtx) - assert(rootSpan, 'rootSpan should not be null') - - this.addEvent(rootSpan, events) - - const attr: Attributes = { - [AttrNames.RequestEndTime]: time, - } - this.setAttributes(rootSpan, attr) - - if (spanStatusOptions.code !== SpanStatusCode.ERROR) { - spanStatusOptions.code = SpanStatusCode.OK - } - this.endRootSpan(spanStatusOptions, endTime, webCtx) - - this.delActiveContext(webCtx) - } - - - // #region protected methods - - protected async startOnInit(webApplication: Application): Promise { - if (! this.config.enable) { return } - if (this.isStartedMap.get(webApplication) === true) { return } - - this.isStartedMap.set(webApplication, true) - - // const events: Attributes = { - // event: AttrNames.RequestBegin, - // time: this.startTime, - // } - // const rootSpan = this.getRootSpan(webApplication) - // rootSpan && this.addEvent(rootSpan, events) - } - - - protected initRootSpan(scope: Context): TraceContext { - assert(scope, 'initRootSpan() webCtx should not be null, maybe this calling is not in a request context') - - let ret: TraceContext | undefined = void 0 - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - const traceCtx = typeof scope.getApp === 'function' && scope.request?.headers - ? propagation.extract(ROOT_CONTEXT, scope.request.headers) - : ROOT_CONTEXT - this.startActiveSpan( - this.genRootSpanName(scope), - (span, ctx) => { - assert(span, 'rootSpan should not be null on init') - this.setRootContext(scope, ctx) - ret = ctx - }, - { kind: SpanKind.SERVER }, - traceCtx, - scope, - ) - assert(ret, 'initRootSpan() failed') - return ret - } - - protected genRootSpanName(scope: Context): string { - const routerInfo = this.getRequestRouterInfo(scope) - const protocol = retrieveRequestProtocolFromCtx(scope) || 'unknown' - const opts = { - protocol, - method: scope.method, - route: routerInfo?.fullUrl ?? scope.path, - } - const spanName = this.config.rootSpanName && typeof this.config.rootSpanName === 'function' - ? this.config.rootSpanName(scope) - : genRequestSpanName(opts) - return spanName - } - -} - - -// #region types - -export interface GenDecoratorExecutorOptions { - config: Config - traceService: TraceService -} - -export type ExecutorParamBase = DecoratorExecutorParamBase - -export type DecoratorExecutorParam = ExecutorParamBase - & GenDecoratorExecutorOptions - & { - readonly rootTraceContext: TraceContext, - callerAttr: { [AttrNames.CallerClass]: string, [AttrNames.CallerMethod]: string }, - spanName: string, - spanOptions: Partial, - startActiveSpan: boolean, - traceContext: TraceContext | undefined, - traceScope: TraceScopeType | undefined, - span: Span | undefined, - } - -export type TraceOptions = Partial> | string - -// #region TraceDecoratorOptions - -export interface TraceDecoratorOptions< - /** Decorated method */ - M extends MethodTypeUnknown | undefined = undefined, - /** Arguments of decorated method */ - MParamType = M extends MethodTypeUnknown ? P : unknown[], - MResultType = M extends MethodTypeUnknown ? R : unknown, - MThis = unknown extends ThisParameterType ? ClzInstance : ThisParameterType, -> extends SpanOptions { - - /** @default `{target.name}/{methodName}` */ - spanName: string | KeyGenerator | undefined - /** - * @default true - */ - startActiveSpan: boolean - traceContext: TraceContext | undefined - /** - * Used as the prefix of the span name, - * if spanName is not provided, - * and the Caller ClassName is `AutoConfiguration` | `ContainerConfiguration`, - * and the Caller MethodName is event name, such as `onReady` | `onServerReady`, - */ - namespace: string | undefined - /** - * @default `/` - */ - spanNameDelimiter: string | undefined - - before: MethodTypeUnknown< - [MParamType, DecoratorContext], // input args - DecoratorTraceDataResp | DecoratorTraceDataRespAsync, // output data - ThisParameterType // this - > | undefined - - after: MethodTypeUnknown< - [MParamType, Awaited, DecoratorContext], // input args - DecoratorTraceDataResp | DecoratorTraceDataRespAsync, // output data - ThisParameterType // this - > | undefined - - afterThrow: MethodTypeUnknown< - [MParamType, Error, DecoratorContext], // input args - DecoratorTraceDataResp | DecoratorTraceDataRespAsync, // output data - ThisParameterType // this - > | undefined - - /** - * @default true - */ - autoEndSpan: boolean | undefined -} - -export type KeyGenerator< - TThis = any, - ArgsType = unknown[], - DContext extends DecoratorContext = DecoratorContext, -> = ( - this: TThis, - /** Arguments of the method */ - args: ArgsType, - context: DContext, -) => string | undefined - -export type ScopeGenerator< - TThis = any, - ArgsType = unknown[], - DContext extends DecoratorContextBase = DecoratorContextBase, -> = ( - this: TThis, - /** Arguments of the method */ - args: ArgsType, - context: DContext, -) => object | symbol - -export interface DecoratorContextBase { - webApp: Application | undefined - webContext: Context | undefined - traceService: TraceService | undefined - traceScope: TraceScopeType | undefined - /** Caller Class name */ - instanceName: string - methodName: string -} -export interface DecoratorContext extends DecoratorContextBase { - traceContext: TraceContext | undefined - traceSpan: Span | undefined - instance: T -} diff --git a/packages/otel/src/lib/trace.service/trace.service.types.ts b/packages/otel/src/lib/trace.service/trace.service.types.ts deleted file mode 100644 index 4bb4607ef..000000000 --- a/packages/otel/src/lib/trace.service/trace.service.types.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* c8 ignore start */ -import type { - Attributes, - Context as TraceContext, - Span, - SpanOptions, - TimeInput, -} from '@opentelemetry/api' - -import type { SpanStatusOptions, TraceScopeType } from '../types.js' - - -export interface StartScopeActiveSpanOptions { - name: string - /** - * @default scope is request context, grpc stream should be root trace context - */ - scope?: TraceScopeType | undefined - spanOptions?: SpanOptions | undefined - traceContext?: TraceContext | undefined -} - -export interface EndSpanOptions { - span: Span - scope?: TraceScopeType | undefined - spanStatusOptions?: SpanStatusOptions - endTime?: TimeInput -} - - -export interface DecoratorTraceData { - /** tags */ - attrs?: Attributes - /** logs */ - events?: Attributes - rootAttrs?: Attributes - rootEvents?: Attributes - - /** - * End the span after method `before()` or `after()` called - * used by TraceLog decorator, ignored by TraceInit/Trace decorator - * @default false - * @description if Array, end all spans in the array, and leaf span will be the last one - */ - endSpanAfterTraceLog?: boolean | Span[] - /** - * Used by TraceLog decorator and endSpanAfterTraceLog:true, ignored by TraceInit/Trace decorator - */ - spanStatusOptions?: SpanStatusOptions - /** - * options.traceContext will be overwritten by this value, and options.span also will be updated - */ - traceContext?: TraceContext -} -export type DecoratorTraceDataResp = DecoratorTraceData | undefined | null -export type DecoratorTraceDataRespAsync = Promise - -/* c8 ignore stop */ diff --git a/packages/otel/src/lib/types.ts b/packages/otel/src/lib/types.ts deleted file mode 100644 index dab4e7338..000000000 --- a/packages/otel/src/lib/types.ts +++ /dev/null @@ -1,280 +0,0 @@ - -import type { IncomingHttpHeaders } from 'node:http' - -import type { ILogger } from '@midwayjs/logger' -import type { BaseConfig, Context, ScopeType } from '@mwcp/share' -import type { - AttributeValue, - Attributes, - Context as TraceContext, - SpanStatusCode, - TimeInput, -} from '@opentelemetry/api' -import type { OTLPGRPCExporterConfigNode as OTLPGRPCExporterConfig } from '@opentelemetry/otlp-grpc-exporter-base' -import type { node } from '@opentelemetry/sdk-node' -import type { KnownKeys, MiddlewareConfig as MWConfig } from '@waiting/shared-types' - -import { AttrNames } from './attrnames.types.js' - - -export type NodeTracerConfig = node.TracerConfig -export { - type Attributes, type TraceContext, AttrNames, -} - - -export enum ConfigKey { - namespace = 'otel', - config = 'otelConfig', - middlewareConfig = 'otelMiddlewareConfig', - componentName = 'otelComponent', - serviceName = 'otelService', - middlewareName = 'otelMiddleware', - middlewareNameInner = 'otelMiddlewareInner', - otlpGrpcExporterConfig = 'otlpGrpcExporterConfig', -} - -export const middlewareEnableCacheKey = `${ConfigKey.middlewareName}-enabled` - -export enum Msg { - hello = 'hello otel', -} - -export interface Config extends BaseConfig { - /** - * Enable tracing - * @default true - */ - enable: boolean - /** - * Whether add event to span - * @default true - */ - traceEvent: boolean - /** - * @default true - */ - /** - * - GET: request.query - * - POST: request.body (only when content-type: 'application/json') - * @default true - */ - captureIncomingQuery: boolean - /** - * @default ['authorization', 'host', 'user-agent'] - */ - // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents - captureRequestHeaders: (string | KnownKeys)[] - /** - * @default false - */ - captureResponseBody: boolean - /** - * Log cpu usage when add span event - * @default false - */ - logCpuUsage: boolean - /** - * Log cpu usage when add span event - * @default false - */ - logMemoryUsage: boolean - /** - * @default [PropagatorList.w3cTraceContext] - */ - propagators: PropagatorList[] - /** - * Trace Exporter - * @default - * - [SpanExporter.otlpGrpc] for prod and unittest - * - [SpanExporter.otlpGrpc, SpanExporter.console] for dev - * @link https://opentelemetry.io/docs/instrumentation/js/instrumentation/ - * @link https://opentelemetry.io/docs/instrumentation/js/exporters/ - */ - exporters: SpanExporterList[] - /** - * @default pkg.name - * @description \@ 字符将会被删除,/ 替换为 - ,便于(ali)日志服务能正常分类 - */ - serviceName?: string - /** - * @default pkg.version - */ - serviceVersion?: string - /** - * Callback to process custom failure - */ - processCustomFailure?: (ctx: Context) => Promise - /** - * Optional function generating root span name, - * if omitted, then `${ctx.protocol} ${method} ${ctx.url}`, - * eg. `HTTP GET /api/v1/users` - */ - rootSpanName?: (ctx: Context) => string -} - -export enum SpanExporterList { - console = 'console', - /** - * https://www.npmjs.com/package/@opentelemetry/exporter-trace-otlp-grpc - */ - otlpGrpc = 'otlp-grpc', -} -/** - * https://opentelemetry.io/docs/reference/specification/context/api-propagators/#propagators-distribution - */ -export enum PropagatorList { - jaeger = 'jaeger', - w3cTraceContext = 'W3CTraceContext', -} - - -/** Options for middleware */ - -export type MiddlewareOptions = object -export type MiddlewareConfig = MWConfig - -export enum HeadersKey { - /** - * format: {trace-id}:{span-id}:{parent-span-id}:{flags} - */ - traceId = 'uber-trace-id', - TRACE_PARENT_HEADER = 'traceparent', - TRACE_STATE_HEADER = 'tracestate', - /** - * @deprecated use HeadersKey.TRACE_PARENT_HEADER - */ - // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values - otelTraceId = 'traceparent', - reqId = 'x-request-id', - authorization = 'authorization', - contentType = 'content-type', - userAgent = 'user-agent', -} - - -export interface SpanHeaderInit extends Attributes { - [HeadersKey.traceId]: string -} - -export interface TraceLogType { - /** - * debug | info | warn | error - * @default info - */ - level?: keyof ILogger - msg: unknown - args?: unknown[] - [key: string]: unknown -} - -export interface SpanRawLog { - timestamp: number - fields: SpanRawLogField[] -} -export interface SpanRawLogField { - key: string - value: unknown -} -export interface SpanRawTag { - key: string - value: unknown -} -export interface TestSpanInfo { - startTime: [number, number] - attributes: Record - name: string - status: { code: number } -} - -export interface InitTraceOptions { - [ConfigKey.config]: Config - [ConfigKey.otlpGrpcExporterConfig]: OTLPGRPCExporterConfig - /** - * - true: using SimpleSpanProcessor - * - false: using BatchSpanProcessor - */ - isDevelopmentEnvironment: boolean -} - -// export type CreateActiveSpanCallback = (span: Span) => unknown - -export interface SpanStatusOptions { - /** - * The status code of this message. - * @default SpanStatusCode.OK - */ - code: SpanStatusCode - /** normal message. */ - message?: string - error?: Error -} - -export type AttributesMap = Map - - -export interface JaegerTraceInfo { - traceID: string - spans: JaegerTraceInfoSpan[] - total: number - limit: number - offset: number - errors: unknown -} - -export interface JaegerTraceInfoSpan { - traceID: string - spanID: string - flags: number - operationName: string - references: JaegerTraceInfoReferences[] - startTime: number - duration: number - tags: Attributes[] - logs: JaegerTraceInfoLog[] - processID: string - warnings: unknown -} - -export interface JaegerTraceInfoReferences { - refType: 'CHILD_OF' - traceID: string - spanID: string -} - -export interface JaegerTraceInfoLog { - timestamp: number - fields: JaegerTraceInfoLogField[] -} - -export interface JaegerTraceInfoLogField { - key: string - type: string - value: AttributeValue -} - - -export interface TraceError extends Error { - [AttrNames.IsTraced]?: boolean -} - -export interface AddEventOptions { - /** - * false not add span event - */ - traceEvent?: boolean - /** - * @default true - */ - logCpuUsage?: Config['logCpuUsage'] - /** - * @default true - */ - logMemoryUsage?: Config['logMemoryUsage'] - eventName?: string - startTime?: TimeInput -} - -export type TraceScopeParamType = string | ScopeType -export type TraceScopeType = ScopeType - diff --git a/packages/otel/src/lib/util.ts b/packages/otel/src/lib/util.ts deleted file mode 100644 index 23e504b79..000000000 --- a/packages/otel/src/lib/util.ts +++ /dev/null @@ -1,491 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unnecessary-type-parameters */ -import assert from 'node:assert' -import type { - IncomingHttpHeaders, - IncomingMessage, - OutgoingHttpHeaders, - OutgoingMessage, -} from 'node:http' - -import { getRouterInfo } from '@mwcp/share' -import type { Context as WebContext } from '@mwcp/share' -import { - SpanKind, - SpanStatusCode, - createContextKey, - propagation, -} from '@opentelemetry/api' -import type { Attributes, Context as TraceContext, Span } from '@opentelemetry/api' -import { ATTR_HTTP_ROUTE } from '@opentelemetry/semantic-conventions' -import type { Headers as UndiciHeaders } from 'undici' - -import { AttrNames } from './types.js' -import type { Config } from './types.js' - - -const defaultProperty: PropertyDescriptor = { - configurable: true, - enumerable: true, - writable: false, -} - - -/** - * span key - */ -const SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN') -/** - * Return the span if one exists - * - * @param context context to get span from - */ -export function getSpan(context: TraceContext): Span | undefined { - return context.getValue(SPAN_KEY) as Span | undefined -} -/** - * Set the span on a context - * - * @param context context to use as parent - * @param span span to set active - */ -export function setSpan(context: TraceContext, span: Span): TraceContext { - return context.setValue(SPAN_KEY, span) -} -/** - * Remove current span stored in the context - * - * @param context context to delete span from - */ -export function deleteSpan(context: TraceContext): TraceContext { - return context.deleteValue(SPAN_KEY) -} - -export function isSpanEnded(span: Span): boolean { - // @ts-expect-error - if (typeof span.ended === 'boolean') { - // @ts-expect-error - - return span.ended as boolean - } - - /* c8 ignore start */ - if (typeof span.isRecording === 'function') { - return ! span.isRecording() - } - throw new Error('span.ended() and span.isRecording() are not functions, we cannot determine if the span is ended') - /* c8 ignore stop */ -} - -/** - * Parse status code from HTTP response. - */ -export function parseResponseStatus(kind: SpanKind, statusCode?: number): SpanStatusCode { - const upperBound = kind === SpanKind.CLIENT ? 400 : 500 - // 1xx, 2xx, 3xx are OK on client and server - // 4xx is OK on server - if (statusCode && statusCode >= 100 && statusCode < upperBound) { - return SpanStatusCode.UNSET - } - - // All other codes are error - return SpanStatusCode.ERROR -} - - -/** - * Adds attributes for request content-length and content-encoding HTTP headers - * @param { IncomingMessage } Request object whose headers will be analyzed - * @param { Attributes } Attributes object to be modified - */ -function setRequestContentLengthAttribute( - request: IncomingMessage, - attributes: Attributes, -): void { - - const length = getContentLength(request.headers) - if (length === null) { return } - - if (isCompressed(request.headers)) { - attributes['http.request_content_length'] = length - } - else { - attributes['http.request_content_length_uncompressed'] = length - } -} - -/** - * Adds attributes for response content-length and content-encoding HTTP headers - * @param { IncomingMessage } Response object whose headers will be analyzed - * @param { Attributes } SpanAttributes object to be modified - */ -export function setResponseContentLengthAttribute( - response: IncomingMessage, - attributes: Attributes, -): void { - - const length = getContentLength(response.headers) - if (length === null) { return } - - if (isCompressed(response.headers)) { - attributes['http.response_content_length'] = length - } - else { - attributes['http.response_content_length_uncompressed'] = length - } -} - -function getContentLength(headers: OutgoingHttpHeaders | IncomingHttpHeaders): number | null { - const contentLengthHeader = headers['content-length'] - if (contentLengthHeader === undefined) { return null } - - const contentLength = parseInt(contentLengthHeader as string, 10) - if (Number.isNaN(contentLength)) { return null } - - return contentLength -} - -function isCompressed(headers: OutgoingHttpHeaders | IncomingHttpHeaders): boolean { - const encoding = headers['content-encoding'] - - return !! encoding && encoding !== 'identity' -} - - -/** - * Returns attributes related to the kind of HTTP protocol used - * @param {string} [kind] Kind of HTTP protocol used: "1.0", "1.1", "2", "SPDY" or "QUIC". - */ -function getAttributesFromHttpKind(kind?: string): Attributes { - const attributes: Attributes = {} - if (kind) { - attributes['http.flavor'] = kind - if (kind.toUpperCase() === 'QUIC') { - attributes['net.transport'] = 'ip_udp' - } - else { - attributes['net.transport'] = 'ip_tcp' - } - } - return attributes -} - - -/** - * Returns incoming request attributes scoped to the request data - */ -export async function getIncomingRequestAttributesFromWebContext( - ctx: WebContext, - config: Config, -): Promise { - - const routerInfo = await getRouterInfo(ctx) - - const attrs: Attributes = { - ['http.host']: ctx.host, - ['http.method']: ctx.method || 'GET', - [ATTR_HTTP_ROUTE]: routerInfo?.fullUrl ?? 'unknown', - ['http.scheme']: ctx.protocol, - ['http.server_name']: config.serviceName ?? 'unknown', - ['http.target']: ctx.path || '/', - ['http.url']: ctx.href, - ['net.host.name']: ctx.hostname, - [AttrNames.ServiceName]: config.serviceName ?? 'unknown', - [AttrNames.ServiceVersion]: config.serviceVersion ?? 'unknown', - // [AttrNames.ServicePid]: process.pid, - } - - let httpKindAttributes = {} - - if (typeof ctx[AttrNames.traceId] === 'string') { - attrs[AttrNames.traceId] = ctx[AttrNames.traceId] - } - - const { req } = ctx - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (req) { - const userAgent = req.headers['user-agent'] - const ips = req.headers['x-forwarded-for'] - - if (typeof ips === 'string') { - attrs['http.client_ip'] = ips.split(',')[0] - } - - if (typeof userAgent !== 'undefined') { - attrs['http.user_agent'] = userAgent - } - - // Object.defineProperty(attrs, 'http.request.header.content_type', { - // enumerable: true, - // writable: false, - // value: headers['content-type'], - // }) - setRequestContentLengthAttribute(req, attrs) - - httpKindAttributes = getAttributesFromHttpKind(req.httpVersion) - } - - return Object.assign(attrs, httpKindAttributes) -} - - -/** - * Key format `http.{request|response}.header.{name}` - * @param headersKeyMap Map - */ -export function genAttributesFromHeader( - type: 'request' | 'response', - headersKeyMap: Map, - getHeader: (key: string) => string | number | undefined | string[], -): Attributes | undefined { - - const attrs: Attributes = {} - - for (const [lower, normalized] of headersKeyMap) { - const data = getHeader(lower) - if (typeof data === 'undefined' || data === '') { continue } - - const value = Array.isArray(data) ? data : data - const key = `http.${type}.header.${normalized}` - Object.defineProperty(attrs, key, { - enumerable: true, - writable: false, - value, - }) - } - - if (Object.keys(attrs).length) { - return attrs - } - return -} - -/** - * Returns map - */ -export type NormalizedKeyMap = Map - -export function normalizeHeaderKey(inputKeys: string[]): NormalizedKeyMap { - const keys: [string, string][] = inputKeys.map((header) => { - const str = header.toLowerCase() - return [str, str.replace(/-/ug, '_')] - }) - - const ret = new Map(keys) - return ret -} - - -export function propagateOutgoingHeader( - traceContext: TraceContext, - message: OutgoingMessage, -): void { - - const headers = {} - propagation.inject(traceContext, headers) - - Object.entries(headers).forEach(([key, val]) => { - if (typeof val === 'string' || typeof val === 'number' || Array.isArray(val)) { - message.setHeader(key, val) - } - }) -} - -/** - * Skip if header already exists - */ -export function propagateHeader( - traceContext: TraceContext, - headers: T, -): void { - - const tmp = {} - propagation.inject(traceContext, tmp) - - Object.entries(tmp).forEach(([key, val]) => { - const curr = headers.get(key) - if (typeof curr !== 'undefined' && curr !== null) { return } - - if (typeof val === 'string' || typeof val === 'number') { - headers.set(key, val.toString()) - } - else if (Array.isArray(val)) { - headers.set(key, val.join(',')) - } - }) -} - -/** - * - * @param headersKey if omit then use inner prepared headers key - */ -export function setSpanWithRequestHeaders( - span: Span, - requestHeadersMap: Map | undefined, - getHeader: (key: string) => string | number | undefined | string[], - headersKey?: string[], -): void { - - const keyMap = headersKey - ? normalizeHeaderKey(headersKey) - : requestHeadersMap - - if (! keyMap?.size) { return } - - const attrs = genAttributesFromHeader('request', keyMap, getHeader) - if (attrs) { - span.setAttributes(attrs) - } -} - -interface AddSpanEventWithIncomingRequestDataOptions { - headers?: Headers | OutgoingHttpHeaders | UndiciHeaders - query?: object - /** request data */ - requestBody: unknown - span: Span -} -/** - * String of JSON.stringify limited to 2048 characters - */ -export function addSpanEventWithIncomingRequestData(options: AddSpanEventWithIncomingRequestDataOptions): void { - const { span, requestBody: data, headers, query } = options - - const attrs: Attributes = {} - - if (query) { - if (typeof query === 'object' && Object.keys(query).length) { - let value = 'object could not be stringified to JSON' - try { - value = truncateString(JSON.stringify(query, null, 2)) - } - catch (err) { - void err - } - Object.defineProperty(attrs, AttrNames.Http_Request_Query, { - ...defaultProperty, - value, - }) - } - } - - if (data && Object.keys(data).length) { - let value = 'object could not be stringified to JSON' - try { - value = truncateString(JSON.stringify(data, null, 2)) - } - catch (err) { - void err - } - Object.defineProperty(attrs, AttrNames.Http_Request_Body, { - ...defaultProperty, - value, - }) - } - - if (headers && typeof headers.get === 'function') { - Object.defineProperty(attrs, 'http.request.header.content_length', { - ...defaultProperty, - value: headers.get('content-length'), - }) - Object.defineProperty(attrs, 'http.request.header.content_type', { - ...defaultProperty, - value: headers.get('content-type'), - }) - } - - if (Object.keys(attrs).length) { - span.addEvent(AttrNames.Incoming_Request_data, attrs) - } -} - -export interface AddSpanEventWithOutgoingResponseDataOptions { - /** return data */ - body: unknown - headers?: Headers | OutgoingHttpHeaders | UndiciHeaders - span: Span - /** response status code */ - status: number -} -/** - * String of JSON.stringify limited to 2048 characters - */ -export function addSpanEventWithOutgoingResponseData(options: AddSpanEventWithOutgoingResponseDataOptions): void { - const { span, body, headers, status } = options - - const attrs: Attributes = {} - - let value = '' - if (typeof body === 'object') { - try { - value = truncateString(JSON.stringify(body, null, 2)) - } - catch { - value = 'object could not be stringified to JSON' - } - } - else if (typeof body === 'string') { - value = body ? truncateString(body) : '' - } - // else { - // value = body ? truncateString(body.toString()) : '' - // } - Object.defineProperty(attrs, AttrNames.Http_Response_Body, { - ...defaultProperty, - value, - }) - - Object.defineProperty(attrs, AttrNames.Http_Response_Code, { - ...defaultProperty, - value: status, - }) - - if (headers && typeof headers.get === 'function') { - Object.defineProperty(attrs, 'http.response.header.content_length', { - ...defaultProperty, - value: headers.get('content-length'), - }) - Object.defineProperty(attrs, 'http.response.header.content_type', { - ...defaultProperty, - value: headers.get('content-type'), - }) - } - - if (Object.keys(attrs).length) { - span.addEvent(AttrNames.Outgoing_Response_data, attrs) - } -} - -export function truncateString(str: string, maxLength = 2048): string { - if (str && str.length > maxLength) { - return str.slice(0, maxLength) + '... LENGTH: ' + str.length.toString() + ' bytes' - } - return str -} - -export interface GenRequestSpanNameOptions { - /** ctx.request?.protocol */ - protocol: string - /** ctx.method */ - method: string - route: string -} - -/** - * Generate span name from request - * @example - * - 'HTTP GET /api/v1/user' - * - 'RPC /helloworld.Greeter/SayHello' - */ -export function genRequestSpanName(options: GenRequestSpanNameOptions, maxLength = 128): string { - const { protocol, method, route } = options - assert(protocol, 'protocol is required') - assert(method, 'method is required') - - if (protocol === 'grpc') { - const spanName = `RPC ${route}` - return spanName.slice(0, maxLength) - } - const spanName = `${protocol.toLocaleUpperCase()} ${method.toUpperCase()} ${route}` - return spanName.slice(0, maxLength) -} - diff --git a/packages/otel/src/middleware/grpc/helper.middleware.grpc.ts b/packages/otel/src/middleware/grpc/helper.middleware.grpc.ts deleted file mode 100644 index 9833a2cf9..000000000 --- a/packages/otel/src/middleware/grpc/helper.middleware.grpc.ts +++ /dev/null @@ -1,129 +0,0 @@ -import type { Metadata } from '@midwayjs/grpc' -import type { Context as Context, GrpcContext, NextFunction } from '@mwcp/share' -import { RpcMethodType } from '@mwcp/share' -import type { Attributes, TextMapGetter, TextMapSetter } from '@opentelemetry/api' -import { genError, genISO8601String } from '@waiting/shared-core' - -import type { TraceService } from '##/lib/index.js' -import { AttrNames } from '##/lib/types.js' - -import { GrpcStatusCode } from './status.grpc.js' - - -/** - * Catch and sample top exception if __isTraced is false or undefined, - * ex will NOT be thrown again - */ -export async function handleTopExceptionAndNext( - ctx: GrpcContext, - traceSvc: TraceService, - next: NextFunction, -): Promise { - - try { - const res = await next() as object - if (typeof ctx.status === 'undefined') { // for gRPC - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (res) { - ctx.status = 200 - } - else { - ctx.status = 500 - } - } - return res - } - catch (error) { - const err = genError({ error }) - traceSvc.setRootSpanWithError(err, void 0, ctx) - /* c8 ignore next 3 */ - if (typeof ctx.status === 'undefined') { - ctx.status = 500 - } - else if (ctx.status >= 200 && ctx.status < 300) { - ctx.status = 500 - } - - ctx.pendingStatus.details = ctx.pendingStatus.details && ctx.pendingStatus.details !== 'OK' - ? `${ctx.pendingStatus.details}\n${err.message}` - : err.message - - if (ctx.pendingStatus.code === 0) { - ctx.pendingStatus.code = GrpcStatusCode.INTERNAL - } - - return err - } -} - - -/** - * Catch and sample exception, - * re-throw ex - */ -export async function handleAppExceptionAndNext( - webCtx: Context, - traceSvc: TraceService, - next: NextFunction, -): Promise { - - try { - const res = await next() as unknown - - const rootSpan = traceSvc.getRootSpan(webCtx) - if (rootSpan) { - const events: Attributes = { - event: AttrNames.PostProcessBegin, - time: genISO8601String(), - } - traceSvc.addEvent(rootSpan, events) - } - return res - } - catch (error) { - const err = genError({ error }) - const currSpan = traceSvc.getActiveSpan() - if (currSpan) { - traceSvc.setSpanWithError(currSpan, err, void 0, webCtx) - } - else { - traceSvc.setRootSpanWithError(err, void 0, webCtx) - } - throw err - } -} - - -export const metadataSetter: TextMapSetter> = { - set(carrier, key, value) { - carrier.set(key, value) - }, -} -export const metadataGetter: TextMapGetter = { - get: (carrier, key) => { - return carrier.get(key) as string | string[] | undefined - }, - keys: (carrier) => { - // @ts-expect-error internalRepr - const data = carrier.internalRepr - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (data) { - return Array.from(data, ([key]) => key) - } - return [] - }, -} - - -export function detectRpcMethodType(ctx: GrpcContext): RpcMethodType.unary | RpcMethodType.bidi { - if (ctx['readable']) { - return RpcMethodType.bidi - } - return RpcMethodType.unary -} - - -export function isGrpcContextFinished(ctx: GrpcContext): boolean { - // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing - return !! (ctx['closed'] || ctx['cancelled'] || ctx['errored'] || ctx['destroyed']) -} diff --git a/packages/otel/src/middleware/grpc/index.middleware.grpc.ts b/packages/otel/src/middleware/grpc/index.middleware.grpc.ts deleted file mode 100644 index 4bf46ad8d..000000000 --- a/packages/otel/src/middleware/grpc/index.middleware.grpc.ts +++ /dev/null @@ -1,5 +0,0 @@ - -export * from './trace-inner.middleware.grpc.js' -export * from './trace-outer.middleware.grpc.js' -export * from './status.grpc.js' - diff --git a/packages/otel/src/middleware/grpc/status.grpc.ts b/packages/otel/src/middleware/grpc/status.grpc.ts deleted file mode 100644 index 8bd16cfa5..000000000 --- a/packages/otel/src/middleware/grpc/status.grpc.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * gRPC status code. - * - * See https://grpc.github.io/grpc/core/md_doc_statuscodes.html. - */ -export enum GrpcStatusCode { - /** - * Not an error; returned on success. - */ - OK = 0, - /** - * The operation was cancelled, typically by the caller. - */ - CANCELLED = 1, - /** - * Unknown error. - * - * For example, this error may be returned when a `Status` value received from - * another address space belongs to an error space that is not known in this - * address space. - * - * Also errors raised by APIs that do not return enough error information may - * be converted to this error. - */ - UNKNOWN = 2, - /** - * The client specified an invalid argument. - * - * Note that this differs from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` - * indicates arguments that are problematic regardless of the state of the - * system (e.g., a malformed file name). - */ - INVALID_ARGUMENT = 3, - /** - * The deadline expired before the operation could complete. - * - * For operations that change the state of the system, this error may be - * returned even if the operation has completed successfully. - * - * For example, a successful response from a server could have been delayed - * long enough for the deadline to expire. - */ - DEADLINE_EXCEEDED = 4, - /** - * Some requested entity (e.g., file or directory) was not found. - * - * Note to server developers: if a request is denied for an entire class of - * users, such as gradual feature rollout or undocumented allowlist, - * `NOT_FOUND` may be used. If a request is denied for some users within a - * class of users, such as user-based access control, `PERMISSION_DENIED` must - * be used. - */ - NOT_FOUND = 5, - /** - * The entity that a client attempted to create (e.g., file or directory) - * already exists. - */ - ALREADY_EXISTS = 6, - /** - * The caller does not have permission to execute the specified operation. - * - * `PERMISSION_DENIED` must not be used for rejections caused by exhausting - * some resource (use `RESOURCE_EXHAUSTED` instead for those errors). - * `PERMISSION_DENIED` must not be used if the caller can not be identified - * (use `UNAUTHENTICATED` instead for those errors). - * - * This error code does not imply the request is valid or the requested entity - * exists or satisfies other pre-conditions. - */ - PERMISSION_DENIED = 7, - /** - * Some resource has been exhausted, perhaps a per-user quota, or perhaps the - * entire file system is out of space. - */ - RESOURCE_EXHAUSTED = 8, - /** - * The operation was rejected because the system is not in a state required - * for the operation's execution. - * - * For example, the directory to be deleted is non-empty, an rmdir operation - * is applied to a non-directory, etc. - * - * Service implementors can use the following guidelines to decide between - * `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: - * - * (a) Use `UNAVAILABLE` if the client can retry just the failing call. - * (b) Use `ABORTED` if the client should retry at a higher level (e.g., - * when a client-specified test-and-set fails, indicating the client - * should restart a read-modify-write sequence). - * (c) Use `FAILED_PRECONDITION` if the client should not retry until the - * system state has been explicitly fixed. E.g., if an "rmdir" fails - * because the directory is non-empty, `FAILED_PRECONDITION` should be - * returned since the client should not retry unless the files are - * deleted from the directory. - */ - FAILED_PRECONDITION = 9, - /** - * The operation was aborted, typically due to a concurrency issue such as a - * sequencer check failure or transaction abort. - * - * See the guidelines above for deciding between `FAILED_PRECONDITION`, - * `ABORTED`, and `UNAVAILABLE`. - */ - ABORTED = 10, - /** - * The operation was attempted past the valid range. - * - * E.g., seeking or reading past end-of-file. - * - * Unlike `INVALID_ARGUMENT`, this error indicates a problem that may be fixed - * if the system state changes. For example, a 32-bit file system will - * generate `INVALID_ARGUMENT` if asked to read at an offset that is not in - * the range [0,2^32-1], but it will generate `OUT_OF_RANGE` if asked to read - * from an offset past the current file size. - * - * There is a fair bit of overlap between `FAILED_PRECONDITION` and - * `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific error) - * when it applies so that callers who are iterating through a space can - * easily look for an `OUT_OF_RANGE` error to detect when they are done. - */ - OUT_OF_RANGE = 11, - /** - * The operation is not implemented or is not supported/enabled in this - * service. - */ - UNIMPLEMENTED = 12, - /** - * Internal errors. - * - * This means that some invariants expected by the underlying system have been - * broken. This error code is reserved for serious errors. - */ - INTERNAL = 13, - /** - * The service is currently unavailable. - * - * This is most likely a transient condition, which can be corrected by - * retrying with a backoff. - * - * Note that it is not always safe to retry non-idempotent operations. - */ - UNAVAILABLE = 14, - /** - * Unrecoverable data loss or corruption. - */ - DATA_LOSS = 15, - /** - * The request does not have valid authentication credentials for the - * operation. - */ - UNAUTHENTICATED = 16, -} diff --git a/packages/otel/src/middleware/grpc/trace-inner.middleware.grpc.ts b/packages/otel/src/middleware/grpc/trace-inner.middleware.grpc.ts deleted file mode 100644 index 7fa4b1c52..000000000 --- a/packages/otel/src/middleware/grpc/trace-inner.middleware.grpc.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { Middleware } from '@midwayjs/core' -import { type GrpcContext, Context, IMiddleware, NextFunction } from '@mwcp/share' - -import { TraceService } from '##/lib/index.js' -import { AttrNames, ConfigKey, middlewareEnableCacheKey } from '##/lib/types.js' -import { addSpanEventWithIncomingRequestData } from '##/lib/util.js' - -import { handleAppExceptionAndNext } from './helper.middleware.grpc.js' - - -@Middleware() -export class TraceMiddlewareInnerGRpc implements IMiddleware { - - static getName(): string { - const name = ConfigKey.middlewareNameInner + 'GRpc' - return name - } - - match(ctx: Context) { - return ctx.getAttr(middlewareEnableCacheKey) === 'true' - } - - resolve() { - return middleware - } - -} - -/** - * 链路追踪中间件 - * - 对不在白名单内的路由进行追踪 - * - 对异常链路进行上报 - */ -async function middleware( - ctx: Context, - next: NextFunction, -): Promise { - - const container = ctx.app.getApplicationContext() - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - const traceSvc = container.get(TraceService) ?? await container.getAsync(TraceService) - - const ctx2 = ctx as unknown as GrpcContext - const rootSpan = traceSvc.getRootSpan(ctx2) - if (rootSpan) { - addSpanEventWithIncomingRequestData({ - requestBody: ctx2.request, - span: rootSpan, - }) - traceSvc.addEvent(rootSpan, { - event: AttrNames.PreProcessFinish, - }) - } - - return handleAppExceptionAndNext(ctx, traceSvc, next) -} - diff --git a/packages/otel/src/middleware/grpc/trace-outer.middleware.grpc.ts b/packages/otel/src/middleware/grpc/trace-outer.middleware.grpc.ts deleted file mode 100644 index e72852690..000000000 --- a/packages/otel/src/middleware/grpc/trace-outer.middleware.grpc.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { Middleware } from '@midwayjs/core' -import { type Context, type GrpcContext, IMiddleware, NextFunction, RpcMethodType } from '@mwcp/share' -import { SpanKind, SpanStatus, context, propagation } from '@opentelemetry/api' - -import type { Span } from '##/index.js' -import { TraceService } from '##/lib/index.js' -import { Config, ConfigKey, middlewareEnableCacheKey } from '##/lib/types.js' -import { - addSpanEventWithOutgoingResponseData, - getSpan, - parseResponseStatus, -} from '##/lib/util.js' - -import { detectRpcMethodType, handleTopExceptionAndNext, isGrpcContextFinished, metadataGetter } from './helper.middleware.grpc.js' - - -@Middleware() -export class TraceMiddlewareGRpc implements IMiddleware { - - static getName(): string { - const name = ConfigKey.middlewareName + 'GRpc' - return name - } - - match(ctx: Context) { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (! ctx.app) { // false when ctx is a grpc instance - ctx.app = ctx.getApp() as unknown as Context['app'] - } - - const config = ctx.app.getConfig(ConfigKey.config) as Config - if (! config.enable) { - return false - } - // check config.enable only, ignore middleware.enable - ctx.setAttr(middlewareEnableCacheKey, 'true') - return true - } - - resolve() { - return middleware - } - -} - -/** - * 链路追踪中间件 - * - 对不在白名单内的路由进行追踪 - * - 对异常链路进行上报 - */ -async function middleware( - ctx: Context, - next: NextFunction, -): Promise { - - const container = ctx.app.getApplicationContext() - - const ctx2 = ctx as unknown as GrpcContext - const rpcMethodType = detectRpcMethodType(ctx2) - if (rpcMethodType !== RpcMethodType.unary) { - return next() - } - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - const traceSvc = container.get(TraceService) ?? await container.getAsync(TraceService) - const rootContext = await traceSvc.startOnRequest(ctx) - if (! rootContext) { - return next() - } - - const { metadata } = ctx2 - if (metadata) { - propagation.extract(rootContext, metadata, metadataGetter) - } - - const rootSpan = getSpan(rootContext) - if (! rootSpan) { - return next() - } - - ctx.setAttr('rootTraceContext', rootContext) - ctx.setAttr('rootSpan', rootSpan) - - const res = await context.with(rootContext, async () => { - return handleTopExceptionAndNext(ctx2, traceSvc, next) - }) - addSpanEventWithOutgoingResponseData({ - body: res, - span: rootSpan, - status: ctx.status, - }) - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (rpcMethodType === RpcMethodType.unary) { - if (isGrpcContextFinished(ctx2)) { // unary - finishCallback(ctx2, traceSvc) - return - } - - setImmediate(() => { - if (isGrpcContextFinished(ctx2)) { // unary - finishCallback(ctx2, traceSvc) - return - } - }) - } - - if (res instanceof Error) { - throw res - } - else { - return res - } -} - - -function finishCallback(ctx: GrpcContext, traceSvc: TraceService): void { - const rootSpan = ctx.getAttr('rootSpan') - if (! rootSpan?.isRecording()) { return } - const code = parseResponseStatus(SpanKind.CLIENT, ctx.status) - const spanStatus: SpanStatus = { code } - traceSvc.finish(ctx, spanStatus) -} - diff --git a/packages/otel/src/middleware/http/helper.middleware.http.ts b/packages/otel/src/middleware/http/helper.middleware.http.ts deleted file mode 100644 index a73ef903e..000000000 --- a/packages/otel/src/middleware/http/helper.middleware.http.ts +++ /dev/null @@ -1,87 +0,0 @@ -import type { Context as Context, NextFunction } from '@mwcp/share' -import { type Attributes } from '@opentelemetry/api' -import { genError, genISO8601String } from '@waiting/shared-core' - -import type { TraceService } from '##/lib/index.js' -import { AttrNames } from '##/lib/types.js' - - -/** - * Catch and sample top exception if __isTraced is false or undefined, - * ex will NOT be thrown again - */ -export async function handleTopExceptionAndNext( - ctx: Context, - traceSvc: TraceService, - next: NextFunction, -): Promise { - - try { - const res = await next() as unknown - if (typeof ctx.status === 'undefined' && res) { // for gRPC - ctx.status = 200 - } - return res - } - catch (error) { - const err = genError({ error }) - traceSvc.setRootSpanWithError(err, void 0, ctx) - /* c8 ignore next 3 */ - if (typeof ctx.status === 'undefined') { - ctx.status = 500 - } - else if (ctx.status >= 200 && ctx.status < 300) { - ctx.status = 500 - } - - if (typeof ctx.body === 'undefined') { - if (ctx.status === 404) { - ctx.status = 500 - } - - if (err.message) { - ctx.body = err.message - } - } - - return void 0 - } -} - - -/** - * Catch and sample exception, - * re-throw ex - */ -export async function handleAppExceptionAndNext( - webCtx: Context, - traceSvc: TraceService, - next: NextFunction, -): Promise { - - try { - await next() - - const rootSpan = traceSvc.getRootSpan(webCtx) - if (rootSpan) { - const events: Attributes = { - event: AttrNames.PostProcessBegin, - time: genISO8601String(), - } - traceSvc.addEvent(rootSpan, events) - } - } - catch (error) { - const err = genError({ error }) - const currSpan = traceSvc.getActiveSpan() - if (currSpan) { - traceSvc.setSpanWithError(currSpan, err, void 0, webCtx) - } - else { - traceSvc.setRootSpanWithError(err, void 0, webCtx) - } - throw err - } -} - - diff --git a/packages/otel/src/middleware/http/index.middleware.http.ts b/packages/otel/src/middleware/http/index.middleware.http.ts deleted file mode 100644 index 6ce5fc7ad..000000000 --- a/packages/otel/src/middleware/http/index.middleware.http.ts +++ /dev/null @@ -1,4 +0,0 @@ - -export * from './trace-inner.middleware.http.js' -export * from './trace-outer.middleware.http.js' - diff --git a/packages/otel/src/middleware/http/trace-inner.middleware.http.ts b/packages/otel/src/middleware/http/trace-inner.middleware.http.ts deleted file mode 100644 index 15567d460..000000000 --- a/packages/otel/src/middleware/http/trace-inner.middleware.http.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { Middleware } from '@midwayjs/core' -import { Context, IMiddleware, NextFunction } from '@mwcp/share' - -import { TraceService } from '##/lib/index.js' -import { AttrNames, ConfigKey, middlewareEnableCacheKey } from '##/lib/types.js' -import { addSpanEventWithIncomingRequestData } from '##/lib/util.js' - -import { handleAppExceptionAndNext } from './helper.middleware.http.js' - - -@Middleware() -export class TraceMiddlewareInner implements IMiddleware { - - static getName(): string { - const name = ConfigKey.middlewareNameInner - return name - } - - match(ctx: Context) { - return ctx.getAttr(middlewareEnableCacheKey) === 'true' - } - - resolve() { - return middleware - } - -} - -/** - * 链路追踪中间件 - * - 对不在白名单内的路由进行追踪 - * - 对异常链路进行上报 - */ -async function middleware( - ctx: Context, - next: NextFunction, -): Promise { - - const container = ctx.app.getApplicationContext() - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - const traceSvc = container.get(TraceService) ?? await container.getAsync(TraceService) - const rootSpan = traceSvc.getRootSpan(ctx) - if (rootSpan) { - addSpanEventWithIncomingRequestData({ - headers: ctx.headers, - query: ctx.query, - requestBody: ctx.request.body, - span: rootSpan, - }) - traceSvc.addEvent(rootSpan, { - event: AttrNames.PreProcessFinish, - // [AttrNames.ServiceMemoryUsage]: JSON.stringify(humanMemoryUsage(), null, 2), - }) - } - - return handleAppExceptionAndNext(ctx, traceSvc, next) -} - diff --git a/packages/otel/src/middleware/http/trace-outer.middleware.http.ts b/packages/otel/src/middleware/http/trace-outer.middleware.http.ts deleted file mode 100644 index ebf11aa80..000000000 --- a/packages/otel/src/middleware/http/trace-outer.middleware.http.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { Middleware } from '@midwayjs/core' -import { Context, IMiddleware, NextFunction } from '@mwcp/share' -import { type Span, SpanKind, SpanStatus, context } from '@opentelemetry/api' - -import { TraceService } from '##/lib/index.js' -import { Config, ConfigKey, middlewareEnableCacheKey } from '##/lib/types.js' -import { - addSpanEventWithOutgoingResponseData, - getSpan, - parseResponseStatus, - propagateOutgoingHeader, -} from '##/lib/util.js' - -import { handleTopExceptionAndNext } from './helper.middleware.http.js' - - -@Middleware() -export class TraceMiddleware implements IMiddleware { - - static getName(): string { - const name = ConfigKey.middlewareName - return name - } - - match(ctx: Context) { - const config = ctx.app.getConfig(ConfigKey.config) as Config - if (! config.enable) { - return false - } - // check config.enable only, ignore middleware.enable - // const mwConfig = ctx.app.getConfig(ConfigKey.middlewareConfig) as MiddlewareConfig - // if (! mwConfig.enableMiddleware) { - // return false - // } - - // const flag = shouldEnableMiddleware(ctx, mwConfig) - ctx.setAttr(middlewareEnableCacheKey, 'true') - return true - } - - resolve() { - return middleware - } - -} - -/** - * 链路追踪中间件 - * - 对不在白名单内的路由进行追踪 - * - 对异常链路进行上报 - */ -export async function middleware( - ctx: Context, - next: NextFunction, -): Promise { - - const container = ctx.app.getApplicationContext() - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - const traceSvc = container.get(TraceService) ?? await container.getAsync(TraceService) - const rootContext = await traceSvc.startOnRequest(ctx) - if (! rootContext) { - await next() - return - } - ctx.setAttr('rootTraceContext', rootContext) - - ctx.res.once('finish', () => { finishCallback(ctx, traceSvc) }) - - await context.with(rootContext, async () => { - await handleTopExceptionAndNext(ctx, traceSvc, next) - }) - - propagateOutgoingHeader(rootContext, ctx.res) - - const rootSpan = getSpan(rootContext) - if (rootSpan) { - ctx.setAttr('rootSpan', rootSpan) - addSpanEventWithOutgoingResponseData({ - body: ctx.body, - headers: ctx.response.headers, - span: rootSpan, - status: ctx.status, - }) - } -} - - -function finishCallback(ctx: Context, traceSvc: TraceService): void { - const rootSpan = ctx.getAttr('rootSpan') - if (! rootSpan?.isRecording()) { return } - const code = parseResponseStatus(SpanKind.CLIENT, ctx.status) - const spanStatus: SpanStatus = { code } - traceSvc.finish(ctx, spanStatus) -} - diff --git a/packages/otel/src/middleware/index.middleware.ts b/packages/otel/src/middleware/index.middleware.ts deleted file mode 100644 index d65250432..000000000 --- a/packages/otel/src/middleware/index.middleware.ts +++ /dev/null @@ -1,4 +0,0 @@ - -export * from './grpc/index.middleware.grpc.js' -export * from './http/index.middleware.http.js' - diff --git a/packages/otel/src/util/common.ts b/packages/otel/src/util/common.ts deleted file mode 100644 index 576391fc4..000000000 --- a/packages/otel/src/util/common.ts +++ /dev/null @@ -1,415 +0,0 @@ - -import assert from 'node:assert' - -import { makeHttpRequest } from '@midwayjs/core' -import type { AttributeValue } from '@opentelemetry/api' -import { - SEMATTRS_HTTP_METHOD, - SEMATTRS_HTTP_SCHEME, - SEMATTRS_HTTP_SERVER_NAME, - SEMATTRS_NET_HOST_NAME, -} from '@opentelemetry/semantic-conventions' -import { sleep } from '@waiting/shared-core' -import type { Headers as UndiciHeaders } from 'undici' - -import { AttrNames } from '##/lib/attrnames.types.js' -import { exporterEndpoint } from '##/lib/config.js' -import type { Attributes, JaegerTraceInfo, JaegerTraceInfoLogField, JaegerTraceInfoSpan } from '##/lib/index.js' - - -// #region retrieveTraceInfoFromRemote - -const agent = exporterEndpoint.replace(/:\d+$/u, '') - -export async function retrieveTraceInfoFromRemote(traceId: string, expectSpanNumber?: number): Promise<[JaegerTraceInfo]> { - assert(agent, 'OTEL_EXPORTER_OTLP_ENDPOINT not set') - - let id = traceId - if (traceId.includes('-')) { - const txt = traceId.split('-').at(1) - assert(txt) - id = txt - } - - await sleep(1000) - // console.log('retrieveTraceInfoFromRemote: ', { traceId }) - const tracePath = `${agent}:16686/api/traces/${id}?prettyPrint=true` - let resp = await makeHttpRequest(tracePath, { - method: 'GET', - dataType: 'json', - }) - /* c8 ignore next 4 */ - .catch((err) => { - console.error(`retrieve trace info failed, check agent "${agent}" valid or OTEL_EXPORTER_OTLP_ENDPOINT is correct.`) - throw err - }) - - for (let i = 0; i < 30; i += 1) { - assert(resp.status !== 401, `Expect not 401, trace: "${tracePath}"`) - assert(resp.status !== 404, `Expect not 404, trace: "${tracePath}"`) - assert(resp.status !== 500, `Expect not 500, trace: "${tracePath}"`) - - if (resp.status === 200 && resp.data) { break } - /* c8 ignore start */ - const { data } = resp.data as { data: [JaegerTraceInfo] } - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (data.length > 0) { break } - - // console.log('retry traceId...') - await sleep(2000) - resp = await makeHttpRequest(tracePath, { - method: 'GET', - dataType: 'json', - }) - /* c8 ignore stop */ - } - - const { data } = resp.data as { data: [JaegerTraceInfo] } - - /* c8 ignore next 3 */ - if (! expectSpanNumber) { - return data - } - - let { spans } = data[0] - if (spans.length >= expectSpanNumber) { - return data - } - - - /* c8 ignore start */ - for (let i = 0; i < 30; i += 1) { - // console.info('retry span... idx:', i) - await sleep(2000) - const resp2 = await retrieveTraceInfoFromRemote(traceId) - spans = resp2[0].spans - // console.log('spans.length:', spans.length) - if (spans.length >= expectSpanNumber) { - return resp2 - } - } - assert(false, `spans.length: ${spans.length}, expectSpanNumber: ${expectSpanNumber}`) - /* c8 ignore stop */ -} - -// #region sortSpans - -// 对于 JaegerTraceInfo.spans 入参,对于 JaegerTraceInfo.spans 根据 span.reference 的 spanID 依赖关系进行排序 -// 以确保 root span -> span0 -> span1 -> span2 的顺序 -export function sortSpans(spans: JaegerTraceInfoSpan[]): JaegerTraceInfoSpan[] { - assert(spans.length > 0, 'sortSpans() spans.length === 0') - const map = new Map() - - spans.forEach((span) => { - map.set(span.spanID, span) - }) - - const ret: JaegerTraceInfoSpan[] = [] - - // find root - // spans.forEach((span) => { - for (const span of spans) { - const parentSpan = getParentSpan(span, map) - if (! parentSpan) { // root span - ret.push(span) - break - } - } - - const parentSpan = ret.at(-1) - assert(parentSpan) - mergeSpans(parentSpan, spans, ret) - - return ret -} - -function mergeSpans(parentSpan: JaegerTraceInfoSpan, srcSpans: JaegerTraceInfoSpan[], result: JaegerTraceInfoSpan[]): void { - assert(parentSpan) - const pid = parentSpan.spanID - const childSpans = getChildren(pid, srcSpans) - - if (childSpans.length) { // has child node - if (parentSpan !== result.at(-1)) { - result.push(parentSpan) - } - - childSpans.forEach((child) => { // not leaf node - mergeSpans(child, srcSpans, result) - }) - } - else if (parentSpan !== result.at(-1)) { // leaf node - result.push(parentSpan) - } -} - -function getParentSpan( - span: JaegerTraceInfo['spans'][0], - map: Map, -): JaegerTraceInfoSpan | undefined { - - if (! span.references.length) { return } - - const ref = span.references[0] - /* c8 ignore next */ - if (! ref) { return } - - return map.get(ref.spanID) -} - -function getChildren( - parentSpanId: string, - spans: JaegerTraceInfo['spans'], -): JaegerTraceInfoSpan[] { - - const ret: JaegerTraceInfoSpan[] = [] - - assert(parentSpanId) - spans.forEach((span) => { - const ref = span.references[0] - if (ref && ref.spanID === parentSpanId) { - ret.push(span) - } - }) - - if (ret.length > 1) { - sortSpansByStartTime(ret) - } - return ret -} - -function sortSpansByStartTime(spans: JaegerTraceInfoSpan[]): JaegerTraceInfoSpan[] { - return spans.sort((p1, p2) => { - return p1.startTime - p2.startTime - }) -} - -// #region assertRootSpan - -type ExpectAttributes = Record - -export interface AssertsRootOptions { - /** - * @default 'http' - */ - scheme?: 'http' | 'grpc' - path: string - span: JaegerTraceInfoSpan - traceId: string - - operationName?: string - tags?: ExpectAttributes - logs?: (ExpectAttributes | false)[] - /** - * @default true - */ - mergeDefaultTags?: boolean - /** - * @default true - */ - mergeDefaultLogs?: boolean -} - -export function assertRootSpan(options: AssertsRootOptions): void { - const { path, span, tags } = options - const scheme = options.scheme ?? 'http' - const operationName = options.operationName ?? `HTTP GET ${path}` - const httpMethod = scheme === 'http' - ? operationName.includes('GET') ? 'GET' : 'POST' - : 'RPC' - const expectLogs = options.logs ?? [] - - const mergeDefaultTags = options.mergeDefaultTags ?? true - const mergeDefaultLogs = options.mergeDefaultLogs ?? true - - const tags2 = mergeDefaultTags - ? Object.assign({ - [SEMATTRS_HTTP_METHOD]: httpMethod, - [SEMATTRS_HTTP_SCHEME]: scheme, - [SEMATTRS_HTTP_SERVER_NAME]: 'base-app', - [SEMATTRS_NET_HOST_NAME]: '127.0.0.1', - [AttrNames.ServiceName]: 'base-app', - [AttrNames.ServiceVersion]: '1.0.0', - 'span.kind': 'server', - }, tags) - : Object.assign({}, tags) - - const logBase = [ - { event: AttrNames.RequestBegin }, - { event: AttrNames.Incoming_Request_data }, - { event: AttrNames.PreProcessFinish }, - { event: AttrNames.PostProcessBegin }, - { event: AttrNames.Outgoing_Response_data, [AttrNames.Http_Response_Code]: 200 }, - { event: AttrNames.RequestEnd }, - ] - - const logs: ExpectAttributes[] = [] - - if (mergeDefaultLogs) { - for (let idx = 0; idx < Math.max(logBase.length, expectLogs.length, options.logs?.length ?? 0); idx += 1) { - const log = logBase[idx] ?? {} - const expectRow = expectLogs[idx] - if (expectRow === false) { continue } - if (expectRow && Object.keys(expectRow).length) { - const row = Object.assign(log, expectRow) - logs.push(row) - continue - } - logs.push(log) - } - } - else { - options.logs?.forEach((log) => { - if (log) { - logs.push(log) - } - }) - } - - const opt: AssertsOptions = { - traceId: options.traceId, - operationName, - tags: tags2, - logs, - } - - assertsSpan(span, opt) -} - -export interface AssertsOptions { - traceId: string - operationName: string - tags?: ExpectAttributes - logs?: ExpectAttributes[] -} - -export function assertsSpan(span: JaegerTraceInfoSpan, options: AssertsOptions): void { - assert(span, 'span is null') - assert(options, 'options is null') - - assert(span.traceID === options.traceId) - assert(span.operationName === options.operationName, `operationName: ${span.operationName} !== (expect) ${options.operationName}`) - - Object.entries(options.tags ?? {}).forEach(([key, expectValue]) => { - const flag = span.tags.some((tag) => { - if (tag['key'] !== key) { - return false - } - assertJaegerTagItem(tag, key, expectValue) - return true - }) - assert(flag, `${key}: ${expectValue.toString()} not found`) - }) - - - if (options.logs?.length) { - options.logs.forEach((expectLog, idx) => { - /* c8 ignore next 2 */ - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (! expectLog) { return } - const log = span.logs[idx] - assert(log, `log[${idx}] is null`) - - Object.entries(expectLog).forEach(([key, expectValue]) => { - const flag = log.fields.some((field) => { - if (field.key !== key) { - return false - } - - assertJaegerLogField(field, key, expectValue) - return true - }) - assert(flag, `(${idx}) ${key}: ${expectValue.toString()} not found`) - }) - }) - } -} - -export function assertJaegerTagItem(tag: Attributes, key: string, expectValue: AttributeValue | RegExp): void { - const tagVal = tag['value'] - assert(typeof tagVal !== 'undefined', `${key}: tagVal from span is null`) - - if (expectValue instanceof RegExp) { - assert(expectValue.test(tagVal.toString()), `${key}: ${tagVal.toString()} !== (expect) ${expectValue.toString()}`) - } - else { - const res = tagVal === expectValue - assert(res, `${key}: ${tagVal.toString()} !== (expect) ${expectValue.toString()}`) - } -} - -export function assertJaegerLogField(field: JaegerTraceInfoLogField, key: string, expectValue: AttributeValue | RegExp): void { - const fieldVal = field.value - assert(typeof fieldVal !== 'undefined', `${key}: fieldVal from span is null`) - - if (expectValue instanceof RegExp) { - assert(expectValue.test(fieldVal.toString()), `${key}: ${expectValue.toString()} !== (expect) ${fieldVal.toString()}`) - } - else { - const res = fieldVal === expectValue - assert(res, `${key}: ${fieldVal.toString()} !== (expect) ${expectValue.toString()}`) - } -} - - -// function sortSpansByStartTimeDesc(spans: JaegerTraceInfoSpan[]): JaegerTraceInfoSpan[] { -// return spans.sort((a, b) => { -// return b.startTime - a.startTime -// }) -// } - -export interface Traceparent { - version: string - traceId: string - parentId: string - traceFlags: string -} - -export function retrieveTraceparentFromHeader(headers: Headers | UndiciHeaders | Record): Traceparent | undefined { - assert(headers, 'headers is null') - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const traceparent: string = typeof headers.get === 'function' - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - ? headers.get('traceparent') - // @ts-ignore - : headers['traceparent'] - if (! traceparent) { return } - - const [version, traceId, parentId, traceFlags] = traceparent.split('-') - return { - version, - traceId, - parentId, - traceFlags, - } as Traceparent -} - -// #region assertJaegerParentSpanArray - -export interface AssertJaegerParentSpanRow { - parentSpan: JaegerTraceInfoSpan - childSpan: JaegerTraceInfoSpan -} -export function assertJaegerParentSpanArray(input: AssertJaegerParentSpanRow[]): void { - input.forEach((row) => { - assertJaegerParentSpan(row.parentSpan, row.childSpan) - }) -} - -// #region assertJaegerParentSpan - -export function assertJaegerParentSpan( - parentSpan: JaegerTraceInfoSpan, - childSpan: JaegerTraceInfoSpan, -): void { - - assert(parentSpan, 'parentSpan is null') - assert(childSpan, 'childSpan is null') - - assert( - parentSpan.spanID === childSpan.references[0]?.spanID, - `parentSpan.spanID: ${parentSpan.spanID}, - childSpan: ${childSpan.spanID}, - childSpan.parent spanID: ${childSpan.references[0]?.spanID}`, - ) -} - diff --git a/packages/otel/test/00.dummy.test.ts b/packages/otel/test/00.dummy.test.ts deleted file mode 100644 index 0dc314d66..000000000 --- a/packages/otel/test/00.dummy.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('should work', () => { - it('always passed', () => { - assert(testConfig) - }) - }) - -}) - diff --git a/packages/otel/test/01.index.test.ts b/packages/otel/test/01.index.test.ts deleted file mode 100644 index 178dd01e3..000000000 --- a/packages/otel/test/01.index.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { useComponents } from '##/imports.js' -import * as Foo from '##/index.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('should work', () => { - it('index', () => { - assert(Foo) - }) - - it('useComponents', () => { - assert(Array.isArray(useComponents)) - }) - - it('testAppDir eq testConfig.testAppDir', () => { - const { app } = testConfig - assert(app) - - const appDir = app.getAppDir() - assert(appDir) - assert(appDir === testConfig.testAppDir) - }) - }) - -}) - diff --git a/packages/otel/test/02.home.test.ts b/packages/otel/test/02.home.test.ts deleted file mode 100644 index 730f8b91e..000000000 --- a/packages/otel/test/02.home.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { ConfigKey, Msg } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' -import type { RespData, TestRespBody } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - const helloPath = `${apiBase.prefix}/${apiMethod.hello}` - - it(`Should ${apiBase.root} work`, async () => { - const { app, httpRequest } = testConfig - - const resp = await httpRequest.get(apiBase.root) - assert(resp.ok, resp.text) - - const ret = resp.body as TestRespBody | RespData - assert(typeof ret === 'object', JSON.stringify(ret, null, 2)) - - if ('code' in ret && typeof ret.code === 'number') { - assert(ret.code === 0) - assert(typeof ret.data === 'object', JSON.stringify(ret, null, 2)) - - const { url, header } = ret.data - const { host } = header - assert(url === '/', JSON.stringify(ret, null, 2)) - assert(host && testConfig.host.includes(host), JSON.stringify(ret, null, 2)) - } - else { - const { url, header } = ret as RespData - const { host } = header - assert(url === '/', JSON.stringify(ret, null, 2)) - assert(host && testConfig.host.includes(host), JSON.stringify(ret, null, 2)) - } - }) - - it(`Should ${helloPath} work`, async () => { - const { app, httpRequest } = testConfig - - const resp = await httpRequest.get(helloPath) - assert(resp.ok, resp.text) - - const ret = resp.text - assert(ret.includes(Msg.hello), JSON.stringify(ret, null, 2)) - }) - -}) - diff --git a/packages/otel/test/15.error.test.ts b/packages/otel/test/15.error.test.ts deleted file mode 100644 index f4da37a91..000000000 --- a/packages/otel/test/15.error.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.TraceDecorator}/${apiMethod.error}` // exception will be caught - const pathTrace = `${apiBase.TraceDecorator}/${apiMethod.trace_error}` - - it(`Should ${path} work`, async () => { - const { httpRequest } = testConfig - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - - const ret = resp.text - assert(ret.startsWith('debug for')) - assert(ret.includes('error')) - }) - - // error from default.service will be traced - it(`Should ${pathTrace} work`, async () => { - const { httpRequest } = testConfig - - const resp = await httpRequest.get(pathTrace) - assert(! resp.ok, resp.text) - assert(resp.status === 500, resp.text) - - const ret = resp.text - assert(ret.includes('debug for DefaultComponentService.error()'), ret) - }) - -}) - diff --git a/packages/otel/test/16.log.test.ts b/packages/otel/test/16.log.test.ts deleted file mode 100644 index 75dc24936..000000000 --- a/packages/otel/test/16.log.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const pathLog = `${apiBase.TraceDecorator}/${apiMethod.log}` // exception will be caught - const pathAppLog = `${apiBase.TraceDecorator}/${apiMethod.appLog}` - - it(`Should ${pathLog} work`, async () => { - const { httpRequest } = testConfig - - const resp = await httpRequest.get(pathLog) - assert(resp.ok, resp.text) - - const ret = resp.text - assert(ret) - // assert(ret.startsWith('debug for')) - }) - - it(`Should ${pathAppLog} work`, async () => { - const { httpRequest } = testConfig - - const resp = await httpRequest.get(pathAppLog) - assert(resp.ok, resp.text) - - const ret = resp.text - assert(ret) - // assert(! ret, ret) - // assert(ret.includes('debug for DefaultComponentService.error()'), ret) - }) - -}) - diff --git a/packages/otel/test/17.route.test.ts b/packages/otel/test/17.route.test.ts deleted file mode 100644 index 62724fbf4..000000000 --- a/packages/otel/test/17.route.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.route}/${apiMethod.hello}` - - it(`Should ${path}/1 work`, async () => { - const { httpRequest } = testConfig - - const resp = await httpRequest.get(`${path}/1`) - assert(resp.ok, resp.text) - - const ret = resp.text - assert(ret) - // assert(ret.startsWith('debug for')) - }) - - - it(`Should ${path}/2 work`, async () => { - const { httpRequest } = testConfig - - const resp = await httpRequest.get(`${path}/2`) - assert(resp.ok, resp.text) - - const ret = resp.text - assert(ret) - // assert(ret.startsWith('debug for')) - }) -}) - diff --git a/packages/otel/test/18.trace-service.test.ts b/packages/otel/test/18.trace-service.test.ts deleted file mode 100644 index bec7dd1c6..000000000 --- a/packages/otel/test/18.trace-service.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import assert from 'node:assert' - -import { fileShortPath } from '@waiting/shared-core' - -import type { TraceContext } from '##/index.js' -import { TraceService } from '##/index.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - - describe('TraceService TraceContext', () => { - it('normal', async () => { - const { container } = testConfig - const traceService = await container.getAsync(TraceService) - assert(traceService, 'traceService not found') - - const scope = Symbol('not-request') - const { span, traceContext } = traceService.startScopeSpan({ - name: 'foo', - scope, - }) - assert(span) - - const traceContext2 = traceService.getRootTraceContext(scope) - assert(traceContext2) - assert(traceContext2 === traceContext) - - // will skip update - traceService.setRootContext(scope, traceContext) - - const traceContext3 = traceService.getRootTraceContext(scope) - assert(traceContext3 === traceContext) - - try { - traceService.setRootContext(scope, {} as TraceContext) - } - catch (ex) { - assert(ex instanceof Error) - assert(ex.message.includes('scope root trace context exists already'), ex.message) - return - } - finally { - traceService.endSpan({ span, scope }) - } - assert(false, 'should throw Error') - }) - - it('child span', async () => { - const { container } = testConfig - const traceService = await container.getAsync(TraceService) - assert(traceService, 'traceService not found') - - const scope = Symbol('not-request') - const { span, traceContext } = traceService.startScopeSpan({ - name: 'foo1', - scope, - }) - assert(span) - - const traceContext2 = traceService.getRootTraceContext(scope) - assert(traceContext2) - assert(traceContext2 === traceContext) - - // will skip update - traceService.setRootContext(scope, traceContext) - - const traceContext3 = traceService.getRootTraceContext(scope) - assert(traceContext3 === traceContext) - - const { span: span2 } = traceService.startScopeSpan({ - name: 'foo2', - scope, - }) - assert(span2) - - try { - traceService.setRootContext(scope, {} as TraceContext) - } - catch (ex) { - assert(ex instanceof Error) - assert(ex.message.includes('scope root trace context exists already'), ex.message) - return - } - finally { - traceService.endSpan({ span: span2, scope }) - traceService.endSpan({ span, scope }) - } - assert(false, 'should throw Error') - }) - - it('retrieveParentTraceInfoBySpan()', async () => { - const { container } = testConfig - const traceService = await container.getAsync(TraceService) - assert(traceService, 'traceService not found') - - const scope = Symbol('not-request-2') - const { span, traceContext } = traceService.startScopeSpan({ - name: 'foo3', - scope, - }) - assert(span) - - const { span: span2, traceContext: ctx2 } = traceService.startScopeSpan({ - name: 'foo4', - scope, - traceContext, - }) - assert(span2) - void ctx2 - - try { - const info = traceService.retrieveParentTraceInfoBySpan(span2, scope) - assert(info) - const { traceContext: ctx3, span: span3 } = info - assert(ctx3 === traceContext) - assert(span3 === span) - } - finally { - traceService.endSpan({ span: span2, scope }) - traceService.endSpan({ span, scope }) - } - }) - }) -}) diff --git a/packages/otel/test/99.disable-trace.test.ts b/packages/otel/test/99.disable-trace.test.ts deleted file mode 100644 index 40eba8d67..000000000 --- a/packages/otel/test/99.disable-trace.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { exporterEndpoint } from '##/lib/config.js' -import type { Config } from '##/lib/types.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -const agent = exporterEndpoint.replace(/:\d+$/u, '') -assert(agent, 'OTEL_EXPORTER_OTLP_ENDPOINT not set') - -describe(fileShortPath(import.meta.url), function () { - - before(() => { - const { app } = testConfig - const otelConfig: Partial = { enable: false } - app.addConfigObject({ otelConfig }) - }) - - after(() => { - const { app } = testConfig - const otelConfig: Partial = { enable: true } - app.addConfigObject({ otelConfig }) - }) - - const path = `${apiBase.TraceDecorator}/${apiMethod.disable_trace}` - - it(`Should ${path} work`, async () => { - const { httpRequest } = testConfig - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - - const traceId = resp.text - assert(! traceId, 'traceId should empty') - }) - -}) diff --git a/packages/otel/test/api-test.ts b/packages/otel/test/api-test.ts deleted file mode 100644 index d2aaa1383..000000000 --- a/packages/otel/test/api-test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { ConfigKey } from '##/lib/types.js' - - -export const apiBase = { - root: '/', - prefix: `/_${ConfigKey.namespace}`, - demo: '/demo', - - TraceDecorator: `/_${ConfigKey.namespace}_trace_decorator`, - util: `/_${ConfigKey.namespace}_util`, - route: '/route', - decorator_data: `/decorator_data`, - trace_log: '/trace_log', - trace_singleton: '/trace_singleton', - trace_this: '/trace_this', - define_scope: '/define_scope', - grpc: '/grpc', -} - -export const apiMethod = { - root: '/', - hello: 'hello', - home: 'home', - component: 'component', - - id: 'id', - id2: 'id2', - decorator_arg: 'decorator_arg', - decorator_arg2: 'decorator_arg2', - disable_trace: 'disable_trace', - error: 'error', - error_no_capture: 'error_no_capture', - trace_error: 'trace_error', - log: 'log', - appLog: 'app_log', - warn: 'warn', - - propagateHeader: 'propagateHeader', - async: 'async', - sync: 'sync', - mix_on_async: 'mix_on_async', - mix_on_sync: 'mix_on_sync', - - scope: 'scope', - simple_scope: 'simple_scope', - trace_auto_scope: 'trace_auto_scope', - - after_throw: 'after_throw', - mix: 'mix', -} diff --git a/packages/otel/test/decorator/100.decorator.types.ts.test.ts b/packages/otel/test/decorator/100.decorator.types.ts.test.ts deleted file mode 100644 index 1bac60af9..000000000 --- a/packages/otel/test/decorator/100.decorator.types.ts.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' -import type { MethodTypeUnknown } from '@waiting/shared-types' - - -describe(fileShortPath(import.meta.url), function () { - - it(`Should MethodTypeUnknown work`, async () => { - const ret: MethodTypeUnknown = () => { - return 'OK' - } - assert(ret) - - const ret2: MethodTypeUnknown = async () => { - return 'OK' - } - assert(ret2) - }) - -}) - diff --git a/packages/otel/test/decorator/11.traceid.test.ts b/packages/otel/test/decorator/11.traceid.test.ts deleted file mode 100644 index c37a1cc74..000000000 --- a/packages/otel/test/decorator/11.traceid.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - AttrNames, - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - this.retries(2) - - const path = `${apiBase.TraceDecorator}/${apiMethod.id}` - - it(`Should ${path} work`, async () => { - const { httpRequest, validateSpanInfo } = testConfig - if (! validateSpanInfo) { - console.warn('validateSpanInfo is false, skip test') - return - } - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - - const traceId = resp.text - assert(traceId.length === 32) - console.log({ traceId }) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - // info.spans.forEach((span, idx) => { - // console.info(idx, { span }) - // }) - - const [rootSpan, span1] = sortSpans(info.spans) - assert(rootSpan) - assert(span1) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - tags: { - [SEMATTRS_HTTP_TARGET]: path, - [SEMATTRS_HTTP_ROUTE]: path, - }, - mergeDefaultLogs: false, - logs: [ - { event: AttrNames.RequestBegin }, - { event: AttrNames.PreProcessFinish }, - { event: AttrNames.PostProcessBegin }, - { event: AttrNames.Outgoing_Response_data, [AttrNames.Http_Response_Code]: 200 }, - { event: AttrNames.RequestEnd }, - ], - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DefaultComponentService/hello', - tags: { - 'caller.class': 'DefaultComponentService', - 'caller.method': 'hello', - 'span.kind': 'client', - }, - } - assertsSpan(span1, opt1) - - await Promise.all([ - httpRequest.get(path), - httpRequest.get(path), - httpRequest.get(path), - ]) - }) -}) - diff --git a/packages/otel/test/decorator/110.docorator-data.test.ts b/packages/otel/test/decorator/110.docorator-data.test.ts deleted file mode 100644 index b978e48b8..000000000 --- a/packages/otel/test/decorator/110.docorator-data.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertJaegerParentSpanArray, - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path1 = `${apiBase.decorator_data}/${apiMethod.async}` - const path2 = `${apiBase.decorator_data}/${apiMethod.sync}` - - it(`Should ${path1} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const id = Math.random().toString(36).slice(2) - const resp = await httpRequest.get(`${path1}/${id}`) - - assert(resp.ok, resp.text) - const ret = resp.text - assert(ret) - const [traceId, rnd] = ret.split(':') - assert(traceId, ret) - assert(rnd === id, ret) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 3) - assert(info) - const { spans } = info - assert(spans.length) - spans.forEach((span, idx) => { - console.info(idx, { span }) - }) - - const [rootSpan, span1, span2] = sortSpans(spans) - assert(rootSpan) - assert(span1) - assert(span2) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - { parentSpan: span1, childSpan: span2 }, - ]) - - assertRootSpan({ - path: path1, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path1}/:id`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path1}/${id}`, - [SEMATTRS_HTTP_ROUTE]: `${path1}/:id`, - rootAttrs: 'rootAttrs', - }, - logs: [ - {}, - false, - {}, - { event: 'default', rootAttrs: 'rootAttrs' }, - false, - false, - false, - ], - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DecoratorDataComponentController/traceIdAsync', - tags: { - 'caller.class': 'DecoratorDataComponentController', - 'caller.method': 'traceIdAsync', - 'span.kind': 'client', - }, - } - assertsSpan(span1, opt1) - - const opt2: AssertsOptions = { - traceId, - operationName: 'DecoratorDataComponentController/traceDecoratorDataAsync', - tags: { - 'caller.class': 'DecoratorDataComponentController', - 'caller.method': 'traceDecoratorDataAsync', - 'span.kind': 'client', - args0: id, - }, - logs: [ - { event: 'before', args0: id }, - { event: 'after', args0: id, res: `${id}${testSuffix}` }, - ], - } - assertsSpan(span2, opt2) - }) - - - it(`Should ${path2} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const id = Math.random().toString(36).slice(2) - const resp = await httpRequest.get(`${path2}/${id}`) - - assert(resp.ok, resp.text) - const ret = resp.text - assert(ret) - const [traceId, rnd] = ret.split(':') - assert(traceId, ret) - assert(rnd === id, ret) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 3) - assert(info) - console.log('--------------------', { info }) - const { spans } = info - assert(spans.length) - spans.forEach((span, idx) => { - console.info(idx, { span }) - }) - - const [rootSpan, span1, span2] = sortSpans(spans) - assert(rootSpan) - assert(span1) - assert(span2) - - assertRootSpan({ - path: path2, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path2}/:id`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path2}/${id}`, - [SEMATTRS_HTTP_ROUTE]: `${path2}/:id`, - rootAttrs: 'rootAttrs', - }, - logs: [ - {}, - false, - {}, - { event: 'default', rootAttrs: 'rootAttrs' }, - false, - false, - false, - ], - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DecoratorDataComponentController/traceIdSync', - tags: { - 'caller.class': 'DecoratorDataComponentController', - 'caller.method': 'traceIdSync', - 'span.kind': 'client', - }, - } - assertsSpan(span1, opt1) - - const opt2: AssertsOptions = { - traceId, - operationName: 'DecoratorDataComponentController/traceDecoratorDataSync', - tags: { - 'caller.class': 'DecoratorDataComponentController', - 'caller.method': 'traceDecoratorDataSync', - 'span.kind': 'client', - args0: id, - }, - logs: [ - { event: 'before', args0: id }, - { event: 'after', args0: id, res: `${id}${testSuffix}` }, - ], - } - assertsSpan(span2, opt2) - }) -}) - - diff --git a/packages/otel/test/decorator/111.docorator-scope.test.ts b/packages/otel/test/decorator/111.docorator-scope.test.ts deleted file mode 100644 index a84fbeea1..000000000 --- a/packages/otel/test/decorator/111.docorator-scope.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertJaegerParentSpanArray, assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, - sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.decorator_data}/${apiMethod.simple_scope}` - - it(`Should ${path} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest.get(path) - - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - console.log(`traceId: ${traceId}`) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 4) - assert(info) - const { spans } = info - const [rootSpan, span1, span2, span3] = sortSpans(spans) - assert(rootSpan) - assert(span1) - assert(span2) - assert(span3) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - { parentSpan: span1, childSpan: span2 }, - { parentSpan: span2, childSpan: span3 }, - ]) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - }, - logs: [ - {}, - false, - {}, - {}, - {}, - {}, - ], - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/simple', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': 'simple', - 'span.kind': 'client', - }, - } - assertsSpan(span1, opt1) - - const opt2: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple1', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple1', - 'span.kind': 'client', - }, - } - assertsSpan(span2, opt2) - - const opt3: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple1a', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple1a', - 'span.kind': 'client', - }, - } - assertsSpan(span3, opt3) - - }) - - it(`Should ${path} work again`, async () => { - const { httpRequest, testSuffix } = testConfig - await httpRequest.get(path) - }) -}) - - diff --git a/packages/otel/test/decorator/112.docorator-scope.test.ts b/packages/otel/test/decorator/112.docorator-scope.test.ts deleted file mode 100644 index 74dbb8a04..000000000 --- a/packages/otel/test/decorator/112.docorator-scope.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertJaegerParentSpanArray, assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, - sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.decorator_data}/${apiMethod.scope}` - - it(`Should ${path} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest.get(path) - - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 8) - assert(info) - const { spans } = info - const [rootSpan, span1, span2, span3, span4, span5, span6, span7] = sortSpans(spans) - assert(rootSpan) - assert(span1) - assert(span2) - assert(span3) - assert(span4) - assert(span5) - assert(span6) - assert(span7) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - { parentSpan: span1, childSpan: span2 }, - { parentSpan: span2, childSpan: span3 }, - { parentSpan: span4, childSpan: span5 }, - { parentSpan: span6, childSpan: span7 }, - ]) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - }, - logs: [ - {}, - false, - {}, - {}, - {}, - {}, - ], - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/simple', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': 'simple', - 'span.kind': 'client', - }, - } - assertsSpan(span1, opt1) - - const opt2: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple1', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple1', - 'span.kind': 'client', - }, - } - assertsSpan(span2, opt2) - - const opt3: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple1a', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple1a', - 'span.kind': 'client', - }, - } - assertsSpan(span3, opt3) - - assertsSpan(span4, opt2) - assertsSpan(span5, opt3) - - const opt6: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple2', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple2', - 'span.kind': 'client', - }, - } - assertsSpan(span6, opt6) - - const opt7: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple2a', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple2a', - 'span.kind': 'client', - }, - } - assertsSpan(span7, opt7) - }) -}) - - diff --git a/packages/otel/test/decorator/112.json b/packages/otel/test/decorator/112.json deleted file mode 100644 index 337074fb5..000000000 --- a/packages/otel/test/decorator/112.json +++ /dev/null @@ -1,638 +0,0 @@ -{ - "data": [ - { - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spans": [ - { - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "037f6f78e0582c6e", - "operationName": "HTTP GET /decorator_data/scope", - "references": [], - "startTime": 1717564415158000, - "duration": 23088, - "tags": [ - { - "key": "http.host", - "type": "string", - "value": "127.0.0.1:61605" - }, - { - "key": "http.method", - "type": "string", - "value": "GET" - }, - { - "key": "http.route", - "type": "string", - "value": "/decorator_data/scope" - }, - { - "key": "http.scheme", - "type": "string", - "value": "http" - }, - { - "key": "http.server_name", - "type": "string", - "value": "base-app" - }, - { - "key": "http.target", - "type": "string", - "value": "/decorator_data/scope" - }, - { - "key": "http.url", - "type": "string", - "value": "http://127.0.0.1:61605/decorator_data/scope" - }, - { - "key": "net.host.name", - "type": "string", - "value": "127.0.0.1" - }, - { - "key": "service.name", - "type": "string", - "value": "base-app" - }, - { - "key": "service.version", - "type": "string", - "value": "1.0.0" - }, - { - "key": "http.flavor", - "type": "string", - "value": "1.1" - }, - { - "key": "net.transport", - "type": "string", - "value": "ip_tcp" - }, - { - "key": "request.start.time", - "type": "string", - "value": "2024-06-05T13:13:35.154+08:00" - }, - { - "key": "request.end.time", - "type": "string", - "value": "2024-06-05T13:13:35.181+08:00" - }, - { - "key": "span.kind", - "type": "string", - "value": "server" - }, - { - "key": "otel.status_code", - "type": "string", - "value": "OK" - }, - { - "key": "internal.span.format", - "type": "string", - "value": "otlp" - } - ], - "logs": [ - { - "timestamp": 1717564415158254, - "fields": [ - { - "key": "event", - "type": "string", - "value": "request.begin" - }, - { - "key": "time", - "type": "string", - "value": "2024-06-05T13:13:35.154+08:00" - } - ] - }, - { - "timestamp": 1717564415162469, - "fields": [ - { - "key": "event", - "type": "string", - "value": "incoming.request.data" - }, - { - "key": "http.request.header.content_length", - "type": "string", - "value": "" - }, - { - "key": "http.request.header.content_type", - "type": "string", - "value": "" - } - ] - }, - { - "timestamp": 1717564415162609, - "fields": [ - { - "key": "event", - "type": "string", - "value": "pre.process.finish" - }, - { - "key": "service.memory.usage", - "type": "string", - "value": "{\n \"pid\": 11420,\n \"rss\": \"605.389 M\",\n \"heapTotal\": \"89.035 M\",\n \"heapUsed\": \"57.2 M\",\n \"external\": \"4.419 M\",\n \"arrayBuffers\": \"319.514 k\"\n}" - } - ] - }, - { - "timestamp": 1717564415177995, - "fields": [ - { - "key": "event", - "type": "string", - "value": "post.process.begin" - }, - { - "key": "time", - "type": "string", - "value": "2024-06-05T13:13:35.178+08:00" - } - ] - }, - { - "timestamp": 1717564415178714, - "fields": [ - { - "key": "event", - "type": "string", - "value": "outgoing.response.data" - }, - { - "key": "http.response.body", - "type": "string", - "value": "cc10bc5e7de918a3d211c8c751c57ffc" - }, - { - "key": "http.response.code", - "type": "int64", - "value": 200 - }, - { - "key": "http.response.header.content_length", - "type": "string", - "value": "32" - }, - { - "key": "http.response.header.content_type", - "type": "string", - "value": "text/plain; charset=utf-8" - } - ] - }, - { - "timestamp": 1717564415181003, - "fields": [ - { - "key": "event", - "type": "string", - "value": "request.end" - }, - { - "key": "time", - "type": "string", - "value": "2024-06-05T13:13:35.181+08:00" - } - ] - } - ], - "processID": "p1", - "warnings": null - }, - { - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "f49f55e1055f36be", - "operationName": "DecoratorDataComponentController/_simple1a", - "references": [ - { - "refType": "CHILD_OF", - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "f2346a7bc39a433c" - } - ], - "startTime": 1717564415171000, - "duration": 187, - "tags": [ - { - "key": "caller.class", - "type": "string", - "value": "DecoratorDataComponentController" - }, - { - "key": "caller.method", - "type": "string", - "value": "_simple1a" - }, - { - "key": "span.kind", - "type": "string", - "value": "client" - }, - { - "key": "otel.status_code", - "type": "string", - "value": "OK" - }, - { - "key": "internal.span.format", - "type": "string", - "value": "otlp" - } - ], - "logs": [], - "processID": "p1", - "warnings": null - }, - { - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "d17c58417777ad46", - "operationName": "DecoratorDataComponentController/_simple2a", - "references": [ - { - "refType": "CHILD_OF", - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "aabb5336aed1598f" - } - ], - "startTime": 1717564415171000, - "duration": 750, - "tags": [ - { - "key": "caller.class", - "type": "string", - "value": "DecoratorDataComponentController" - }, - { - "key": "caller.method", - "type": "string", - "value": "_simple2a" - }, - { - "key": "span.kind", - "type": "string", - "value": "client" - }, - { - "key": "otel.status_code", - "type": "string", - "value": "OK" - }, - { - "key": "internal.span.format", - "type": "string", - "value": "otlp" - } - ], - "logs": [], - "processID": "p1", - "warnings": null - }, - { - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "f2346a7bc39a433c", - "operationName": "DecoratorDataComponentController/_simple1", - "references": [ - { - "refType": "CHILD_OF", - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "ee5ca4dbbaba0e0a" - } - ], - "startTime": 1717564415170000, - "duration": 3854, - "tags": [ - { - "key": "caller.class", - "type": "string", - "value": "DecoratorDataComponentController" - }, - { - "key": "caller.method", - "type": "string", - "value": "_simple1" - }, - { - "key": "span.kind", - "type": "string", - "value": "client" - }, - { - "key": "otel.status_code", - "type": "string", - "value": "OK" - }, - { - "key": "internal.span.format", - "type": "string", - "value": "otlp" - } - ], - "logs": [], - "processID": "p1", - "warnings": null - }, - { - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "607dc8f2afa9de7c", - "operationName": "DecoratorDataComponentController/_simple1a", - "references": [ - { - "refType": "CHILD_OF", - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "0754faa7f1bf6c90" - } - ], - "startTime": 1717564415167000, - "duration": 353, - "tags": [ - { - "key": "caller.class", - "type": "string", - "value": "DecoratorDataComponentController" - }, - { - "key": "caller.method", - "type": "string", - "value": "_simple1a" - }, - { - "key": "span.kind", - "type": "string", - "value": "client" - }, - { - "key": "otel.status_code", - "type": "string", - "value": "OK" - }, - { - "key": "internal.span.format", - "type": "string", - "value": "otlp" - } - ], - "logs": [], - "processID": "p1", - "warnings": null - }, - { - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "0754faa7f1bf6c90", - "operationName": "DecoratorDataComponentController/_simple1", - "references": [ - { - "refType": "CHILD_OF", - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "ee5ca4dbbaba0e0a" - } - ], - "startTime": 1717564415166000, - "duration": 2121, - "tags": [ - { - "key": "caller.class", - "type": "string", - "value": "DecoratorDataComponentController" - }, - { - "key": "caller.method", - "type": "string", - "value": "_simple1" - }, - { - "key": "span.kind", - "type": "string", - "value": "client" - }, - { - "key": "otel.status_code", - "type": "string", - "value": "OK" - }, - { - "key": "internal.span.format", - "type": "string", - "value": "otlp" - } - ], - "logs": [], - "processID": "p1", - "warnings": null - }, - { - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "aabb5336aed1598f", - "operationName": "DecoratorDataComponentController/_simple2", - "references": [ - { - "refType": "CHILD_OF", - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "ee5ca4dbbaba0e0a" - } - ], - "startTime": 1717564415170000, - "duration": 4507, - "tags": [ - { - "key": "caller.class", - "type": "string", - "value": "DecoratorDataComponentController" - }, - { - "key": "caller.method", - "type": "string", - "value": "_simple2" - }, - { - "key": "span.kind", - "type": "string", - "value": "client" - }, - { - "key": "otel.status_code", - "type": "string", - "value": "OK" - }, - { - "key": "internal.span.format", - "type": "string", - "value": "otlp" - } - ], - "logs": [], - "processID": "p1", - "warnings": null - }, - { - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "ee5ca4dbbaba0e0a", - "operationName": "DecoratorDataComponentController/simple", - "references": [ - { - "refType": "CHILD_OF", - "traceID": "cc10bc5e7de918a3d211c8c751c57ffc", - "spanID": "037f6f78e0582c6e" - } - ], - "startTime": 1717564415166000, - "duration": 10148, - "tags": [ - { - "key": "caller.class", - "type": "string", - "value": "DecoratorDataComponentController" - }, - { - "key": "caller.method", - "type": "string", - "value": "simple" - }, - { - "key": "span.kind", - "type": "string", - "value": "client" - }, - { - "key": "otel.status_code", - "type": "string", - "value": "OK" - }, - { - "key": "internal.span.format", - "type": "string", - "value": "otlp" - } - ], - "logs": [], - "processID": "p1", - "warnings": null - } - ], - "processes": { - "p1": { - "serviceName": "base-app", - "tags": [ - { - "key": "host.arch", - "type": "string", - "value": "amd64" - }, - { - "key": "host.id", - "type": "string", - "value": "b1b03cb7-071a-4620-a1a9-69f07a73fefa" - }, - { - "key": "host.name", - "type": "string", - "value": "DESKTOP-1V84MBJ" - }, - { - "key": "os.type", - "type": "string", - "value": "windows" - }, - { - "key": "os.version", - "type": "string", - "value": "10.0.19045" - }, - { - "key": "otel.library.name", - "type": "string", - "value": "@mwcp/otel" - }, - { - "key": "otel.library.version", - "type": "string", - "value": "30.4.0" - }, - { - "key": "process.command", - "type": "string", - "value": "f:\\project\\my\\midway-components\\node_modules\\mocha\\lib\\cli\\cli.js" - }, - { - "key": "process.command_args", - "type": "string", - "value": "[\"C:\\\\Program Files\\\\nodejs\\\\node.exe\",\"--no-warnings\",\"--loader=ts-node/esm\",\"--enable-source-maps\",\"f:\\\\project\\\\my\\\\midway-components\\\\node_modules\\\\mocha\\\\lib\\\\cli\\\\cli.js\",\"test/**/*.test.ts\",\"--no-parallel\",\"--no-config\",\"--no-package\",\"--bail\",\"--full-trace\",\"--require\",\"tsconfig-paths/register.js\",\"--require\",\"test/setup.ts\",\"--timeout\",\"30000\",\"--ui\",\"bdd\",\"--exit\",\"--diff\",\"--extension\",\"js\",\"--extension\",\"cjs\",\"--extension\",\"mjs\",\"--reporter\",\"spec\",\"--slow\",\"75\",\"--watch-ignore\",\"node_modules\",\"--watch-ignore\",\".git\"]" - }, - { - "key": "process.executable.name", - "type": "string", - "value": "C:\\Windows\\system32\\cmd.exe " - }, - { - "key": "process.executable.path", - "type": "string", - "value": "C:\\Program Files\\nodejs\\node.exe" - }, - { - "key": "process.owner", - "type": "string", - "value": "mark" - }, - { - "key": "process.pid", - "type": "int64", - "value": 11420 - }, - { - "key": "process.runtime.description", - "type": "string", - "value": "Node.js" - }, - { - "key": "process.runtime.name", - "type": "string", - "value": "nodejs" - }, - { - "key": "process.runtime.version", - "type": "string", - "value": "22.1.0" - }, - { - "key": "service.version", - "type": "string", - "value": "1.0.0" - }, - { - "key": "telemetry.sdk.language", - "type": "string", - "value": "nodejs" - }, - { - "key": "telemetry.sdk.name", - "type": "string", - "value": "opentelemetry" - }, - { - "key": "telemetry.sdk.version", - "type": "string", - "value": "1.24.1" - } - ] - } - }, - "warnings": null - } - ], - "total": 0, - "limit": 0, - "offset": 0, - "errors": null -} \ No newline at end of file diff --git a/packages/otel/test/decorator/113.docorator-scope-auto.test.ts b/packages/otel/test/decorator/113.docorator-scope-auto.test.ts deleted file mode 100644 index 45d7012fa..000000000 --- a/packages/otel/test/decorator/113.docorator-scope-auto.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertJaegerParentSpanArray, - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.decorator_data}/${apiMethod.trace_auto_scope}` - - it(`Should ${path} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest.get(path) - - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 8) - assert(info) - const { spans } = info - const [rootSpan, span1, span2, span3, span4, span5, span6, span7] = sortSpans(spans) - assert(rootSpan) - assert(span1) - assert(span2) - assert(span3) - assert(span4) - assert(span5) - assert(span6) - assert(span7) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - - { parentSpan: span1, childSpan: span2 }, - { parentSpan: span2, childSpan: span3 }, - - { parentSpan: span1, childSpan: span4 }, - { parentSpan: span4, childSpan: span5 }, - - { parentSpan: span1, childSpan: span6 }, - { parentSpan: span6, childSpan: span7 }, - ]) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - }, - logs: [ - {}, - false, - {}, - {}, - {}, - {}, - ], - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/simple', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': 'simple', - 'span.kind': 'client', - }, - // logs: [ - // { event: 'before', args0: id }, - // { event: 'after', args0: id, res: `${id}${testSuffix}` }, - // ], - } - assertsSpan(span1, opt1) - - const opt2: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple1', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple1', - 'span.kind': 'client', - }, - } - assertsSpan(span2, opt2) - - const opt3: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple1a', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple1a', - 'span.kind': 'client', - }, - } - assertsSpan(span3, opt3) - - assertsSpan(span4, opt2) - assertsSpan(span5, opt3) - - const opt6: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple2', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple2', - 'span.kind': 'client', - }, - } - assertsSpan(span6, opt6) - - const opt7: AssertsOptions = { - traceId, - operationName: 'DecoratorScopeComponentController/_simple2a', - tags: { - 'caller.class': 'DecoratorScopeComponentController', - 'caller.method': '_simple2a', - 'span.kind': 'client', - }, - } - assertsSpan(span7, opt7) - }) -}) - - diff --git a/packages/otel/test/decorator/12.traceid2.test.ts b/packages/otel/test/decorator/12.traceid2.test.ts deleted file mode 100644 index db8d56812..000000000 --- a/packages/otel/test/decorator/12.traceid2.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertJaegerParentSpanArray, - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - this.retries(3) - - const path = `${apiBase.TraceDecorator}/${apiMethod.id2}` - - it(`Should ${path} work`, async () => { - const { httpRequest, validateSpanInfo } = testConfig - if (! validateSpanInfo) { - console.warn('validateSpanInfo is false, skip test') - return - } - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - - const traceId = resp.text - assert(traceId.length === 32) - console.log({ traceId }) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 4) - assert(info) - // info.spans.forEach((span, idx) => { - // console.info(idx, { span }) - // }) - - const [rootSpan, span1, span2, span3] = sortSpans(info.spans) - assert(rootSpan) - assert(span1) - assert(span2) - assert(span3) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - - { parentSpan: span1, childSpan: span2 }, - { parentSpan: span1, childSpan: span3 }, - ]) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - tags: { - [SEMATTRS_HTTP_TARGET]: path, - [SEMATTRS_HTTP_ROUTE]: path, - }, - logs: [ - {}, - false, - {}, - {}, - {}, - {}, - ], - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DefaultComponentController/traceId2', - tags: { - 'caller.class': 'DefaultComponentController', - 'caller.method': 'traceId2', - 'span.kind': 'client', - }, - } - assertsSpan(span1, opt1) - - const opt2: AssertsOptions = { - traceId, - operationName: 'DefaultComponentService/hello', - tags: { - 'caller.class': 'DefaultComponentService', - 'caller.method': 'hello', - 'span.kind': 'client', - }, - } - assertsSpan(span2, opt2) - - const opt3: AssertsOptions = { - traceId, - operationName: 'DefaultComponentService/helloSync', - tags: { - 'caller.class': 'DefaultComponentService', - 'caller.method': 'helloSync', - 'span.kind': 'client', - }, - } - assertsSpan(span3, opt3) - }) -}) - diff --git a/packages/otel/test/decorator/120.docorator-data-mix.test.ts b/packages/otel/test/decorator/120.docorator-data-mix.test.ts deleted file mode 100644 index 4d65c4742..000000000 --- a/packages/otel/test/decorator/120.docorator-data-mix.test.ts +++ /dev/null @@ -1,183 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - AttrNames, - HeadersKey, - assertJaegerParentSpanArray, assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, - retrieveTraceparentFromHeader, - sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path1 = `${apiBase.decorator_data}/${apiMethod.mix_on_async}` - const path2 = `${apiBase.decorator_data}/${apiMethod.mix_on_sync}` - - it(`Should ${path1} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const id = Math.random().toString(36).slice(2) - const resp = await httpRequest.get(`${path1}/${id}`) - - assert(resp.ok, resp.text) - const ret = resp.text - assert(ret) - const [traceId, rnd] = ret.split(':') - assert(traceId, ret) - assert(rnd === id, ret) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 3) - assert(info) - console.log('--------------------', { info }) - const { spans } = info - spans.forEach((span, idx) => { - console.info(idx, { span }) - }) - - const [rootSpan, span1, span2] = sortSpans(spans) - assert(rootSpan) - assert(span1) - assert(span2) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - { parentSpan: span1, childSpan: span2 }, - ]) - - assertRootSpan({ - path: path1, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path1}/:id`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path1}/${id}`, - [SEMATTRS_HTTP_ROUTE]: `${path1}/:id`, - rootAttrs: 'rootAttrs', - }, - logs: [ - {}, - false, - {}, - { event: 'default', rootAttrs: 'rootAttrs' }, - false, - false, - false, - ], - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DecoratorDataComponentController/mixOnAsync', - tags: { - 'caller.class': 'DecoratorDataComponentController', - 'caller.method': 'mixOnAsync', - 'span.kind': 'client', - }, - } - assertsSpan(span1, opt1) - - const opt2: AssertsOptions = { - traceId, - operationName: 'DecoratorDataComponentController/_mixOnAsync', - tags: { - 'caller.class': 'DecoratorDataComponentController', - 'caller.method': '_mixOnAsync', - 'span.kind': 'client', - args0: id, - }, - logs: [ - { event: 'before', args0: id }, - { event: 'after', args0: id, res: `${id}${testSuffix}` }, - ], - } - assertsSpan(span2, opt2) - }) - - - it(`Should ${path2} return error`, async () => { - const { httpRequest, testSuffix } = testConfig - - const id = Math.random().toString(36).slice(2) - const resp = await httpRequest.get(`${path2}/${id}`) - - assert(! resp.ok, resp.text) - assert(resp.status === 500) - assert(resp.text.includes('before() is a AsyncFunction'), resp.text) - assert(resp.text.includes('class: DecoratorDataComponentController'), resp.text) - assert(resp.text.includes('method: _MixOnSync'), resp.text) - - const traceparent = retrieveTraceparentFromHeader(resp.header as Headers) - assert(traceparent) - - const [info] = await retrieveTraceInfoFromRemote(traceparent.traceId, 2) - assert(info) - const traceId = info.traceID - console.log('--------------------', { info }) - const { spans } = info - - const [rootSpan, span1, span2] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - const errMsg = '[@mwcp/share] Trace() before() is a AsyncFunction, but decorated method is sync function, class: DecoratorDataComponentController, method: _MixOnSync' - - assertRootSpan({ - path: path2, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path2}/:id`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path2}/${id}`, - [SEMATTRS_HTTP_ROUTE]: `${path2}/:id`, - [AttrNames.HTTP_ERROR_NAME]: 'AssertionError', - [AttrNames.HTTP_ERROR_MESSAGE]: errMsg, - [AttrNames.otel_status_code]: 'ERROR', - error: true, - }, - logs: [ - {}, - false, - {}, - false, - { - event: `${AttrNames.Outgoing_Response_data}`, - [AttrNames.Http_Response_Code]: 500, - [AttrNames.Http_Response_Body]: errMsg, - }, - ], - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DecoratorDataComponentController/mixOnSync', - tags: { - 'caller.class': 'DecoratorDataComponentController', - 'caller.method': 'mixOnSync', - 'span.kind': 'client', - [AttrNames.HTTP_ERROR_NAME]: 'AssertionError', - [AttrNames.HTTP_ERROR_MESSAGE]: errMsg, - [AttrNames.otel_status_code]: 'ERROR', - error: true, - }, - logs: [ - { - event: `${AttrNames.Exception}`, - [AttrNames.Exception_Type]: 'ERR_ASSERTION', - [AttrNames.exception_message]: errMsg, - }, - ], - } - assertsSpan(span1, opt1) - }) -}) - - diff --git a/packages/otel/test/decorator/120.trace-log.test.ts b/packages/otel/test/decorator/120.trace-log.test.ts deleted file mode 100644 index 8a4454794..000000000 --- a/packages/otel/test/decorator/120.trace-log.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.trace_log}/${apiMethod.hello}` - - it(`Should ${path} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest.get(path) - - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - rootAttrs: 'rootAttrs', - }, - logs: [ - {}, - false, - {}, - { event: 'default', rootAttrs: 'rootAttrs' }, - false, - false, - false, - ], - }) - - const foo = 'foo' - const bar = 'bar' - const instanceName = 'TraceLogComponentController' - const methodName1 = '_simple1' - const methodName2 = '_simple2' - - const opt1: AssertsOptions = { - traceId, - operationName: 'TraceLogComponentController/hello', - tags: { - args0: foo, - 'caller.class': 'TraceLogComponentController', - 'caller.method': 'hello', - 'span.kind': 'client', - }, - logs: [ - { event: 'before', args0: foo, instanceName, methodName: methodName1 }, - { event: 'after', args0: foo, instanceName, methodName: methodName1, res: foo }, - - { event: 'before', args0: bar, instanceName, methodName: methodName2 }, - { event: 'after', args0: bar, instanceName, methodName: methodName2, res: bar }, - ], - } - assertsSpan(span1, opt1) - }) -}) - - diff --git a/packages/otel/test/decorator/121.trace-log.error.test.ts b/packages/otel/test/decorator/121.trace-log.error.test.ts deleted file mode 100644 index 5a132317c..000000000 --- a/packages/otel/test/decorator/121.trace-log.error.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.trace_log}/${apiMethod.error}` - const path2 = `${apiBase.trace_log}/${apiMethod.error_no_capture}` - - it(`Should ${path} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest.get(path) - - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - rootAttrs: 'rootAttrs', - }, - logs: [ - {}, - false, - {}, - { event: 'default', rootAttrs: 'rootAttrs' }, - false, - false, - false, - ], - }) - - const foo = 'foo' - const bar = 'bar' - const instanceName = 'TraceLogComponentController' - const methodName1 = '_simple1' - const methodName2 = '_simple2' - - const opt1: AssertsOptions = { - traceId, - operationName: 'TraceLogComponentController/error', - tags: { - args0: foo, - 'caller.class': 'TraceLogComponentController', - 'caller.method': 'error', - 'span.kind': 'client', - }, - logs: [ - { event: 'before', args0: foo, instanceName, methodName: methodName1 }, - { event: 'exception', 'exception.message': 'foo-error' }, - - { event: 'before', args0: bar, instanceName, methodName: methodName2 }, - { event: 'exception', 'exception.message': 'bar-error' }, - ], - } - assertsSpan(span1, opt1) - }) - - it(`Should ${path2} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest.get(path2) - assert(! resp.ok, resp.text) - // check span manually - }) -}) - - diff --git a/packages/otel/test/decorator/122.trace-singleton.test.ts b/packages/otel/test/decorator/122.trace-singleton.test.ts deleted file mode 100644 index 2f0261559..000000000 --- a/packages/otel/test/decorator/122.trace-singleton.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path1 = `${apiBase.trace_singleton}/${apiMethod.hello}` - const path2 = `${apiBase.trace_singleton}/${apiMethod.home}` - - it(`Should ${path1} work`, async () => { - const { httpRequest, testSuffix } = testConfig - const path = path1 - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - }, - mergeDefaultLogs: false, - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'TraceController/hello', - } - assertsSpan(span1, opt1) - }) - - it(`Should ${path2} work`, async () => { - const { httpRequest, testSuffix } = testConfig - const path = path2 - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - }, - mergeDefaultLogs: false, - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'TraceController/home', - } - assertsSpan(span1, opt1) - }) - -}) - - diff --git a/packages/otel/test/decorator/123.trace-cb-this.test.ts b/packages/otel/test/decorator/123.trace-cb-this.test.ts deleted file mode 100644 index af6c9c493..000000000 --- a/packages/otel/test/decorator/123.trace-cb-this.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path1 = `${apiBase.trace_this}/${apiMethod.home}` - const path2 = `${apiBase.trace_this}/${apiMethod.hello}` - - it(`Should ${path1} work`, async () => { - const { httpRequest, testSuffix } = testConfig - const path = path1 - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - }, - mergeDefaultLogs: false, - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'TraceThisController/home', - } - assertsSpan(span1, opt1) - }) - - it(`Should ${path2} work`, async () => { - const { httpRequest, testSuffix } = testConfig - const path = path2 - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - }, - mergeDefaultLogs: false, - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'TraceThisController/hello', - } - assertsSpan(span1, opt1) - }) - -}) - - diff --git a/packages/otel/test/decorator/124.trace-log.afterThrow.test.ts b/packages/otel/test/decorator/124.trace-log.afterThrow.test.ts deleted file mode 100644 index 4b8425bca..000000000 --- a/packages/otel/test/decorator/124.trace-log.afterThrow.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.trace_log}/${apiMethod.after_throw}` - - it(`Should ${path} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest.get(path) - - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - rootAttrs: 'rootAttrs', - }, - logs: [ - {}, - false, - {}, - { event: 'default', rootAttrs: 'rootAttrs' }, - false, - false, - false, - ], - }) - - const foo = 'foo' - const bar = 'bar' - const instanceName = 'TraceLogComponentController' - const methodName1 = '_simple1' - const methodName2 = '_simple2' - - const opt1: AssertsOptions = { - traceId, - operationName: 'TraceLogComponentController/error', - tags: { - args0: foo, - 'caller.class': 'TraceLogComponentController', - 'caller.method': 'error', - 'span.kind': 'client', - }, - logs: [ - { event: 'before', args0: foo, instanceName, methodName: methodName1 }, - { event: 'afterThrow', args0: foo, instanceName, methodName: methodName1 }, - { event: 'exception', 'exception.message': 'foo-error' }, - - { event: 'before', args0: bar, instanceName, methodName: methodName2 }, - { event: 'afterThrow', args0: bar, instanceName, methodName: methodName2 }, - { event: 'exception', 'exception.message': 'bar-error' }, - ], - } - assertsSpan(span1, opt1) - }) - -}) - diff --git a/packages/otel/test/decorator/125.trace-log-mix.test.ts b/packages/otel/test/decorator/125.trace-log-mix.test.ts deleted file mode 100644 index 93f9f3e33..000000000 --- a/packages/otel/test/decorator/125.trace-log-mix.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.trace_log}/${apiMethod.mix}` - - it(`Should ${path} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest.get(path) - - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - rootAttrs: 'rootAttrs', - }, - logs: [ - {}, - false, - {}, - { event: 'default', rootAttrs: 'rootAttrs' }, - false, - false, - false, - ], - }) - - const foo = 'foo' - const bar = 'bar' - const instanceName = 'TraceLogMixController' - const methodName1 = '_simple1' - const methodName2 = '_simple2' - - const opt1: AssertsOptions = { - traceId, - operationName: 'TraceLogMixController/hello', - tags: { - args0: foo, - 'caller.class': 'TraceLogMixController', - 'caller.method': 'hello', - 'span.kind': 'client', - }, - logs: [ - { event: 'before', args0: foo, instanceName, methodName: methodName1 }, - { event: 'after', args0: foo, instanceName, methodName: methodName1, res: foo }, - - { event: 'before', args0: bar, instanceName, methodName: methodName2 }, - { event: 'after', args0: bar, instanceName, methodName: methodName2, res: bar }, - ], - } - assertsSpan(span1, opt1) - }) -}) - - diff --git a/packages/otel/test/decorator/13.decorator_arg.test.ts b/packages/otel/test/decorator/13.decorator_arg.test.ts deleted file mode 100644 index ff6d669f5..000000000 --- a/packages/otel/test/decorator/13.decorator_arg.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertJaegerParentSpanArray, - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - this.retries(3) - - const path = `${apiBase.TraceDecorator}/${apiMethod.decorator_arg}` - - it(`Should ${path} work`, async () => { - const { httpRequest, validateSpanInfo } = testConfig - if (! validateSpanInfo) { - console.warn('validateSpanInfo is false, skip test') - return - } - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - - const [traceId, rnd] = resp.text.split(':') - assert(traceId) - assert(traceId.length === 32) - assert(rnd) - console.log({ traceId, rnd }) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 4) - assert(info) - - const [rootSpan, span1, span2, span3] = sortSpans(info.spans) - assert(rootSpan) - assert(span1) - assert(span2) - assert(span3) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - - { parentSpan: span1, childSpan: span2 }, - { parentSpan: span1, childSpan: span3 }, - ]) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: path, - [SEMATTRS_HTTP_ROUTE]: path, - }, - mergeDefaultLogs: false, - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DefaultComponentController/arg', - tags: { - 'caller.class': 'DefaultComponentController', - 'caller.method': 'arg', - 'span.kind': 'client', - }, - } - try { - assertsSpan(span1, opt1) - } - catch (ex) { - console.error({ rootSpan, span1, span2, span3 }) - throw ex - } - - const opt2: AssertsOptions = { - traceId, - operationName: `foo-${rnd}`, - tags: { - 'caller.class': 'DefaultComponentService', - 'caller.method': 'testArg', - 'span.kind': 'client', - }, - } - try { - assertsSpan(span2, opt2) - } - catch (ex) { - console.error({ rootSpan, span1, span2, span3 }) - throw ex - } - - const opt3: AssertsOptions = { - traceId, - operationName: 'DefaultComponentService/helloSync', - tags: { - 'caller.class': 'DefaultComponentService', - 'caller.method': 'helloSync', - 'span.kind': 'client', - }, - } - try { - assertsSpan(span3, opt3) - } - catch (ex) { - console.error({ rootSpan, span1, span2, span3 }) - throw ex - } - - console.info({ rootSpan, span1, span2, span3 }) - }) - -}) - diff --git a/packages/otel/test/decorator/14.decorator_arg2.test.ts b/packages/otel/test/decorator/14.decorator_arg2.test.ts deleted file mode 100644 index 47eb18120..000000000 --- a/packages/otel/test/decorator/14.decorator_arg2.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertJaegerParentSpanArray, - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - this.retries(2) - - const path = `${apiBase.TraceDecorator}/${apiMethod.decorator_arg2}` - - it(`Should ${path} work`, async () => { - const { httpRequest, validateSpanInfo } = testConfig - if (! validateSpanInfo) { - console.warn('validateSpanInfo is false, skip test') - return - } - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - - const [traceId, rnd, suffix] = resp.text.split(':') - assert(traceId) - assert(traceId.length === 32) - assert(rnd) - assert(typeof suffix === 'string') - console.log({ traceId, rnd, suffix }) - const int = parseInt(rnd, 10) - const opName = `foo-${int + 1}-${suffix}` - - const [info] = await retrieveTraceInfoFromRemote(traceId, 3) - assert(info) - - const [rootSpan, span1, span2] = sortSpans(info.spans) - assert(rootSpan) - assert(span1) - assert(span2) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - { parentSpan: span1, childSpan: span2 }, - ]) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: path, - [SEMATTRS_HTTP_ROUTE]: path, - }, - mergeDefaultLogs: false, - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'DefaultComponentController/arg2', - tags: { - 'caller.class': 'DefaultComponentController', - 'caller.method': 'arg2', - 'span.kind': 'client', - }, - } - try { - assertsSpan(span1, opt1) - } - catch (ex) { - console.error({ rootSpan, span1, span2 }) - throw ex - } - - const opt2: AssertsOptions = { - traceId, - operationName: opName, - tags: { - 'caller.class': 'DefaultComponentService', - 'caller.method': 'testArg2', - 'span.kind': 'client', - }, - } - try { - assertsSpan(span2, opt2) - } - catch (ex) { - console.error({ rootSpan, span1, span2 }) - throw ex - } - }) - -}) - diff --git a/packages/otel/test/decorator/19.singleton.test.ts b/packages/otel/test/decorator/19.singleton.test.ts deleted file mode 100644 index b65242c72..000000000 --- a/packages/otel/test/decorator/19.singleton.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - assertJaegerParentSpanArray, - assertRootSpan, - assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import type { AssertsOptions } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - this.retries(3) - - const path = `${apiBase.define_scope}/${apiMethod.hello}` - - it(`Should ${path} work`, async () => { - const { httpRequest, validateSpanInfo } = testConfig - if (! validateSpanInfo) { - console.warn('validateSpanInfo is false, skip test') - return - } - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - - const traceId = resp.text - assert(traceId.length === 32) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 4) - assert(info) - // info.spans.forEach((span, idx) => { - // console.info(idx, { span }) - // }) - - const [rootSpan, span1, span2, span3] = sortSpans(info.spans) - assert(rootSpan) - assert(span1) - assert(span2) - assert(span3) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - { parentSpan: span1, childSpan: span2 }, - { parentSpan: span1, childSpan: span3 }, - ]) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - tags: { - [SEMATTRS_HTTP_TARGET]: path, - [SEMATTRS_HTTP_ROUTE]: path, - }, - mergeDefaultLogs: false, - }) - - const opt1: AssertsOptions = { - traceId, - operationName: 'SingletonService/hello', - tags: { - 'caller.class': 'SingletonService', - 'caller.method': 'hello', - 'span.kind': 'client', - }, - } - assertsSpan(span1, opt1) - - const opt2: AssertsOptions = { - traceId, - operationName: 'SingletonService/helloAsync', - } - assertsSpan(span2, opt2) - - const opt3: AssertsOptions = { - traceId, - operationName: 'SingletonService/helloSync', - } - assertsSpan(span3, opt3) - }) -}) - diff --git a/packages/otel/test/domain/helloworld.ts b/packages/otel/test/domain/helloworld.ts deleted file mode 100644 index 8519fc635..000000000 --- a/packages/otel/test/domain/helloworld.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** -* This file is auto-generated by grpc-helper -*/ - -/* eslint-disable @typescript-eslint/no-namespace */ - -import type * as grpc from '@midwayjs/grpc' - -/* package helloworld start */ -export namespace helloworld { - export interface Greeter { - // Sends a greeting - sayHello(data: HelloRequest): Promise - sayError(data: HelloRequest): Promise - sayHello3(data: HelloRequest): Promise - } - /** - * Greeter client interface - */ - export interface GreeterClient { - // Sends a greeting - sayHello(options?: grpc.IClientOptions): grpc.IClientUnaryService - sayError(options?: grpc.IClientOptions): grpc.IClientUnaryService - sayHello3(options?: grpc.IClientOptions): grpc.IClientUnaryService - } - export interface HelloRequest { - id?: number - name?: string - } - export interface HelloReply { - id?: number - message?: string - traceId?: string - } -} -/* package helloworld end */ diff --git a/packages/otel/test/fixtures/base-app/package.json b/packages/otel/test/fixtures/base-app/package.json deleted file mode 100644 index b9a4ea900..000000000 --- a/packages/otel/test/fixtures/base-app/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "base-app", - "version": "1.0.0", - "type": "module", - "imports": { - "#package.json": "../../../package.json", - "##/*": "../../../dist/*", - "#@/*": "../../../test/*" - }, - "dependencies": { - } -} diff --git a/packages/otel/test/fixtures/base-app/src/configuration.ts b/packages/otel/test/fixtures/base-app/src/configuration.ts deleted file mode 100644 index aa070b525..000000000 --- a/packages/otel/test/fixtures/base-app/src/configuration.ts +++ /dev/null @@ -1,94 +0,0 @@ -import assert from 'node:assert' - -import { App, Configuration } from '@midwayjs/core' -import type { Application } from '@mwcp/share' - -import * as SRC from './types/index.js' - - -@Configuration({ - imports: [SRC], -}) -export class AutoConfiguration { - - @App() readonly app: Application - - // test afterThrow() manually - // @SRC.TraceInit({ - // spanName: 'INIT TEST.onConfigLoad', - // }) - // async onConfigLoad(): Promise { - // throw new Error('TraceInit test afterThrow() manually') - // } - - @SRC.TraceInit({ - spanName: 'INIT TEST.onConfigLoad', - }) - async onConfigLoad(): Promise { - void 0 - } - - @SRC.TraceInit({ - spanName: 'INIT TEST.onReady', - before: async (args, decoratorContext) => { - assert(decoratorContext.webApp) - assert(args.length >= 2) - - const attrs = { testInitBefore: 'testInitBefore' } - const events = { ...attrs } - const rootAttrs = { rootInitAttrsBefore: 'rootInitAttrsBefore' } - const rootEvents = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } - }, - after: (args, res, decoratorContext) => { - assert(decoratorContext.webApp) - assert(args.length >= 2) - assert(res === 123n) - - const attrs = { testInitAfter: 'testInitAfter' } - const events = { ...attrs } - const rootAttrs = { rootInitAttrsAfter: 'rootInitAttrsAfter' } - const rootEvents = { ...rootAttrs } - - const { traceService, traceSpan } = decoratorContext - if (traceSpan) { - traceService?.otel.addSpanEventWithError(traceSpan, new Error('testInitAfter')) - } - - return { attrs, events, rootAttrs, rootEvents } - }, - }) - async onReady(): Promise { - // const foo = this.app.getConfig() as unknown - // void foo - return 123n - } - - @SRC.TraceInit({ - spanName: 'INIT TEST.onServerReady', - before: (args, decoratorContext) => { - assert(decoratorContext.webApp) - assert(args.length >= 2) - return void 0 - }, - after: async (args, res, decoratorContext) => { - assert(decoratorContext.webApp) - assert(args.length >= 2) - assert(res === 234n) - return void 0 - }, - }) - async onServerReady(): Promise { - return 234n - } - - - @SRC.TraceInit({ - spanName: 'INIT TEST.onStop', - }) - async onStop(): Promise { - return - } - -} diff --git a/packages/otel/test/fixtures/base-app/src/home.ts b/packages/otel/test/fixtures/base-app/src/home.ts deleted file mode 100644 index d3e274246..000000000 --- a/packages/otel/test/fixtures/base-app/src/home.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { - Controller, - Get, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import type { Context } from '@mwcp/share' - -import { apiBase, apiMethod } from './types/api-test.js' -import { ConfigKey } from './types/lib-types.js' -import type { Config, MiddlewareConfig } from './types/lib-types.js' -import type { RespData } from './types/root.config.js' - - -@Controller(apiBase.root) -export class HomeController { - - @MConfig(ConfigKey.config) protected readonly config: Config - @MConfig(ConfigKey.middlewareConfig) protected readonly mwConfig: MiddlewareConfig - - @Get(apiMethod.root) - async home(ctx: Context): Promise { - const { - cookies, - header, - url, - } = ctx - - const res = { - cookies, - header, - url, - } - return res - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/provider/200.grpc.provider.ts b/packages/otel/test/fixtures/base-app/src/provider/200.grpc.provider.ts deleted file mode 100644 index b592f75e6..000000000 --- a/packages/otel/test/fixtures/base-app/src/provider/200.grpc.provider.ts +++ /dev/null @@ -1,57 +0,0 @@ -import assert from 'node:assert' - -import { GrpcMethod, Init, Inject, MSProviderType, Provider } from '@midwayjs/core' -import { Clients } from '@midwayjs/grpc' -import { type GrpcContext, MConfig } from '@mwcp/share' - -import { helloworld } from '../types/domain.js' -import { Trace, TraceService } from '../types/index.js' -import { TraceAppLogger, TraceLogger } from '../types/lib-index.js' -import { Config, ConfigKey } from '../types/lib-types.js' - -import { GreeterService } from './200s.grpc.service.js' - - -@Provider(MSProviderType.GRPC, { package: 'helloworld' }) -export class Greeter implements helloworld.Greeter { - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly ctx: GrpcContext - @Inject() readonly traceSvc: TraceService - - @Inject() readonly logger: TraceLogger - @Inject() readonly appLogger: TraceAppLogger - - @Inject() readonly greeterSvc: GreeterService - - @Trace() - @GrpcMethod() - async sayHello(req: helloworld.HelloRequest): Promise { - assert(typeof req.id === 'number', 'request.id must be number') - const traceId = this.traceSvc.getTraceId() - const res: helloworld.HelloReply = { - id: req.id, - message: 'Hello ' + req.name, - traceId, - } - return res - } - - @Trace() - @GrpcMethod() - sayError(req: helloworld.HelloRequest): Promise { - assert(typeof req.id === 'number', 'request.id must be number') - throw new Error('Method not implemented.') - } - - @Trace() - @GrpcMethod() - async sayHello3(req: helloworld.HelloRequest): Promise { - const traceId = this.traceSvc.getTraceId() - const res = await this.greeterSvc.sayHello3(req) - res.traceId = traceId - return res - } -} - - diff --git a/packages/otel/test/fixtures/base-app/src/provider/200s.grpc.service.ts b/packages/otel/test/fixtures/base-app/src/provider/200s.grpc.service.ts deleted file mode 100644 index a3f6da63e..000000000 --- a/packages/otel/test/fixtures/base-app/src/provider/200s.grpc.service.ts +++ /dev/null @@ -1,41 +0,0 @@ -import assert from 'node:assert' - -import { GrpcMethod, Init, Inject, Singleton } from '@midwayjs/core' -import { Clients } from '@midwayjs/grpc' -import { type GrpcContext, MConfig } from '@mwcp/share' - -import { helloworld } from '../types/domain.js' -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' - - -@Singleton() -export class GreeterService { - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly ctx: GrpcContext - @Inject() readonly traceSvc: TraceService - - @Inject() readonly grpcClients: Clients - - private greeterService: helloworld.GreeterClient - - @Init() - async init() { - // 赋值一个服务实例 - this.greeterService = this.grpcClients.getService( - 'helloworld.Greeter', - ) - assert(this.greeterService, 'this.greeterService not exists') - } - - - @Trace() - async sayHello3(req: helloworld.HelloRequest): Promise { - // 调用服务 - const res = await this.greeterService.sayHello().sendMessage(req) - return res - } -} - - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/11.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/11.controller.ts deleted file mode 100644 index f7a4c8eb1..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/11.controller.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { TraceService } from '../types/index.js' -import { Config, ConfigKey, Msg } from '../types/lib-types.js' - -import { DefaultComponentService } from './trace.service.js' - - -@Controller(apiBase.TraceDecorator) -export class DefaultComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly svc: DefaultComponentService - @Inject() readonly traceSvc: TraceService - - @Get(`/${apiMethod.id}`) - async traceId(): Promise { - const traceId = this.traceSvc.getTraceId() - await this.svc.hello(Msg.hello) - this.traceSvc.setAttributes(void 0, { foo: 'foo' }) - // ensure child span of svc.hello is sent, to keep span order for unit test validation - // await this.traceSvc.flush() - return traceId - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/110a.decorator-data.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/110a.decorator-data.controller.ts deleted file mode 100644 index 5d359a59f..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/110a.decorator-data.controller.ts +++ /dev/null @@ -1,112 +0,0 @@ -import assert from 'node:assert' - - -import { - Controller, - Get, - Inject, - Param, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import { context } from '@opentelemetry/api' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Attributes, DecoratorTraceData, Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' -import { testConfig } from '../types/root.config.js' - - -@Controller(apiBase.decorator_data) -export class DecoratorDataComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.async}/:id`) - async traceIdAsync(@Param('id') id: string): Promise<`${string}:${string}`> { - const traceId = this.traceSvc.getTraceId() - const ctx2 = context.active() - void ctx2 - const traceCtx = this.traceSvc.getActiveContext() - void traceCtx - await this.traceDecoratorDataAsync(id) - // ensure child span is sent, to keep span order for unit test validation - // await this.traceSvc.flush() - return `${traceId}:${id}` - } - - @Trace() - @Get(`/${apiMethod.sync}/:id`) - async traceIdSync(@Param('id') id: string): Promise<`${string}:${string}`> { - const traceId = this.traceSvc.getTraceId() - this.traceDecoratorDataSync(id) - return `${traceId}:${id}` - } - - - // #region private methods - - @Trace({ - before: (args, decoratorContext) => { - assert(decoratorContext.webApp) - assert(decoratorContext.instanceName === 'DecoratorDataComponentController') - assert(decoratorContext.methodName === 'traceDecoratorDataAsync') - - assert(decoratorContext.traceService) - const traceCtx = decoratorContext.traceService.getActiveContext() - void traceCtx - - const attrs: Attributes = { - args0: args[0], - traceDecoratorDataAsync: 'foo', - } - const events: Attributes = { ...attrs } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } as DecoratorTraceData - }, - after: (args, res, decoratorContext) => { - assert(decoratorContext.instanceName === 'DecoratorDataComponentController') - assert(decoratorContext.methodName === 'traceDecoratorDataAsync') - - const events = { args0: args[0], res } - return { events } - }, - }) - private async traceDecoratorDataAsync(id: string): Promise { - const traceCtx = this.traceSvc.getActiveContext() - void traceCtx - return id + testConfig.testSuffix - } - - - @Trace({ - before: (args, decoratorContext) => { - assert(decoratorContext.instanceName === 'DecoratorDataComponentController') - assert(decoratorContext.methodName === 'traceDecoratorDataSync') - - const attrs: Attributes = { - args0: args[0], - traceDecoratorDataAsync: 'foo', - } - const events: Attributes = { ...attrs } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } as DecoratorTraceData - }, - after: (args, res) => { - const events = { args0: args[0], res } - return { events } - }, - }) - private traceDecoratorDataSync(id: string): string { - return id + testConfig.testSuffix - } - - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/111c.decorator-scope.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/111c.decorator-scope.controller.ts deleted file mode 100644 index 266b38f96..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/111c.decorator-scope.controller.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' - - -@Controller(apiBase.decorator_data) -export class DecoratorScopeComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.simple_scope}`) - async simple(): Promise { - const traceId = this.traceSvc.getTraceId() - await this._simple1() - return traceId - } - - // #region private methods - - @Trace() - private async _simple1(): Promise { - await this._simple1a() - return 'ok' - } - - // #region private methods sub - - @Trace() - private async _simple1a(): Promise { - return 'ok' - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/112a.decorator-scope.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/112a.decorator-scope.controller.ts deleted file mode 100644 index 4aaeb25c4..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/112a.decorator-scope.controller.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import { sleep } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' - - -@Controller(apiBase.decorator_data) -export class DecoratorScopeComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.scope}`) - async simple(): Promise { - const traceId = this.traceSvc.getTraceId() - await this._simple1() - await sleep(1) - await Promise.all([ - this._simple1(), - Promise.resolve().then(async () => { - await sleep(1) // make sure the order of the two methods - return this._simple2() - }), - ]) - return traceId - } - - // #region private methods - - @Trace() - private async _simple1(): Promise { - await this._simple1a() - return 'ok' - } - - @Trace() - private async _simple2(): Promise { - await this._simple2a() - return 'ok' - } - - // #region private methods sub - - @Trace() - private async _simple1a(): Promise { - return 'ok' - } - - @Trace() - private async _simple2a(): Promise { - return 'ok' - } -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/113a.decorator-scope-auto.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/113a.decorator-scope-auto.controller.ts deleted file mode 100644 index 4445e09c9..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/113a.decorator-scope-auto.controller.ts +++ /dev/null @@ -1,115 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import { sleep } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { type TraceContext, Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' - - -@Controller(apiBase.decorator_data) -export class DecoratorScopeComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.trace_auto_scope}`) - async simple(): Promise { - const traceId = this.traceSvc.getTraceId() - const opts1: InputOptions = { } - const opts2: InputOptions = { } - await this._simple1(opts1) - await Promise.all([ - this._simple1(opts1), - Promise.resolve().then(async () => { - await sleep(1) // make sure the order of the two methods - return this._simple2(opts2) - }), - ]) - return traceId - } - - // #region private methods - - @Trace({ - before: ([input], ctx) => { - const { traceContext } = ctx - assert(traceContext) - input.traceContext = traceContext - return null - }, - }) - private async _simple1(input: InputOptions): Promise { - assert(input.traceContext, 'input.traceScope not assigned by before()') - await this._simple1a(input) - return 'ok' - } - - @Trace({ - before: ([input], ctx) => { - const { traceContext } = ctx - assert(traceContext) - input.traceContext = traceContext - return null - }, - }) - private async _simple2(input: InputOptions): Promise { - assert(input.traceContext, 'input.traceScope not assigned by before()') - await this._simple2a(input) - return 'ok' - } - - // #region private methods sub - - @Trace({ - before: ([input], ctx) => { - const { traceContext } = ctx - assert(traceContext) - input.traceContext = traceContext - return null - }, - after: ([input], _res, ctx) => { - const { traceContext } = ctx - assert(input.traceContext === traceContext) - return void 0 - }, - }) - private async _simple1a(input: InputOptions): Promise { - assert(input.traceContext, 'input.traceScope not assigned by before()') - return 'ok' - } - - @Trace({ - before: ([input], ctx) => { - const { traceContext } = ctx - assert(traceContext) - input.traceContext = traceContext - return null - }, - after: ([input], _res, ctx) => { - const { traceContext } = ctx - assert(traceContext) - assert(input.traceContext = traceContext) - return null - }, - }) - private async _simple2a(input: InputOptions): Promise { - assert(input.traceContext, 'input.traceScope not assigned by before()') - return 'ok' - } -} - - -interface InputOptions { - traceContext?: TraceContext | undefined - [key: PropertyKey]: unknown -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/12.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/12.controller.ts deleted file mode 100644 index e6a3927f0..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/12.controller.ts +++ /dev/null @@ -1,42 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey, Msg } from '../types/lib-types.js' - -import { DefaultComponentService } from './trace.service.js' - - -@Controller(apiBase.TraceDecorator) -export class DefaultComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly svc: DefaultComponentService - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.id2}`) - async traceId2(): Promise { - const traceId = this.traceSvc.getTraceId() - this.traceSvc.setAttributes(void 0, { bar: 'bar' }) - const msg = await this.svc.hello(Msg.hello) - assert(msg) - - const msg2 = this.svc.helloSync(Msg.hello) - assert(typeof msg2 === 'string') - assert(msg2) - - // await this.traceSvc.flush() - return traceId - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/120a.trace-log.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/120a.trace-log.controller.ts deleted file mode 100644 index f56ac96ab..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/120a.trace-log.controller.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import { sleep } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { DecoratorTraceData, Trace, TraceLog, TraceService } from '../types/index.js' -import { Attributes, Config, ConfigKey } from '../types/lib-types.js' - - -@Controller(apiBase.trace_log) -export class TraceLogComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.hello}`) - async hello(): Promise { - const traceId = this.traceSvc.getTraceId() - await this._simple1('foo') - await sleep(1) // make sure the order of the two methods - this._simple2('bar') - return traceId - } - - // #region private methods - - @TraceLog({ - before: async ([input], { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } as DecoratorTraceData - }, - after: ([input], res, { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - private async _simple1(input: string): Promise { - return input - } - - @TraceLog({ - before: ([input], { instanceName, methodName }) => { - const events: Attributes = { - args0: input, - instanceName, - methodName, - } - return { events } as DecoratorTraceData - }, - after: ([input], res, { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - private _simple2(input: string): string { - return input - } -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/120c.decorator-data-mix.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/120c.decorator-data-mix.controller.ts deleted file mode 100644 index af3c60424..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/120c.decorator-data-mix.controller.ts +++ /dev/null @@ -1,85 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, - Param, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Attributes, DecoratorTraceData, Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' -import { testConfig } from '../types/root.config.js' - - -@Controller(apiBase.decorator_data) -export class DecoratorDataComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.mix_on_async}/:id`) - async mixOnAsync(@Param('id') id: string): Promise<`${string}:${string}`> { - const traceId = this.traceSvc.getTraceId() - await this._mixOnAsync(id) - return `${traceId}:${id}` - } - - @Trace() - @Get(`/${apiMethod.mix_on_sync}/:id`) - async mixOnSync(@Param('id') id: string): Promise<`${string}:${string}`> { - const traceId = this.traceSvc.getTraceId() - this._MixOnSync(id) - return `${traceId}:${id}` - } - - // #region private methods - - - // mix async and sync decorator's callback on async method - @Trace({ - before: async (args) => { - const attrs: Attributes = { - args0: args[0], - traceDecoratorDataAsync: 'foo', - } - const events: Attributes = { ...attrs } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } - }, - after: (args, res) => { - const events = { args0: args[0], res } - return { events } - }, - }) - private async _mixOnAsync(id: string): Promise { - return id + testConfig.testSuffix - } - - // mix async and sync decorator's callback on sync method - // should throw error according to the decorator's callback before() return Promise - @Trace({ - before: async (args) => { - const attrs: Attributes = { - args0: args[0], - traceDecoratorDataAsync: 'foo', - } - const events: Attributes = { ...attrs } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } - }, - }) - private _MixOnSync(id: string): string { - return id + testConfig.testSuffix - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/121a.trace-log.error.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/121a.trace-log.error.controller.ts deleted file mode 100644 index 9e7441793..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/121a.trace-log.error.controller.ts +++ /dev/null @@ -1,125 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import { sleep } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { DecoratorTraceData, Trace, TraceLog, TraceService } from '../types/index.js' -import { Attributes, Config, ConfigKey } from '../types/lib-types.js' - - -@Controller(apiBase.trace_log) -export class TraceLogComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.error}`) - async error(): Promise { - const traceId = this.traceSvc.getTraceId() - try { - await this._simple1('foo') - } - catch (ex) { - assert(ex instanceof Error) - assert(ex.message === 'foo-error') - - await sleep(1) // make sure the order of the two methods - - try { - this._simple2('bar') - } - catch (ex2) { - assert(ex2 instanceof Error) - assert(ex2.message === 'bar-error') - - return traceId - } - } - - assert(false, 'Should not run here') - } - - @Trace() - @Get(`/${apiMethod.error_no_capture}`) - async errorNoCapture(): Promise { - const traceId = this.traceSvc.getTraceId() - await this._simple1('foo') - return traceId - } - - - // #region private methods - - @TraceLog({ - before: async ([input], { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } as DecoratorTraceData - }, - after: ([input], res, { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - private async _simple1(input: string): Promise { - if (input === 'foo') { - throw new Error('foo-error') - } - return input - } - - @TraceLog({ - before: ([input], { instanceName, methodName }) => { - const events: Attributes = { - args0: input, - instanceName, - methodName, - } - return { events } as DecoratorTraceData - }, - after: ([input], res, { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - private _simple2(input: string): string { - if (input === 'bar') { - throw new Error('bar-error') - } - return input - } -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/122a.trace-singleton.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/122a.trace-singleton.controller.ts deleted file mode 100644 index fe2bf9c79..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/122a.trace-singleton.controller.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { Context } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' - -import { TraceSingletonService } from './122b.trace-singleton.service.js' - - -@Controller(apiBase.trace_singleton) -export class TraceController { - - @Inject() readonly traceSvc: TraceService - @Inject() readonly svc: TraceSingletonService - @Inject() readonly ctx: Context - - @Trace() - @Get(`/${apiMethod.home}`) - async home(): Promise { - const traceId = this.traceSvc.getTraceId() - await this.svc.home({ input: 'hello', webContext: this.ctx }) - return traceId - } - - @Trace() - @Get(`/${apiMethod.hello}`) - async hello(): Promise { - const traceId = this.traceSvc.getTraceId() - await this.svc.hello2({ input: 'hello2' }, this.ctx) - return traceId - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/122b.trace-singleton.service.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/122b.trace-singleton.service.ts deleted file mode 100644 index 84e1dbbc7..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/122b.trace-singleton.service.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* eslint-disable @typescript-eslint/await-thenable */ -import assert from 'node:assert' - -import { Singleton } from '@midwayjs/core' -import { Context } from '@mwcp/share' - -import { Trace } from '../types/index.js' - - -@Singleton() -export class TraceSingletonService { - - @Trace({ - before([options], decoratorContext) { - assert(decoratorContext) - assert(decoratorContext.webContext) - assert(typeof decoratorContext.webContext.getApp === 'function') - assert(decoratorContext.traceService) - - assert(options) - assert(options.webContext === decoratorContext.webContext) - assert(options.input === 'hello') - options.input += '-modified' - - return void 0 - }, - after: ([options], res, decoratorContext) => { - assert(decoratorContext) - assert(decoratorContext.webContext) - assert(typeof decoratorContext.webContext.getApp === 'function') - assert(decoratorContext.traceService) - - assert(options) - assert(options.webContext === decoratorContext.webContext) - assert(options.input.endsWith('-modified')) - assert(options.input === res) - - return void 0 - }, - }) - async home(options: InputOptions): Promise { - assert(typeof options.webContext?.getApp === 'function') - assert(options.input.endsWith('-modified'), options.input) - assert(options.webContext.host) - const ret = await options.input - return ret - } - - @Trace({ - before: ([options, ctx], decoratorContext) => { - assert(decoratorContext) - assert(decoratorContext.webContext) - assert(typeof decoratorContext.webContext.getApp === 'function') - assert(decoratorContext.traceService) - - assert(options) - assert(! options.webContext) - assert(options.input === 'hello2') - options.input += '-modified' - assert(! options.webContext) - assert(ctx === decoratorContext.webContext) - - return void 0 - }, - after: ([options, ctx], res, decoratorContext) => { - assert(decoratorContext) - assert(decoratorContext.webContext) - assert(typeof decoratorContext.webContext.getApp === 'function') - assert(decoratorContext.traceService) - - assert(options) - assert(! options.webContext) - assert(options.input.endsWith('-modified')) - assert(options.input === res) - assert(ctx === decoratorContext.webContext) - - return void 0 - }, - }) - async hello2(options: InputOptions, ctx: Context): Promise { - assert(typeof ctx.getApp === 'function') - assert(options.input.endsWith('-modified'), options.input) - assert(! options.webContext) - - assert(ctx.host) - const ret = options.input - return ret - } -} - -interface InputOptions { - input: string - webContext?: Context -} diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/123a.trace-cb-this.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/123a.trace-cb-this.controller.ts deleted file mode 100644 index 61227a995..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/123a.trace-cb-this.controller.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { Context } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' - -import { TraceSingletonThisService } from './123b.trace-cb-this.service.js' - - -@Controller(apiBase.trace_this) -export class TraceThisController { - - @Inject() readonly traceSvc: TraceService - @Inject() readonly svc: TraceSingletonThisService - @Inject() readonly ctx: Context - - @Trace() - @Get(`/${apiMethod.home}`) - async home(): Promise { - const traceId = this.traceSvc.getTraceId() - await this.svc.home({ input: 'hello', webContext: this.ctx }) - return traceId - } - - @Trace() - @Get(`/${apiMethod.hello}`) - async hello(): Promise { - const traceId = this.traceSvc.getTraceId() - this.svc.hello2({ input: 'hello2' }, this.ctx) - return traceId - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/123b.trace-cb-this.service.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/123b.trace-cb-this.service.ts deleted file mode 100644 index b53002564..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/123b.trace-cb-this.service.ts +++ /dev/null @@ -1,97 +0,0 @@ -/* eslint-disable @typescript-eslint/await-thenable */ -import assert from 'node:assert' - -import { Singleton } from '@midwayjs/core' -import { Context } from '@mwcp/share' - -import { Trace } from '../types/index.js' - - -@Singleton() -export class TraceSingletonThisService { - foo = 1 - - @Trace({ - before([options], decoratorContext) { - assert(this instanceof TraceSingletonThisService) - assert(this === decoratorContext.instance) - assert(this.foo === 1) - this.foo += 1 - - assert(options) - assert(options.webContext === decoratorContext.webContext) - assert(options.input === 'hello') - options.input += '-modified' - - return void 0 - }, - after([options], res, decoratorContext) { - assert(this instanceof TraceSingletonThisService) - assert(this === decoratorContext.instance) - assert(this.foo === 2) - this.foo = 1 - - assert(options) - assert(options.webContext === decoratorContext.webContext) - assert(options.input.endsWith('-modified')) - assert(options.input === res) - - return void 0 - }, - }) - async home(this: TraceSingletonThisService, options: InputOptions): Promise { - assert(typeof options.webContext?.getApp === 'function') - assert(options.input.endsWith('-modified'), options.input) - assert(options.webContext.host) - const ret = await options.input - return ret - } - - @Trace({ - before([options, ctx], decoratorContext) { - assert(this instanceof TraceSingletonThisService) - assert(this === decoratorContext.instance) - assert(this.foo === 1) - - assert(options) - assert(! options.webContext) - assert(options.input === 'hello2') - options.input += '-modified' - assert(! options.webContext) - assert(ctx === decoratorContext.webContext) - - return void 0 - }, - after([options, ctx], res, decoratorContext) { - assert(this instanceof TraceSingletonThisService) - assert(this === decoratorContext.instance) - assert(this.foo === 1) - - assert(decoratorContext.webContext) - assert(typeof decoratorContext.webContext.getApp === 'function') - assert(decoratorContext.traceService) - - assert(options) - assert(! options.webContext) - assert(options.input.endsWith('-modified')) - assert(options.input === res) - assert(ctx === decoratorContext.webContext) - - return void 0 - }, - }) - hello2(this: TraceSingletonThisService, options: InputOptions, ctx: Context): string { - assert(typeof ctx.getApp === 'function') - assert(options.input.endsWith('-modified'), options.input) - assert(! options.webContext) - - assert(ctx.host) - const ret = options.input - return ret - } -} - -interface InputOptions { - input: string - webContext?: Context -} diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/124a.trace-log.afterThrow.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/124a.trace-log.afterThrow.controller.ts deleted file mode 100644 index cd928c1c7..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/124a.trace-log.afterThrow.controller.ts +++ /dev/null @@ -1,140 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import { sleep } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { DecoratorTraceData, Trace, TraceLog, TraceService } from '../types/index.js' -import { Attributes, Config, ConfigKey } from '../types/lib-types.js' - - -@Controller(apiBase.trace_log) -export class TraceLogComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.after_throw}`) - async error(): Promise { - const traceId = this.traceSvc.getTraceId() - try { - await this._simple1('foo') - } - catch (ex) { - assert(ex instanceof Error) - assert(ex.message === 'foo-error') - - await sleep(1) // make sure the order of the two methods - - try { - this._simple2('bar') - } - catch (ex2) { - assert(ex2 instanceof Error) - assert(ex2.message === 'bar-error') - - return traceId - } - } - - assert(false, 'Should not run here') - } - - // #region private methods - - @TraceLog({ - afterThrow: async ([input], error, { instanceName, methodName }) => { - void error - const attrs: Attributes = { - args0: input, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - before: async ([input], { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } as DecoratorTraceData - }, - after: ([input], res, { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - private async _simple1(input: string): Promise { - if (input === 'foo') { - throw new Error('foo-error') - } - return input - } - - @TraceLog({ - afterThrow: ([input], error, { instanceName, methodName }) => { - void error - const attrs: Attributes = { - args0: input, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - before: ([input], { instanceName, methodName }) => { - const events: Attributes = { - args0: input, - instanceName, - methodName, - } - return { events } as DecoratorTraceData - }, - after: ([input], res, { instanceName, methodName }) => { - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - private _simple2(input: string): string { - if (input === 'bar') { - throw new Error('bar-error') - } - return input - } -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/125a.trace-log-mix.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/125a.trace-log-mix.controller.ts deleted file mode 100644 index 6ce3de2c3..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/125a.trace-log-mix.controller.ts +++ /dev/null @@ -1,136 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' -import { sleep } from '@waiting/shared-core' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { DecoratorTraceData, Trace, TraceLog, TraceService, getSpan } from '../types/index.js' -import { Attributes, Config, ConfigKey } from '../types/lib-types.js' - - -@Controller(apiBase.trace_log) -export class TraceLogMixController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.mix}`) - async hello(): Promise { - const activeContext = this.traceSvc.getActiveContext() - void activeContext - const traceId = this.traceSvc.getTraceId() - await this._simple1('foo') - await sleep(1) // make sure the order of the two methods - this._simple2('bar') - return traceId - } - - // #region private methods - - @TraceLog({ - async before([input], { instanceName, methodName }) { - const activeContext = this.traceSvc.getActiveContext() - assert(activeContext) - const activeSpan = getSpan(activeContext) - assert(activeSpan) - // @ts-expect-error - assert(activeSpan.name === 'TraceLogMixController/hello') - - const attrs: Attributes = { - args0: input, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - const rootAttrs: Attributes = { rootAttrs: 'rootAttrs' } - const rootEvents: Attributes = { ...rootAttrs } - - return { attrs, events, rootAttrs, rootEvents } as DecoratorTraceData - }, - after([input], res, { instanceName, methodName }) { - const activeContext = this.traceSvc.getActiveContext() - assert(activeContext) - const activeSpan = getSpan(activeContext) - assert(activeSpan) - // @ts-expect-error - assert(activeSpan.name === 'TraceLogMixController/hello') - - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - private async _simple1(this: TraceLogMixController, input: string): Promise { - const activeContext = this.traceSvc.getActiveContext() - assert(activeContext) - const activeSpan = getSpan(activeContext) - assert(activeSpan) - // @ts-expect-error - assert(activeSpan.name === 'TraceLogMixController/hello') - return input - } - - @TraceLog({ - before([input], { instanceName, methodName }) { - const activeContext = this.traceSvc.getActiveContext() - assert(activeContext) - const activeSpan = getSpan(activeContext) - assert(activeSpan) - // @ts-expect-error - assert(activeSpan.name === 'TraceLogMixController/hello') - - const events: Attributes = { - args0: input, - instanceName, - methodName, - } - return { events } as DecoratorTraceData - }, - after([input], res, { instanceName, methodName }) { - const activeContext = this.traceSvc.getActiveContext() - assert(activeContext) - const activeSpan = getSpan(activeContext) - assert(activeSpan) - // @ts-expect-error - assert(activeSpan.name === 'TraceLogMixController/hello') - - const attrs: Attributes = { - args0: input, - res, - } - const events: Attributes = { - ...attrs, - instanceName, - methodName, - } - return { events } - }, - }) - private _simple2(this: TraceLogMixController, input: string): string { - const activeContext = this.traceSvc.getActiveContext() - assert(activeContext) - const activeSpan = getSpan(activeContext) - assert(activeSpan) - // @ts-expect-error - assert(activeSpan.name === 'TraceLogMixController/hello') - - return input - } -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/13.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/13.controller.ts deleted file mode 100644 index dd8008258..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/13.controller.ts +++ /dev/null @@ -1,41 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey, Msg } from '../types/lib-types.js' - -import { DefaultComponentService } from './trace.service.js' - - -@Controller(apiBase.TraceDecorator) -export class DefaultComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly svc: DefaultComponentService - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.decorator_arg}`) - async arg(): Promise { - const traceId = this.traceSvc.getTraceId() - const rnd = Math.random() - const msg = await this.svc.testArg(rnd) - assert(msg) - const msg2 = this.svc.helloSync(Msg.hello) - assert(msg2) - - // await this.traceSvc.flush() - const ret = `${traceId}:${rnd}` - return ret - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/14.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/14.controller.ts deleted file mode 100644 index 548987c1d..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/14.controller.ts +++ /dev/null @@ -1,39 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' - -import { DefaultComponentService } from './trace.service.js' - - -@Controller(apiBase.TraceDecorator) -export class DefaultComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly svc: DefaultComponentService - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.decorator_arg2}`) - async arg2(): Promise { - const traceId = this.traceSvc.getTraceId() - const rnd = Math.round(Math.random() * 100) - const str = 'bar' - const msg = await this.svc.testArg2(rnd, str) - assert(msg) - - const ret = `${traceId}:${rnd}:${str}` - return ret - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/17.route.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/17.route.controller.ts deleted file mode 100644 index f3dbbb2db..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/17.route.controller.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey, Msg } from '../types/lib-types.js' - -import { DefaultComponentService } from './trace.service.js' - - -@Controller(apiBase.route) -export class RouteComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly svc: DefaultComponentService - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.hello}/:id`) - async traceId(): Promise { - const traceId = this.traceSvc.getTraceId() - await this.svc.hello(Msg.hello) - this.traceSvc.setAttributes(void 0, { helloFoo: 'helloFoo' }) - // ensure child span of svc.hello is sent, to keep span order for unit test validation - await this.traceSvc.flush() - return traceId - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/19.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/19.controller.ts deleted file mode 100644 index 43a32304e..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/19.controller.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { TraceService } from '../types/index.js' -import { Config, ConfigKey, Msg } from '../types/lib-types.js' - -import { SingletonService as DefaultComponentService } from './19b.singleton.service.js' - - -@Controller(apiBase.define_scope) -export class DefaultComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly svc: DefaultComponentService - @Inject() readonly traceSvc: TraceService - - @Get(`/${apiMethod.hello}`) - async traceId(): Promise { - const traceId = this.traceSvc.getTraceId() - await this.svc.hello(Msg.hello) - return traceId - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/19b.singleton.service.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/19b.singleton.service.ts deleted file mode 100644 index c046a022d..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/19b.singleton.service.ts +++ /dev/null @@ -1,37 +0,0 @@ -import assert from 'node:assert' - -import { Inject, Singleton } from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' - - -@Singleton() -export class SingletonService { - - @MConfig(ConfigKey.config) readonly config: Config - @Inject() readonly traceSvc: TraceService - - @Trace() - async hello(input: string): Promise { - assert(typeof this.config.enable !== 'undefined') - await this.helloAsync(input) - this.helloSync(input) - return input - } - - @Trace() - async helloAsync(input: string): Promise { - assert(typeof this.config.enable !== 'undefined') - return input - } - - @Trace() - helloSync(input: string): string { - assert(typeof this.config.enable !== 'undefined') - return input - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/trace.controller.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/trace.controller.ts deleted file mode 100644 index 220fc61c5..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/trace.controller.ts +++ /dev/null @@ -1,122 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { Context, MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' -import { TraceAppLogger, TraceLogger } from '../types/lib-index.js' -import { Config, ConfigKey } from '../types/lib-types.js' - -import { DefaultComponentService } from './trace.service.js' - - -@Controller(apiBase.TraceDecorator) -export class DefaultComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly ctx: Context - @Inject() readonly svc: DefaultComponentService - @Inject() readonly traceSvc: TraceService - - @Inject() readonly logger: TraceLogger - @Inject() readonly appLogger: TraceAppLogger - - @Trace() - @Get(`/${apiMethod.disable_trace}`) - async noTrace(): Promise { - const traceId = this.traceSvc.getTraceId() - return traceId // should be empty - } - - @Trace() - @Get(`/${apiMethod.error}`) - async error(): Promise { - try { - await this.svc.error(true) - } - catch (ex) { - if (ex instanceof Error) { - return ex.message - } - throw ex - } - - return 'should not reach here' - } - - @Trace() - @Get(`/${apiMethod.trace_error}`) - async traceError(): Promise { - await this.svc.traceError(true) - return 'should not reach here' - } - - - @Get(`/${apiMethod.log}`) - async log(): Promise { - const traceId = this.traceSvc.getTraceId() - assert(traceId, 'traceId should not be empty') - this.logger.log({ - msg: traceId, - }) - - this.logger.debug({ - msg: traceId, - }) - this.logger.info({ - msg: traceId, - }) - this.logger.warn({ - msg: traceId, - }) - this.logger.error({ - msg: traceId, - }) - this.logger.write({ - msg: traceId, - }) - this.logger.verbose({ - msg: traceId, - }) - return traceId - } - - @Get(`/${apiMethod.appLog}`) - async appLog(): Promise { - const traceId = this.traceSvc.getTraceId() - - this.appLogger.debug(void 0, false) - this.appLogger.debug(traceId, false) - this.appLogger.info(traceId, false) - this.appLogger.warn(traceId, false) - this.appLogger.error(traceId, false) - this.appLogger.write(traceId, false) - this.appLogger.verbose(traceId, false) - - // no event - this.appLogger.log({ - msg: traceId, - }) - this.appLogger.log({ - msg: traceId, - }, this.traceSvc.getRootSpan(this.ctx)) - return traceId - } - - @Get(`/${apiMethod.warn}`) - async warn(): Promise { - const traceId = this.traceSvc.getTraceId() - this.logger.warn({ - traceId, - }) - return traceId - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/trace.decorator/trace.service.ts b/packages/otel/test/fixtures/base-app/src/trace.decorator/trace.service.ts deleted file mode 100644 index 143cabf1c..000000000 --- a/packages/otel/test/fixtures/base-app/src/trace.decorator/trace.service.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* eslint-disable @typescript-eslint/await-thenable */ -import assert from 'node:assert' - -import { Inject, Provide } from '@midwayjs/core' -import { MConfig } from '@mwcp/share' - -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' - - -@Provide() -export class DefaultComponentService { - - @MConfig(ConfigKey.config) readonly config: Config - @Inject() readonly traceSvc: TraceService - - @Trace() - async hello2(input: string): Promise { - assert(typeof this.config.enable !== 'undefined') - const ret = await input - return ret - } - - @Trace({ startActiveSpan: false }) - async hello(input: string): Promise { - assert(typeof this.config.enable !== 'undefined') - const ret = await input - return ret - } - - @Trace({ startActiveSpan: false }) - helloSync(input: string): string { - assert(typeof this.config.enable !== 'undefined') - return input - } - - @Trace({ - spanName: args => `foo-${args[0]}`, - }) - testArgSync(input: number): string { - return input.toString() - } - - @Trace({ - startActiveSpan: false, - spanName: args => `foo-${args[0]}`, - }) - async testArg(input: number): Promise { - const ret = await input.toString() - return ret - } - - @Trace({ - spanName: ([v1, v2]) => `foo-${v1 + 1}-${v2}`, - }) - async testArg2(v1: number, v2: string): Promise { - void v2 - const ret = await v1.toString() - return ret - } - - async error(triggerError: boolean): Promise { - if (triggerError) { - throw new Error('debug for DefaultComponentService.error()') - } - return 'OK' - } - - /** Error will be traced cause decorator */ - @Trace() - async traceError(triggerError: boolean): Promise { - if (triggerError) { - throw new Error('debug for DefaultComponentService.error()') - } - return 'OK' - } - -} - diff --git a/packages/otel/test/fixtures/base-app/src/types/api-test.ts b/packages/otel/test/fixtures/base-app/src/types/api-test.ts deleted file mode 100644 index 5b59da9cd..000000000 --- a/packages/otel/test/fixtures/base-app/src/types/api-test.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../api-test.js' - diff --git a/packages/otel/test/fixtures/base-app/src/types/domain.ts b/packages/otel/test/fixtures/base-app/src/types/domain.ts deleted file mode 100644 index d191810b3..000000000 --- a/packages/otel/test/fixtures/base-app/src/types/domain.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export type * from '../../../../domain/helloworld.js' - diff --git a/packages/otel/test/fixtures/base-app/src/types/index.ts b/packages/otel/test/fixtures/base-app/src/types/index.ts deleted file mode 100644 index 3b423e718..000000000 --- a/packages/otel/test/fixtures/base-app/src/types/index.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/index.js' - diff --git a/packages/otel/test/fixtures/base-app/src/types/lib-index.ts b/packages/otel/test/fixtures/base-app/src/types/lib-index.ts deleted file mode 100644 index a776b6f14..000000000 --- a/packages/otel/test/fixtures/base-app/src/types/lib-index.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/lib/index.js' - diff --git a/packages/otel/test/fixtures/base-app/src/types/lib-types.ts b/packages/otel/test/fixtures/base-app/src/types/lib-types.ts deleted file mode 100644 index 0ef106bf2..000000000 --- a/packages/otel/test/fixtures/base-app/src/types/lib-types.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/lib/types.js' - diff --git a/packages/otel/test/fixtures/base-app/src/types/root.config.ts b/packages/otel/test/fixtures/base-app/src/types/root.config.ts deleted file mode 100644 index 1ebbbf75c..000000000 --- a/packages/otel/test/fixtures/base-app/src/types/root.config.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../root.config.js' - diff --git a/packages/otel/test/fixtures/base-app/src/types/util.ts b/packages/otel/test/fixtures/base-app/src/types/util.ts deleted file mode 100644 index 33ba1677a..000000000 --- a/packages/otel/test/fixtures/base-app/src/types/util.ts +++ /dev/null @@ -1,3 +0,0 @@ - -export * from '../../../../../src/lib/util.js' - diff --git a/packages/otel/test/fixtures/base-app/src/util/20a.util.controller.ts b/packages/otel/test/fixtures/base-app/src/util/20a.util.controller.ts deleted file mode 100644 index eb21fee1f..000000000 --- a/packages/otel/test/fixtures/base-app/src/util/20a.util.controller.ts +++ /dev/null @@ -1,57 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, -} from '@midwayjs/core' -import { Context, MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey, HeadersKey } from '../types/lib-types.js' -import { propagateHeader } from '../types/util.js' - - -@Controller(apiBase.util) -export class UtilController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly ctx: Context - @Inject() readonly traceSvc: TraceService - - @Trace() - @Get(`/${apiMethod.propagateHeader}`) - async propagateHeader(): Promise<'OK'> { - const headers = new Headers() - assert(headers) - assert(! headers.get(HeadersKey.TRACE_PARENT_HEADER)) - - headers.set('a', '1') - assert(headers.get('a') === '1') - - const traceCtx = this.traceSvc.getActiveContext() - propagateHeader(traceCtx, headers) - assert(headers) - const traceParent = headers.get(HeadersKey.TRACE_PARENT_HEADER) - assert(traceParent) - - const traceId = this.traceSvc.getTraceId() - const spanId = traceParent.split('-')[1] - assert(spanId === traceId) - - - const headers2 = new Headers() - const txt = 'abc' - headers2.set(HeadersKey.TRACE_PARENT_HEADER, txt) - propagateHeader(traceCtx, headers2) - const id2 = headers2.get(HeadersKey.TRACE_PARENT_HEADER) - assert(id2 === txt) - - return 'OK' - } - - -} - diff --git a/packages/otel/test/fixtures/base-app/src/util/21a.controller.ts b/packages/otel/test/fixtures/base-app/src/util/21a.controller.ts deleted file mode 100644 index 607bf57e7..000000000 --- a/packages/otel/test/fixtures/base-app/src/util/21a.controller.ts +++ /dev/null @@ -1,69 +0,0 @@ -import assert from 'node:assert' - -import { - Controller, - Get, - Inject, - Post, -} from '@midwayjs/core' -import { Context, MConfig } from '@mwcp/share' - -import { apiBase, apiMethod } from '../types/api-test.js' -import { Trace, TraceService } from '../types/index.js' -import { Config, ConfigKey } from '../types/lib-types.js' -import { deleteSpan, getSpan, isSpanEnded } from '../types/util.js' - - -@Controller(apiBase.util) -export class UtilComponentController { - - @MConfig(ConfigKey.config) readonly config: Config - - @Inject() readonly ctx: Context - @Inject() readonly traceSvc: TraceService - - @Trace({ - spanName: '', - }) - @Get(`/${apiMethod.hello}`) - @Post(`/${apiMethod.hello}`) - async simple(): Promise { - const traceId = this.traceSvc.getTraceId() - const traceId2 = this.traceSvc.otel.getTraceId() - assert(traceId, 'traceId should not be empty') - assert(traceId2, 'traceId2 should not be empty') - await this._simple1() - return traceId - } - - // #region private methods - - @Trace({ - spanName: () => '', - }) - private async _simple1(): Promise { - const { span, traceContext } = this.traceSvc.startScopeSpan({ name: 'simple1', scope: this.ctx }) - assert(span) - assert(! isSpanEnded(span)) - - const traceCtx2 = this.traceSvc.getActiveContext() - assert(traceCtx2) - assert(traceCtx2 !== traceContext) - - const span2 = getSpan(traceCtx2) - assert(span2) - assert(span2 !== span) - - const traceCtx3 = deleteSpan(traceCtx2) - const span3 = getSpan(traceCtx3) - assert(! span3, 'span3 should be undefined') - - const span2a = getSpan(traceCtx2) - assert(span2a) - assert(span2a !== span) - - return 'ok' - } - -} - diff --git a/packages/otel/test/fixtures/base-app/tsconfig.json b/packages/otel/test/fixtures/base-app/tsconfig.json deleted file mode 100644 index e3e9c84c9..000000000 --- a/packages/otel/test/fixtures/base-app/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "../../..", - "declarationMap": false, - "strictPropertyInitialization": false - }, - "include": [ - "../../../src/**/*.ts", - "../../../test/**/*.ts" - ], - "exclude": [ - "dist", - "node_modules*", - "test", - "**/*.d.ts", - "**/*.spec.ts" - ] -} diff --git a/packages/otel/test/grpc/200.grpc.test.ts b/packages/otel/test/grpc/200.grpc.test.ts deleted file mode 100644 index 1ca008718..000000000 --- a/packages/otel/test/grpc/200.grpc.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import assert from 'node:assert' -import { join } from 'node:path' - -import { createGRPCConsumer } from '@midwayjs/grpc' -import { fileShortPath, retrieveDirname } from '@waiting/shared-core' - -import { assertJaegerParentSpanArray, assertRootSpan, retrieveTraceInfoFromRemote, sortSpans } from '##/index.js' -import type { helloworld } from '#@/domain/helloworld.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), () => { - describe('should create grpc service in one server', () => { - const id = 1 - const id2 = 2 - const name = 'harry' - - const options = { - package: 'helloworld', - protoPath: join(testConfig.testDir, 'grpc', 'helloworld.proto'), - url: 'localhost:6565', - } - - it('normal', async () => { - const service = await createGRPCConsumer(options) - const res = await service.sayHello({ timeout: 3000 }).sendMessage({ id, name }) - - console.info({ res }) - assert(res.id === id) - assert(res.message === `Hello ${name}`) - - await assertAll(res.traceId) - }) - - it('req2', async () => { - const service = await createGRPCConsumer(options) - const res = await service.sayHello({ timeout: 3000 }).sendMessage({ id, name }) - console.info({ res }) - assert(res.id === id) - assert(res.message === `Hello ${name}`) - await assertAll(res.traceId) - - const res2 = await service.sayHello({ timeout: 3000 }).sendMessage({ id, name }) - console.info({ res2 }) - assert(res2.id === id) - assert(res2.message === `Hello ${name}`) - await assertAll(res2.traceId) - }) - - it('parallel request with same client', async () => { - const service = await createGRPCConsumer(options) - const pms1 = service.sayHello({ timeout: 3000 }).sendMessage({ id, name }) - const pms2 = service.sayHello({ timeout: 3000 }).sendMessage({ id: id2, name }) - - await Promise.all([pms1, pms2]).then(async ([res1, res2]) => { - console.info({ res1, res2 }) - assert(res1.id === id) - assert(res1.message === `Hello ${name}`) - assert(res2.id === id2) - assert(res2.message === `Hello ${name}`) - - await assertAll(res1.traceId) - await assertAll(res2.traceId) - }) - }) - - it('parallel request with different client', async () => { - const service = await createGRPCConsumer(options) - const service2 = await createGRPCConsumer(options) - - const pms1 = service.sayHello({ timeout: 3000 }).sendMessage({ id, name }) - const pms2 = service2.sayHello({ timeout: 3000 }).sendMessage({ id: id2, name }) - - await Promise.all([pms1, pms2]).then(async ([res1, res2]) => { - console.info({ res1, res2 }) - assert(res1.id === id) - assert(res1.message === `Hello ${name}`) - assert(res2.id === id2) - assert(res2.message === `Hello ${name}`) - - await assertAll(res1.traceId) - await assertAll(res2.traceId) - }) - }) - - it('error', async () => { - const service = await createGRPCConsumer(options) - try { - await service.sayError().sendMessage({ id, name }) - } - catch (ex) { - assert(ex instanceof Error) - assert(ex.message.includes('Method not implemented'), ex.message) - return - } - assert(false, 'should throw Error') - }) - - it('request grpc server', async () => { - const service = await createGRPCConsumer(options) - const res = await service.sayHello3().sendMessage({ id: id2, name }) - - console.info({ res }) - assert(res.id === id2) - assert(res.message === `Hello ${name}`) - - await assert3(res.traceId) - }) - - }) -}) - - -async function assertAll(traceId?: string): Promise { - assert(traceId && traceId.length === 32, `traceId: ${traceId}`) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 2) - assert(info) - const [rootSpan, span1] = sortSpans(info.spans) - assert(rootSpan) - assert(span1) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - ]) - - const path = '/helloworld.Greeter/SayHello' - assertRootSpan({ - scheme: 'grpc', - operationName: `RPC ${path}`, - path, - span: rootSpan, - traceId, - tags: { - 'http.method': 'SayHello', - 'http.target': path, - 'http.route': 'unknown', - 'span.kind': 'server', - 'otel.status_code': 'OK', - }, - mergeDefaultTags: false, - mergeDefaultLogs: false, - }) - -} - - -async function assert3(traceId?: string): Promise { - assert(traceId && traceId.length === 32, `traceId: ${traceId}`) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 3) - assert(info) - const [rootSpan, span1, span2] = sortSpans(info.spans) - assert(rootSpan) - assert(span1) - assert(span2) - - assertJaegerParentSpanArray([ - { parentSpan: rootSpan, childSpan: span1 }, - { parentSpan: span1, childSpan: span2 }, - ]) - - const path = '/helloworld.Greeter/SayHello3' - assertRootSpan({ - scheme: 'grpc', - operationName: `RPC ${path}`, - path, - span: rootSpan, - traceId, - tags: { - 'http.method': 'SayHello3', - 'http.target': path, - 'http.route': 'unknown', - 'span.kind': 'server', - 'otel.status_code': 'OK', - }, - mergeDefaultTags: false, - logs: [ - {}, - { event: 'incoming.request.data', 'http.request.body': JSON.stringify({ id: 2, name: 'harry' }, null, 2) }, - {}, - {}, - { - event: 'outgoing.response.data', - 'http.response.body': JSON.stringify({ id: 2, message: 'Hello harry', traceId }, null, 2), - 'http.response.code': 200, - }, - ], - }) - -} - diff --git a/packages/otel/test/grpc/helloworld.proto b/packages/otel/test/grpc/helloworld.proto deleted file mode 100644 index c99c76e1a..000000000 --- a/packages/otel/test/grpc/helloworld.proto +++ /dev/null @@ -1,22 +0,0 @@ -syntax = "proto3"; - -package helloworld; - -service Greeter { - // Sends a greeting - rpc SayHello (HelloRequest) returns (HelloReply) {} - rpc SayError (HelloRequest) returns (HelloReply) {} - rpc SayHello3 (HelloRequest) returns (HelloReply) {} -} - -message HelloRequest { - int32 id = 1; - string name = 2; -} - -message HelloReply { - int32 id = 1; - string message = 2; - string traceId = 3; -} - diff --git a/packages/otel/test/lib/31.isTraceScopeParamType.test.ts b/packages/otel/test/lib/31.isTraceScopeParamType.test.ts deleted file mode 100644 index a69f00ed9..000000000 --- a/packages/otel/test/lib/31.isTraceScopeParamType.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { isTraceScopeParamType } from '##/lib/decorator.helper.base.js' - - -describe(fileShortPath(import.meta.url), function () { - - describe('Should isTraceScopeParamType() work', () => { - it('string', async () => { - const ret = isTraceScopeParamType('foo') - assert(ret) - }) - - it('symbol', async () => { - const ret = isTraceScopeParamType(Symbol('foo')) - assert(ret) - }) - - it('object', async () => { - const scope = { foo: 1 } - const ret = isTraceScopeParamType(scope) - assert(ret) - }) - - it('array', async () => { - const fake: unknown[] = [] - const ret = isTraceScopeParamType(fake) - assert(ret) - }) - - it('undefined', async () => { - const ret = isTraceScopeParamType(void 0) - assert(! ret) - }) - - it('function invalid', async () => { - const obj = { foo: 1 } - const scope = () => { - return obj - } - const ret = isTraceScopeParamType(scope) - assert(! ret) - }) - }) - -}) - diff --git a/packages/otel/test/prepare.mts b/packages/otel/test/prepare.mts deleted file mode 100644 index 8681fd3aa..000000000 --- a/packages/otel/test/prepare.mts +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env tsx -import { dirname, join, sep } from 'node:path' -import { cp, mkdir, rm } from 'node:fs/promises' -import { fileURLToPath } from 'node:url' -import { $ } from '@waiting/shared-core' -import { cd } from 'zx' - -const currentURL = import.meta.url -const currentPath = fileURLToPath(currentURL) -const currentDir = dirname(currentPath) -const currentFileName = currentPath.split(sep).pop() -const rootDir = join(currentDir, '../../..') -const shareSrcDir = join(rootDir, 'packages/share') - -const nodeModulesDir = join(rootDir, 'node_modules') -const mwcpModuleDir = join(nodeModulesDir, '@mwcp') -const shareModuleDir = join(nodeModulesDir, '@mwcp/share') - -console.log({ shareSrcDir, shareModuleDir }) - -cd(shareSrcDir) -// $.verbose = true -await $`npm run build` -await rm(shareModuleDir, { force: true, recursive: true }) -cd(mwcpModuleDir) -await mkdir('share') -const src = 'src' -const dist = 'dist' -const pkg = 'package.json' -await cp(join(shareSrcDir, src), `${shareModuleDir}/${src}`, { recursive: true, force: true }) -await cp(join(shareSrcDir, dist), `${shareModuleDir}/${dist}`, { recursive: true, force: true }) -await cp(join(shareSrcDir, pkg), `${shareModuleDir}/${pkg}`, { force: true }) - diff --git a/packages/otel/test/root.config.ts b/packages/otel/test/root.config.ts deleted file mode 100644 index 3b3b78f46..000000000 --- a/packages/otel/test/root.config.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type { IncomingHttpHeaders } from 'node:http' -import { join } from 'node:path' - -import type { ValidateService } from '@midwayjs/validate' -import type { Application, IMidwayContainer, JsonResp } from '@mwcp/share' -import { genCurrentDirname } from '@waiting/shared-core' -import type { Response, SuperTest, Test } from 'supertest' - - -export const testDir = genCurrentDirname(import.meta.url) -export const baseDir = join(testDir, '..') - -export const CI = !! process.env['CI'] // GithubAction -export const TEST = !! (CI - || process.env['MIDWAY_SERVER_ENV'] === 'unittest' - || process.env['MIDWAY_SERVER_ENV'] === 'local' - || process.env['NODE_ENV'] === 'unittest' - || process.env['NODE_ENV'] === 'local' -) - -export type TestResponse = Response -export type TestRespBody = JsonResp -export interface RespData { - header: IncomingHttpHeaders - url: string - cookies: unknown - // spanInfo: TestSpanInfo -} - -export interface TestConfig { - baseDir: string - testDir: string - testAppDir: string - CI: boolean - TEST: boolean - app: Application - container: IMidwayContainer - host: string - httpRequest: SuperTest - validateService: ValidateService - /** - * Validate span info from remote Jaeger - */ - validateSpanInfo: boolean - testSuffix: string -} - -const testAppDir = join(testDir, 'fixtures', 'base-app') -export const testConfig = { - baseDir, - testDir, - testAppDir, - CI, - TEST, - host: '', - httpRequest: {}, - validateSpanInfo: true, - testSuffix: 'FFF', -} as TestConfig - - diff --git a/packages/otel/test/setup.ts b/packages/otel/test/setup.ts deleted file mode 100644 index 3456c680e..000000000 --- a/packages/otel/test/setup.ts +++ /dev/null @@ -1,69 +0,0 @@ -// https://mochajs.org/#global-fixtures -// https://mochajs.org/#root-hook-plugins -import assert from 'node:assert' - -import { close, createApp, createHttpRequest } from '@midwayjs/mock' -import { ValidateService } from '@midwayjs/validate' -import type { Application } from '@mwcp/share' -import type { Suite } from 'mocha' - -import { type TestConfig, testConfig } from './root.config.js' - - -let app: Application - -export async function mochaGlobalSetup(this: Suite) { - app = await createAppInstance() - await updateConfig(app, testConfig) - await updateConfig2(app, testConfig) -} - -export async function mochaGlobalTeardown(this: Suite) { - await clean(app, testConfig) - await close(app) -} - - -/** - * Update testConfig in place - */ -async function createAppInstance(): Promise { - try { - app = await createApp(testConfig.testAppDir) as Application - } - catch (ex) { - console.error('createApp error:', ex) - throw ex - } - - assert(app, 'app not exists') - - const middlewares = app.getMiddleware().getNames() - console.info({ middlewares }) - - return app - // https://midwayjs.org/docs/testing -} - -async function updateConfig(mockApp: Application, config: TestConfig): Promise { - config.app = mockApp - config.httpRequest = createHttpRequest(mockApp) - - assert(config.httpRequest, 'httpRequest not exists') - const { url } = config.httpRequest.get('/') - config.host = url - - config.container = mockApp.getApplicationContext() - config.validateService = await config.container.getAsync(ValidateService) - // const svc = await testConfig.container.getAsync(TaskQueueService) -} - -async function updateConfig2(mockApp: Application, config: TestConfig): Promise { - void mockApp - void config -} - -async function clean(mockApp: Application, config: TestConfig): Promise { - void mockApp - void config -} diff --git a/packages/otel/test/tracing.js.example b/packages/otel/test/tracing.js.example deleted file mode 100644 index 3783e51a3..000000000 --- a/packages/otel/test/tracing.js.example +++ /dev/null @@ -1,42 +0,0 @@ -const process = require('process') - -const opentelemetry = require('@opentelemetry/sdk-node') -const { Resource } = require('@opentelemetry/resources'); -const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions') - - -const { name, version } = require('./package.json') -// normilize service name for ali SLS -const serviceName = name ? name.replace(/@/g, '').replace(/\//g, '-') : 'my-service' - -const resource = new Resource({ - [SemanticResourceAttributes.SERVICE_NAME]: serviceName, - [SemanticResourceAttributes.SERVICE_VERSION]: version, -}) - -// 初始化一个 open-telemetry 的 SDK -const sdk = new opentelemetry.NodeSDK({ - resource, -}) - - -// 初始化 SDK,成功启动之后,再启动 Midway 框架 -sdk.start() -// Bootstrap.configure().run() - -// 在进程关闭时,同时关闭数据采集 -process.on('SIGTERM', () => { - shutdown() -}) - -process.on('exit', () => { - shutdown() -}) - -function shutdown() { - sdk.shutdown() - .then(() => console.log('Tracing terminated')) - .catch((error) => console.log('Error terminating tracing', error)) - .finally(() => process.exit(0)); -} - diff --git a/packages/otel/test/tsconfig.json b/packages/otel/test/tsconfig.json deleted file mode 100644 index cfbe091fd..000000000 --- a/packages/otel/test/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": { - "noEmit": true, - "noImplicitAny": false, - "noImplicitThis": false, - "noPropertyAccessFromIndexSignature": false, - "noUnusedLocals": false, - "rootDir": ".." - }, - "include": [ - "../src/", - "." - ] -} diff --git a/packages/otel/test/util/20.util.test.ts b/packages/otel/test/util/20.util.test.ts deleted file mode 100644 index 1be113daa..000000000 --- a/packages/otel/test/util/20.util.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { truncateString } from '##/lib/util.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - describe('should propagateHeader() work', () => { - const path = `${apiBase.util}/${apiMethod.propagateHeader}` - - it('common', async () => { - const { httpRequest } = testConfig - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - assert(resp.text === 'OK') - }) - }) - - describe('should truncateString() work', () => { - const str = 'abcdefg' - - it('common', async () => { - const ret = truncateString(str) - assert(ret === str) - }) - - it('common', async () => { - const ret = truncateString(str, 1) - assert(ret === 'a... LENGTH: 7 bytes') - }) - }) - -}) - diff --git a/packages/otel/test/util/21.addSpanEventWithIncomingRequestData.test.ts b/packages/otel/test/util/21.addSpanEventWithIncomingRequestData.test.ts deleted file mode 100644 index 1c5df7ee2..000000000 --- a/packages/otel/test/util/21.addSpanEventWithIncomingRequestData.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import assert from 'node:assert/strict' - -import { SEMATTRS_HTTP_METHOD, SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions' -import { fileShortPath } from '@waiting/shared-core' - -import { - AssertsOptions, - AttrNames, assertRootSpan, assertsSpan, - retrieveTraceInfoFromRemote, sortSpans, -} from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - - const path = `${apiBase.util}/${apiMethod.hello}` - - it(`Should GET ${path} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest.get(`${path}?foo=1`) - - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 3) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assert(rootSpan.spanID === span1.references[0]?.spanID) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP GET ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - }, - logs: [ - {}, - { - [AttrNames.Http_Request_Query]: JSON.stringify({ foo: '1' }, null, 2), - }, - {}, - {}, - {}, - ], - }) - }) - - it(`Should POST ${path} work`, async () => { - const { httpRequest, testSuffix } = testConfig - - const resp = await httpRequest - .post(path) - .send({ foo: '1' }) - - assert(resp.ok, resp.text) - const traceId = resp.text - assert(traceId) - - const [info] = await retrieveTraceInfoFromRemote(traceId, 3) - assert(info) - const { spans } = info - const [rootSpan, span1] = sortSpans(spans) - assert(rootSpan) - assert(span1) - - assert(rootSpan.spanID === span1.references[0]?.spanID) - - assertRootSpan({ - path, - span: rootSpan, - traceId, - operationName: `HTTP POST ${path}`, - tags: { - [SEMATTRS_HTTP_TARGET]: `${path}`, - [SEMATTRS_HTTP_ROUTE]: `${path}`, - }, - logs: [ - {}, - { - [AttrNames.Http_Request_Body]: JSON.stringify({ foo: '1' }, null, 2), - }, - {}, - {}, - {}, - ], - }) - - }) -}) - - diff --git a/packages/otel/test/util/22.retrieveTraceparentFromHeader.test.ts b/packages/otel/test/util/22.retrieveTraceparentFromHeader.test.ts deleted file mode 100644 index 0517bd11c..000000000 --- a/packages/otel/test/util/22.retrieveTraceparentFromHeader.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import type { Traceparent } from '##/index.js' -import { retrieveTraceparentFromHeader } from '##/index.js' - - -describe(fileShortPath(import.meta.url), function () { - describe('retrieveTraceparentFromHeader()', () => { - const ver = '00' - const id = '0af7651916cd43dd8448eb211c80319c' - const pid = 'b7ad6b7169203331' - const flag = '01' - - it('falsy', async () => { - const headers = new Headers() - const traceparent = retrieveTraceparentFromHeader(headers) - assert(! traceparent) - }) - - it('headers', async () => { - const headers = new Headers() - - headers.set('traceparent', `${ver}-${id}-${pid}-${flag}`) - const traceparent = retrieveTraceparentFromHeader(headers) - assert(traceparent) - assert(traceparent.version === ver) - assert(traceparent.traceId === id) - assert(traceparent.parentId === pid) - assert(traceparent.traceFlags === flag) - }) - - it('object', async () => { - const headers = { - traceparent: `${ver}-${id}-${pid}-${flag}`, - } - const traceparent = retrieveTraceparentFromHeader(headers) - assert(traceparent) - assert(traceparent.version === ver) - assert(traceparent.traceId === id) - assert(traceparent.parentId === pid) - assert(traceparent.traceFlags === flag) - }) - - }) -}) - diff --git a/packages/otel/test/util/23.retrieveTraceInfoFromRemote.test.ts b/packages/otel/test/util/23.retrieveTraceInfoFromRemote.test.ts deleted file mode 100644 index 431caf548..000000000 --- a/packages/otel/test/util/23.retrieveTraceInfoFromRemote.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath } from '@waiting/shared-core' - -import { retrieveTraceInfoFromRemote, retrieveTraceparentFromHeader } from '##/index.js' -import { apiBase, apiMethod } from '#@/api-test.js' -import { testConfig } from '#@/root.config.js' - - -describe(fileShortPath(import.meta.url), function () { - describe('retrieveTraceInfoFromRemote()', () => { - const path = `${apiBase.util}/${apiMethod.propagateHeader}` - - it('common', async () => { - const { httpRequest } = testConfig - - const resp = await httpRequest.get(path) - assert(resp.ok, resp.text) - assert(resp.text === 'OK') - - const traceparent = retrieveTraceparentFromHeader(resp.headers as Headers) - assert(traceparent) - const txt = `${traceparent.version}-${traceparent.traceId}-${traceparent.parentId}-${traceparent.traceFlags}` - const info = await retrieveTraceInfoFromRemote(txt) - assert(info) - }) - - }) -}) - diff --git a/packages/otel/test/z/903.share.test.ts b/packages/otel/test/z/903.share.test.ts deleted file mode 100644 index 33ddb4d85..000000000 --- a/packages/otel/test/z/903.share.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import assert from 'node:assert/strict' - -import { fileShortPath, getNpmPkgViewFromRegistry } from '@waiting/shared-core' - - -describe(fileShortPath(import.meta.url), function () { - - describe('should work', () => { - it('getNpmPkgViewFromRegistry()', async () => { - const pkgName = '@mwcp/otel' - const info = await getNpmPkgViewFromRegistry(pkgName) - assert(info?.name === pkgName) - - const info2 = await getNpmPkgViewFromRegistry(pkgName) - assert(info2?.name === pkgName) - }) - }) - -}) - diff --git a/packages/otel/tsconfig.json b/packages/otel/tsconfig.json deleted file mode 100644 index 8890df64a..000000000 --- a/packages/otel/tsconfig.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "./tsconfig.base.json", - "compilerOptions": { - "rootDir": "src" - } -}