From ef5712fd3b279b0e80494322231232047b06f9e6 Mon Sep 17 00:00:00 2001 From: Mayur Kale Date: Fri, 7 Jun 2019 11:00:33 -0700 Subject: [PATCH] upgrade gts to 1.0 (#572) --- packages/opencensus-core/package-lock.json | 224 ++-- packages/opencensus-core/package.json | 2 +- .../src/common/console-logger.ts | 18 +- .../opencensus-core/src/common/noop-logger.ts | 2 +- .../opencensus-core/src/common/time-util.ts | 10 +- .../opencensus-core/src/common/validations.ts | 27 +- .../opencensus-core/src/common/version.ts | 5 +- .../src/exporters/console-exporter.ts | 39 +- .../src/exporters/exporter-buffer.ts | 12 +- .../opencensus-core/src/exporters/types.ts | 12 +- packages/opencensus-core/src/index.ts | 31 +- .../opencensus-core/src/internal/cls-ah.ts | 35 +- packages/opencensus-core/src/internal/cls.ts | 11 +- packages/opencensus-core/src/internal/util.ts | 6 +- .../src/metrics/cumulative/cumulative.ts | 67 +- .../metrics/cumulative/derived-cumulative.ts | 100 +- .../src/metrics/cumulative/types.ts | 2 +- .../metrics/export/base-metric-producer.ts | 2 +- .../metrics/export/metric-producer-manager.ts | 4 +- .../src/metrics/export/types.ts | 12 +- .../src/metrics/gauges/derived-gauge.ts | 71 +- .../src/metrics/gauges/gauge.ts | 55 +- .../src/metrics/gauges/types.ts | 2 +- .../src/metrics/metric-component.ts | 4 +- .../src/metrics/metric-registry.ts | 203 ++-- .../opencensus-core/src/metrics/metrics.ts | 8 +- packages/opencensus-core/src/metrics/types.ts | 14 +- packages/opencensus-core/src/metrics/utils.ts | 38 +- .../opencensus-core/src/resource/resource.ts | 66 +- .../opencensus-core/src/resource/types.ts | 2 +- .../src/stats/bucket-boundaries.ts | 30 +- .../src/stats/metric-producer.ts | 6 +- .../opencensus-core/src/stats/metric-utils.ts | 31 +- .../opencensus-core/src/stats/recorder.ts | 87 +- packages/opencensus-core/src/stats/stats.ts | 74 +- packages/opencensus-core/src/stats/types.ts | 72 +- packages/opencensus-core/src/stats/view.ts | 150 ++- .../src/tags/propagation/binary-serializer.ts | 23 +- .../src/tags/propagation/text-format.ts | 25 +- .../src/tags/propagation/variant-encoding.ts | 4 +- packages/opencensus-core/src/tags/tag-map.ts | 28 +- packages/opencensus-core/src/tags/tagger.ts | 16 +- packages/opencensus-core/src/tags/types.ts | 2 +- .../opencensus-core/src/tags/validation.ts | 15 +- .../opencensus-core/src/trace/config/types.ts | 14 +- .../src/trace/instrumentation/base-plugin.ts | 78 +- .../src/trace/instrumentation/types.ts | 38 +- .../model/no-record/no-record-root-span.ts | 13 +- .../trace/model/no-record/no-record-span.ts | 37 +- .../src/trace/model/root-span.ts | 13 +- .../opencensus-core/src/trace/model/span.ts | 114 +- .../src/trace/model/tracer-base.ts | 103 +- .../opencensus-core/src/trace/model/tracer.ts | 47 +- .../opencensus-core/src/trace/model/types.ts | 32 +- .../src/trace/propagation/noop-propagation.ts | 11 +- .../src/trace/propagation/types.ts | 6 +- .../src/trace/sampler/sampler.ts | 46 +- .../test/test-binary-serializer.ts | 57 +- .../test/test-bucket-boundaries.ts | 4 +- .../test/test-console-exporter.ts | 17 +- .../test/test-console-logger.ts | 3 +- .../opencensus-core/test/test-cumulative.ts | 248 ++-- .../test/test-derived-cumulative.ts | 162 +-- .../test/test-derived-gauge.ts | 242 ++-- .../test/test-exporter-buffer.ts | 40 +- packages/opencensus-core/test/test-gauge.ts | 506 +++++--- .../test/test-metric-component.ts | 17 +- .../test/test-metric-producer-manager.ts | 46 +- .../test/test-metric-producer.ts | 170 +-- .../test/test-metric-registry.ts | 470 ++++---- .../opencensus-core/test/test-metric-utils.ts | 58 +- .../test/test-no-record-root-span.ts | 28 +- .../test/test-no-record-span.ts | 13 +- .../opencensus-core/test/test-recorder.ts | 344 +++--- .../opencensus-core/test/test-resource.ts | 45 +- .../opencensus-core/test/test-root-span.ts | 106 +- packages/opencensus-core/test/test-sampler.ts | 87 +- packages/opencensus-core/test/test-span.ts | 114 +- packages/opencensus-core/test/test-stats.ts | 159 ++- .../opencensus-core/test/test-string-utils.ts | 2 +- packages/opencensus-core/test/test-tag-map.ts | 53 +- packages/opencensus-core/test/test-tagger.ts | 103 +- .../opencensus-core/test/test-text-format.ts | 24 +- .../opencensus-core/test/test-time-util.ts | 9 +- .../opencensus-core/test/test-tracer-base.ts | 259 +++-- packages/opencensus-core/test/test-tracer.ts | 34 +- packages/opencensus-core/test/test-utils.ts | 28 +- .../opencensus-core/test/test-validation.ts | 28 +- .../test/test-variant-encoding.ts | 21 +- packages/opencensus-core/test/test-view.ts | 628 +++++----- .../package-lock.json | 218 ++-- .../opencensus-exporter-instana/package.json | 2 +- .../src/instana.ts | 105 +- .../test/test-instana.ts | 32 +- .../package-lock.json | 216 ++-- .../opencensus-exporter-jaeger/package.json | 2 +- .../src/jaeger-driver/index.ts | 155 ++- .../opencensus-exporter-jaeger/src/jaeger.ts | 57 +- .../test/test-jaeger.ts | 126 +- .../package-lock.json | 212 ++-- .../opencensus-exporter-ocagent/package.json | 2 +- .../src/adapters.ts | 225 ++-- .../src/ocagent.ts | 88 +- .../src/types/google.ts | 22 +- .../src/types/index.ts | 2 +- .../src/types/opencensus.ts | 173 +-- .../src/types/trace-service.ts | 12 +- .../test/test-ocagent.ts | 899 ++++++++------- .../package-lock.json | 227 ++-- .../package.json | 2 +- .../src/prometheus-stats.ts | 76 +- .../test/test-prometheus-stats.ts | 434 ++++--- .../package-lock.json | 227 ++-- .../package.json | 2 +- .../src/common-utils.ts | 74 +- .../src/stackdriver-cloudtrace-utils.ts | 111 +- .../src/stackdriver-cloudtrace.ts | 105 +- .../src/stackdriver-monitoring-utils.ts | 191 ++-- .../src/stackdriver-monitoring.ts | 166 +-- .../src/types.ts | 114 +- .../test/nocks.ts | 118 +- .../test/test-stackdriver-cloudtrace-utils.ts | 236 ++-- .../test/test-stackdriver-cloudtrace.ts | 318 +++--- .../test/test-stackdriver-monitoring-utils.ts | 532 +++++---- .../test/test-stackdriver-monitoring.ts | 55 +- .../package-lock.json | 237 ++-- .../opencensus-exporter-zipkin/package.json | 2 +- .../opencensus-exporter-zipkin/src/zipkin.ts | 80 +- .../test/test-zipkin.ts | 305 ++--- .../package-lock.json | 226 ++-- .../opencensus-exporter-zpages/package.json | 2 +- .../controllers/rpcz.controller.ts | 4 +- .../controllers/statsz.controller.ts | 4 +- .../controllers/traceconfigz.controller.ts | 2 +- .../controllers/tracez.controller.ts | 9 +- .../latency-bucket-boundaries.ts | 52 +- .../page-handlers/rpcz.page-handler.ts | 146 +-- .../page-handlers/statsz.page-handler.ts | 67 +- .../page-handlers/templates-dir.ts | 4 +- .../traceconfigz.page-handler.ts | 32 +- .../page-handlers/tracez.page-handler.ts | 114 +- .../src/zpages-frontend/routes.ts | 16 +- .../opencensus-exporter-zpages/src/zpages.ts | 50 +- .../test/test-zpages.ts | 481 +++++--- .../package-lock.json | 204 ++-- .../package.json | 2 +- .../src/grpc-stats/client-stats.ts | 138 ++- .../src/grpc-stats/common-distributions.ts | 81 +- .../src/grpc-stats/server-stats.ts | 129 ++- .../src/grpc-stats/stats-common.ts | 6 +- .../src/grpc.ts | 441 ++++--- .../src/index.ts | 6 +- .../test/test-grpc.ts | 1013 ++++++++++------- .../package-lock.json | 225 ++-- .../package.json | 2 +- .../src/http-stats.ts | 218 ++-- .../src/http.ts | 275 +++-- .../src/index.ts | 6 +- .../src/types.ts | 19 +- .../test/test-http.ts | 438 ++++--- .../package-lock.json | 225 ++-- .../package.json | 2 +- .../src/http2.ts | 192 ++-- .../test/test-http2.ts | 168 +-- .../package-lock.json | 225 ++-- .../package.json | 2 +- .../src/https.ts | 64 +- .../test/test-https.ts | 318 +++--- .../package-lock.json | 164 +-- .../package.json | 4 +- .../src/ioredis.ts | 42 +- .../test/test-ioredis.ts | 111 +- .../package-lock.json | 227 ++-- .../package.json | 2 +- .../src/mongodb.ts | 125 +- .../test/test-mongodb.ts | 170 +-- .../package-lock.json | 164 +-- .../package.json | 2 +- .../src/redis.ts | 50 +- .../test/test-redis.ts | 82 +- .../opencensus-nodejs-base/package-lock.json | 232 ++-- packages/opencensus-nodejs-base/package.json | 2 +- .../src/trace/config/default-config.ts | 4 +- .../src/trace/constants.ts | 6 +- .../trace/instrumentation/plugin-loader.ts | 50 +- .../src/trace/tracing-base.ts | 32 +- .../load-internal-file-module.ts | 31 +- .../simple-module.ts | 13 +- .../enduser-simple-module-plugin.ts | 13 +- .../load-internal-file-module/index.ts | 3 +- .../src/extra-module.ts | 2 +- .../node_modules/simple-module/index.ts | 2 +- .../test/test-plugin-loader.ts | 67 +- .../test/test-tracing.ts | 117 +- packages/opencensus-nodejs/package-lock.json | 232 ++-- packages/opencensus-nodejs/package.json | 2 +- packages/opencensus-nodejs/src/index.ts | 2 +- .../opencensus-nodejs/src/trace/tracing.ts | 4 +- .../opencensus-nodejs/test/test-tracing.ts | 31 +- .../package-lock.json | 226 ++-- .../opencensus-propagation-b3/package.json | 2 +- .../src/b3-format.ts | 29 +- .../src/validators.ts | 17 +- .../test/test-b3-format.ts | 51 +- .../package-lock.json | 165 +-- .../package.json | 2 +- .../src/binary-format.ts | 29 +- .../test/test-binary-format.ts | 94 +- .../package-lock.json | 226 ++-- .../package.json | 2 +- .../src/jaeger-format.ts | 58 +- .../src/validators.ts | 17 +- .../test/test-jaeger-format.ts | 46 +- .../package-lock.json | 217 ++-- .../package.json | 2 +- .../src/index.ts | 10 +- .../src/stackdriver-format.ts | 29 +- .../src/v1.ts | 36 +- .../test/test-stackdriver-format.ts | 86 +- .../test/test-v1.ts | 72 +- .../package-lock.json | 226 ++-- .../package.json | 2 +- .../src/tracecontext-format.ts | 37 +- .../src/validators.ts | 22 +- .../test/test-tracecontext-format.ts | 92 +- .../package-lock.json | 193 +--- .../opencensus-resource-util/package.json | 2 +- .../opencensus-resource-util/src/constants.ts | 8 +- .../src/detect-resource.ts | 10 +- .../src/resource-utils.ts | 54 +- .../test/test-detect-resource.ts | 392 +++---- 231 files changed, 12285 insertions(+), 10249 deletions(-) diff --git a/packages/opencensus-core/package-lock.json b/packages/opencensus-core/package-lock.json index 35f72a2a4..b4ade73cc 100644 --- a/packages/opencensus-core/package-lock.json +++ b/packages/opencensus-core/package-lock.json @@ -192,9 +192,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -250,11 +250,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, "async-listener": { "version": "0.6.9", "resolved": "https://registry.npmjs.org/async-listener/-/async-listener-0.6.9.tgz", @@ -271,53 +266,6 @@ } } }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -453,16 +401,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -545,8 +483,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -980,37 +917,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -1041,21 +978,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1144,23 +1066,43 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } } }, "intercept-stdout": { @@ -1416,15 +1358,10 @@ "handlebars": "^4.1.2" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2296,6 +2233,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2362,9 +2304,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2397,11 +2339,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2435,9 +2377,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2580,17 +2522,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2828,29 +2770,25 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" }, "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - }, "semver": { "version": "5.7.0", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", @@ -3020,9 +2958,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-core/package.json b/packages/opencensus-core/package.json index 7ed13d74b..024cd0228 100644 --- a/packages/opencensus-core/package.json +++ b/packages/opencensus-core/package.json @@ -60,7 +60,7 @@ "@types/shimmer": "^1.0.1", "@types/uuid": "^3.4.3", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "intercept-stdout": "^0.1.2", "mocha": "^6.1.0", "nyc": "14.1.1", diff --git a/packages/opencensus-core/src/common/console-logger.ts b/packages/opencensus-core/src/common/console-logger.ts index c44ed6dc1..7d09ffa26 100644 --- a/packages/opencensus-core/src/common/console-logger.ts +++ b/packages/opencensus-core/src/common/console-logger.ts @@ -31,7 +31,7 @@ export class ConsoleLogger implements types.Logger { * Constructs a new ConsoleLogger instance * @param options A logger configuration object. */ - constructor(options?: types.LoggerOptions|string|number) { + constructor(options?: types.LoggerOptions | string | number) { let opt: types.LoggerOptions = {}; if (typeof options === 'number') { if (options < 0) { @@ -39,15 +39,17 @@ export class ConsoleLogger implements types.Logger { } else if (options > ConsoleLogger.LEVELS.length) { options = ConsoleLogger.LEVELS.length - 1; } - opt = {level: ConsoleLogger.LEVELS[options]}; + opt = { level: ConsoleLogger.LEVELS[options] }; } else if (typeof options === 'string') { - opt = {level: options}; + opt = { level: options }; } else { opt = options || {}; } if (opt.level) this.level = opt.level; - this.logger = - logDriver({levels: ConsoleLogger.LEVELS, level: opt.level || 'silent'}); + this.logger = logDriver({ + levels: ConsoleLogger.LEVELS, + level: opt.level || 'silent', + }); } /** @@ -96,8 +98,10 @@ export class ConsoleLogger implements types.Logger { * https://github.com/cainus/logdriver/blob/bba1761737ca72f04d6b445629848538d038484a/index.js#L50 * @param options A logger options or strig to logger in console */ -const logger = (options?: types.LoggerOptions|string|number): types.Logger => { +const logger = ( + options?: types.LoggerOptions | string | number +): types.Logger => { return new ConsoleLogger(options); }; -export {logger}; +export { logger }; diff --git a/packages/opencensus-core/src/common/noop-logger.ts b/packages/opencensus-core/src/common/noop-logger.ts index a55f8a8ea..be83184c7 100644 --- a/packages/opencensus-core/src/common/noop-logger.ts +++ b/packages/opencensus-core/src/common/noop-logger.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {Logger} from './types'; +import { Logger } from './types'; /** No-op implementation of Logger */ class NoopLogger implements Logger { diff --git a/packages/opencensus-core/src/common/time-util.ts b/packages/opencensus-core/src/common/time-util.ts index b4beb82a2..609e3fc9e 100644 --- a/packages/opencensus-core/src/common/time-util.ts +++ b/packages/opencensus-core/src/common/time-util.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {Timestamp} from '../metrics/export/types'; +import { Timestamp } from '../metrics/export/types'; const MILLIS_PER_SECOND = 1e3; const NANOS_PER_MILLI = 1e3 * 1e3; @@ -54,9 +54,9 @@ export function getTimestampWithProcessHRTime(): Timestamp { const nanos = hrtimeRefNanos + offsetNanos; if (nanos >= NANOS_PER_SECOND) { - return {seconds: seconds + 1, nanos: nanos % NANOS_PER_SECOND}; + return { seconds: seconds + 1, nanos: nanos % NANOS_PER_SECOND }; } - return {seconds, nanos}; + return { seconds, nanos }; } /** @@ -68,7 +68,7 @@ export function getTimestampWithProcessHRTime(): Timestamp { export function timestampFromMillis(epochMilli: number): Timestamp { return { seconds: Math.floor(epochMilli / MILLIS_PER_SECOND), - nanos: (epochMilli % MILLIS_PER_SECOND) * NANOS_PER_MILLI + nanos: (epochMilli % MILLIS_PER_SECOND) * NANOS_PER_MILLI, }; } @@ -76,5 +76,5 @@ setHrtimeReference(); export const TEST_ONLY = { setHrtimeReference, - resetHrtimeFunctionCache + resetHrtimeFunctionCache, }; diff --git a/packages/opencensus-core/src/common/validations.ts b/packages/opencensus-core/src/common/validations.ts index 01f61257b..cb2d71da3 100644 --- a/packages/opencensus-core/src/common/validations.ts +++ b/packages/opencensus-core/src/common/validations.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {LabelKey, LabelValue} from '../metrics/export/types'; +import { LabelKey, LabelValue } from '../metrics/export/types'; /** * Validates that an object reference passed as a parameter to the calling @@ -38,9 +38,12 @@ export function validateNotNull(reference: T, errorMessage: string): T { * @param errorMessage The exception message to use if the check fails. */ export function validateArrayElementsNotNull( - array: T[], errorMessage: string) { + array: T[], + errorMessage: string +) { const areAllDefined = array.every( - element => element !== null && typeof element !== 'undefined'); + element => element !== null && typeof element !== 'undefined' + ); if (!areAllDefined) { throw new Error(`${errorMessage} elements should not be a NULL`); } @@ -48,7 +51,9 @@ export function validateArrayElementsNotNull( /** Throws an error if any of the map elements is null. */ export function validateMapElementNotNull( - map: Map, errorMessage: string) { + map: Map, + errorMessage: string +) { for (const [key, value] of map.entries()) { if (key == null || value == null) { throw new Error(`${errorMessage} elements should not be a NULL`); @@ -58,11 +63,15 @@ export function validateMapElementNotNull( /** Throws an error if any of the array element present in the map. */ export function validateDuplicateKeys( - keys: LabelKey[], constantLabels: Map) { - const keysAndConstantKeys = - new Set([...keys, ...constantLabels.keys()].map(k => k.key)); - if (keysAndConstantKeys.size !== (keys.length + constantLabels.size)) { + keys: LabelKey[], + constantLabels: Map +) { + const keysAndConstantKeys = new Set( + [...keys, ...constantLabels.keys()].map(k => k.key) + ); + if (keysAndConstantKeys.size !== keys.length + constantLabels.size) { throw new Error( - `The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys`); + `The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys` + ); } } diff --git a/packages/opencensus-core/src/common/version.ts b/packages/opencensus-core/src/common/version.ts index 885c86889..4ca70f6d2 100644 --- a/packages/opencensus-core/src/common/version.ts +++ b/packages/opencensus-core/src/common/version.ts @@ -1,4 +1,3 @@ - /** * Copyright 2018, OpenCensus Authors * @@ -15,9 +14,9 @@ * limitations under the License. */ -type Package = { +interface Package { version: string; -}; +} // Load the package details. Note that the `require` is performed at runtime, // which means package.json will be relative to the location of this file. diff --git a/packages/opencensus-core/src/exporters/console-exporter.ts b/packages/opencensus-core/src/exporters/console-exporter.ts index fd1e724bb..fc4d7009c 100644 --- a/packages/opencensus-core/src/exporters/console-exporter.ts +++ b/packages/opencensus-core/src/exporters/console-exporter.ts @@ -15,11 +15,12 @@ */ import * as loggerTypes from '../common/types'; -import {Measurement, View} from '../stats/types'; -import {TagKey, TagValue} from '../tags/types'; +import { Measurement, View } from '../stats/types'; +import { TagKey, TagValue } from '../tags/types'; import * as modelTypes from '../trace/model/types'; -import {ExporterBuffer} from './exporter-buffer'; -import {Exporter, ExporterConfig, StatsEventListener} from './types'; +import { ExporterBuffer } from './exporter-buffer'; +import * as logger from '../common/console-logger'; +import { Exporter, ExporterConfig, StatsEventListener } from './types'; /** Do not send span data */ export class NoopExporter implements Exporter { @@ -34,8 +35,7 @@ export class NoopExporter implements Exporter { /** Format and sends span data to the console. */ export class ConsoleExporter implements Exporter { /** Buffer object to store the spans. */ - // @ts-ignore - private logger?: loggerTypes.Logger; + logger: loggerTypes.Logger; private buffer: ExporterBuffer; /** @@ -45,7 +45,7 @@ export class ConsoleExporter implements Exporter { */ constructor(config: ExporterConfig) { this.buffer = new ExporterBuffer(this, config); - this.logger = config.logger; + this.logger = config.logger || logger.logger(); } onStartSpan(span: modelTypes.Span) {} @@ -66,17 +66,16 @@ export class ConsoleExporter implements Exporter { * @param spans A list of spans to publish. */ publish(spans: modelTypes.Span[]) { - spans.map((span) => { + spans.map(span => { const ROOT_STR = `RootSpan: {traceId: ${span.traceId}, spanId: ${ - span.id}, name: ${span.name} }`; - const SPANS_STR: string[] = span.spans.map( - (child) => [`\t\t{spanId: ${child.id}, name: ${child.name}}`].join( - '\n')); + span.id + }, name: ${span.name} }`; + const SPANS_STR: string[] = span.spans.map(child => + [`\t\t{spanId: ${child.id}, name: ${child.name}}`].join('\n') + ); const result: string[] = []; - result.push( - ROOT_STR + '\n\tChildSpans:\n' + - `${SPANS_STR.join('\n')}`); + result.push(ROOT_STR + '\n\tChildSpans:\n' + `${SPANS_STR.join('\n')}`); console.log(`${result}`); }); return Promise.resolve(); @@ -90,8 +89,9 @@ export class ConsoleStatsExporter implements StatsEventListener { * @param view registered view */ onRegisterView(view: View) { - console.log(`View registered: ${view.name}, Measure registered: ${ - view.measure.name}`); + console.log( + `View registered: ${view.name}, Measure registered: ${view.measure.name}` + ); } /** * Event called when a measurement is recorded @@ -100,7 +100,10 @@ export class ConsoleStatsExporter implements StatsEventListener { * @param tags The tags to which the value is applied */ onRecord( - views: View[], measurement: Measurement, tags: Map) { + views: View[], + measurement: Measurement, + tags: Map + ) { console.log(`Measurement recorded: ${measurement.measure.name}`); } diff --git a/packages/opencensus-core/src/exporters/exporter-buffer.ts b/packages/opencensus-core/src/exporters/exporter-buffer.ts index f2e0a883f..f4ab7981e 100644 --- a/packages/opencensus-core/src/exporters/exporter-buffer.ts +++ b/packages/opencensus-core/src/exporters/exporter-buffer.ts @@ -48,12 +48,12 @@ export class ExporterBuffer { constructor(exporter: types.Exporter, config: configTypes.BufferConfig) { this.exporter = exporter; this.logger = config.logger || logger.logger(); - this.bufferSize = isNaN(Number(config.bufferSize)) ? - DEFAULT_BUFFER_SIZE : - Number(config.bufferSize); - this.bufferTimeout = isNaN(Number(config.bufferTimeout)) ? - DEFAULT_BUFFER_TIMEOUT : - Number(config.bufferTimeout); + this.bufferSize = isNaN(Number(config.bufferSize)) + ? DEFAULT_BUFFER_SIZE + : Number(config.bufferSize); + this.bufferTimeout = isNaN(Number(config.bufferTimeout)) + ? DEFAULT_BUFFER_TIMEOUT + : Number(config.bufferTimeout); return this; } diff --git a/packages/opencensus-core/src/exporters/types.ts b/packages/opencensus-core/src/exporters/types.ts index 3cac99510..8ff4117a2 100644 --- a/packages/opencensus-core/src/exporters/types.ts +++ b/packages/opencensus-core/src/exporters/types.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {Measurement, View} from '../stats/types'; -import {TagKey, TagValue} from '../tags/types'; +import { Measurement, View } from '../stats/types'; +import { TagKey, TagValue } from '../tags/types'; import * as configTypes from '../trace/config/types'; import * as modelTypes from '../trace/model/types'; @@ -25,7 +25,7 @@ export interface Exporter extends modelTypes.SpanEventListener { * Sends a list of spans to the service. * @param spans A list of spans to publish. */ - publish(spans: modelTypes.Span[]): Promise; + publish(spans: modelTypes.Span[]): Promise; } /** @@ -48,8 +48,10 @@ export interface StatsEventListener { * @param tags The tags to which the value is applied */ onRecord( - views: View[], measurement: Measurement, - tags: Map): void; + views: View[], + measurement: Measurement, + tags: Map + ): void; /** * Starts the exporter that polls Metric from Metrics library and send diff --git a/packages/opencensus-core/src/index.ts b/packages/opencensus-core/src/index.ts index 7aa9c9702..d8d410110 100644 --- a/packages/opencensus-core/src/index.ts +++ b/packages/opencensus-core/src/index.ts @@ -26,7 +26,26 @@ export * from './common/types'; export * from './metrics/types'; export * from './metrics/cumulative/types'; export * from './metrics/gauges/types'; -export {Metric, MetricDescriptor, TimeSeries, MetricDescriptorType, LabelKey, LabelValue, Point as TimeSeriesPoint, DistributionValue, BucketOptions, Bucket as DistributionBucket, SummaryValue, Explicit, Exemplar, Timestamp, Snapshot, ValueAtPercentile, MetricProducerManager, MetricProducer} from './metrics/export/types'; +export { + Metric, + MetricDescriptor, + TimeSeries, + MetricDescriptorType, + LabelKey, + LabelValue, + Point as TimeSeriesPoint, + DistributionValue, + BucketOptions, + Bucket as DistributionBucket, + SummaryValue, + Explicit, + Exemplar, + Timestamp, + Snapshot, + ValueAtPercentile, + MetricProducerManager, + MetricProducer, +} from './metrics/export/types'; // classes @@ -59,12 +78,12 @@ export * from './resource/resource'; // interfaces export * from './stats/types'; -export {TagKey, TagValue, TagMetadata, TagTtl} from './tags/types'; +export { TagKey, TagValue, TagMetadata, TagTtl } from './tags/types'; export * from './resource/types'; // logger import * as logger from './common/console-logger'; -export {logger}; +export { logger }; // version export * from './common/version'; @@ -83,7 +102,7 @@ export * from './metrics/gauges/derived-gauge'; export * from './metrics/gauges/gauge'; // Stats singleton instance -import {BaseStats} from './stats/stats'; -import {Stats} from './stats/types'; +import { BaseStats } from './stats/stats'; +import { Stats } from './stats/types'; const globalStats: Stats = BaseStats.instance; -export {globalStats}; +export { globalStats }; diff --git a/packages/opencensus-core/src/internal/cls-ah.ts b/packages/opencensus-core/src/internal/cls-ah.ts index bcddf7073..68a7e1dd5 100644 --- a/packages/opencensus-core/src/internal/cls-ah.ts +++ b/packages/opencensus-core/src/internal/cls-ah.ts @@ -18,21 +18,30 @@ // https://github.com/GoogleCloudPlatform/cloud-trace-nodejs import * as asyncHook from 'async_hooks'; -import {Context, Func, Namespace as CLSNamespace} from 'continuation-local-storage'; -import {EventEmitter} from 'events'; +import { + Context, + Func, + Namespace as CLSNamespace, +} from 'continuation-local-storage'; +import { EventEmitter } from 'events'; import * as shimmer from 'shimmer'; const WRAPPED = Symbol('context_wrapped'); /** A map of AsyncResource IDs to Context objects. */ -let contexts: {[asyncId: number]: Context;} = {}; +let contexts: { [asyncId: number]: Context } = {}; let current: Context = {}; // Create the hook. -asyncHook.createHook({init, before, destroy}).enable(); +asyncHook.createHook({ init, before, destroy }).enable(); // A list of well-known EventEmitter methods that add event listeners. -const EVENT_EMITTER_METHODS: Array = - ['addListener', 'on', 'once', 'prependListener', 'prependOnceListener']; +const EVENT_EMITTER_METHODS: Array = [ + 'addListener', + 'on', + 'once', + 'prependListener', + 'prependOnceListener', +]; class AsyncHooksNamespace implements CLSNamespace { get name(): string { @@ -76,7 +85,7 @@ class AsyncHooksNamespace implements CLSNamespace { // TODO(kjin): Monitor https://github.com/Microsoft/TypeScript/pull/15473. // When it's landed and released, we can remove these `any` casts. // tslint:disable-next-line:no-any - if ((cb as any)[WRAPPED] as boolean || !current) { + if (((cb as any)[WRAPPED] as boolean) || !current) { return cb; } const boundContext = current; @@ -93,7 +102,7 @@ class AsyncHooksNamespace implements CLSNamespace { enumerable: false, configurable: true, writable: false, - value: cb.length + value: cb.length, }); return contextWrapper; } @@ -105,9 +114,9 @@ class AsyncHooksNamespace implements CLSNamespace { // will cause us to lose context. bindEmitter(ee: NodeJS.EventEmitter): void { const ns = this; - EVENT_EMITTER_METHODS.forEach((method) => { + EVENT_EMITTER_METHODS.forEach(method => { if (ee[method]) { - shimmer.wrap(ee, method, (oldMethod) => { + shimmer.wrap(ee, method, oldMethod => { return function(this: {}, event: string, cb: Func) { return oldMethod.call(this, event, ns.bind(cb)); }; @@ -123,7 +132,11 @@ const namespace = new AsyncHooksNamespace(); /** init is called during object construction. */ function init( - uid: number, provider: string, parentUid: number, parentHandle: {}) { + uid: number, + provider: string, + parentUid: number, + parentHandle: {} +) { contexts[uid] = current; } diff --git a/packages/opencensus-core/src/internal/cls.ts b/packages/opencensus-core/src/internal/cls.ts index b1a3e372e..1a544a949 100644 --- a/packages/opencensus-core/src/internal/cls.ts +++ b/packages/opencensus-core/src/internal/cls.ts @@ -23,13 +23,12 @@ import * as semver from 'semver'; export type Namespace = CLS.Namespace; export type Func = CLS.Func; -const useAsyncHooks: boolean = semver.satisfies( - process.version, '>=8'); //&& - // !!process.env.GCLOUD_TRACE_NEW_CONTEXT; - -const cls: typeof CLS = - useAsyncHooks ? require('./cls-ah') : require('continuation-local-storage'); +const useAsyncHooks: boolean = semver.satisfies(process.version, '>=8'); //&& +// !!process.env.GCLOUD_TRACE_NEW_CONTEXT; +const cls: typeof CLS = useAsyncHooks + ? require('./cls-ah') + : require('continuation-local-storage'); const TRACE_NAMESPACE = 'opencensus.io'; diff --git a/packages/opencensus-core/src/internal/util.ts b/packages/opencensus-core/src/internal/util.ts index b6165826f..e24c1a762 100644 --- a/packages/opencensus-core/src/internal/util.ts +++ b/packages/opencensus-core/src/internal/util.ts @@ -26,9 +26,9 @@ const SPAN_ID_RANDOM_BYTES = 8; const spanIdBuffer = Buffer.alloc(SPAN_ID_RANDOM_BYTES); const randomFillSync = crypto.randomFillSync; const randomBytes = crypto.randomBytes; -const spanRandomBuffer = randomFillSync ? - () => randomFillSync(spanIdBuffer) : - () => randomBytes(SPAN_ID_RANDOM_BYTES); +const spanRandomBuffer = randomFillSync + ? () => randomFillSync(spanIdBuffer) + : () => randomBytes(SPAN_ID_RANDOM_BYTES); export function randomSpanId() { return spanRandomBuffer().toString('hex'); diff --git a/packages/opencensus-core/src/metrics/cumulative/cumulative.ts b/packages/opencensus-core/src/metrics/cumulative/cumulative.ts index f5a4f7a69..95790fbc2 100644 --- a/packages/opencensus-core/src/metrics/cumulative/cumulative.ts +++ b/packages/opencensus-core/src/metrics/cumulative/cumulative.ts @@ -14,12 +14,23 @@ * limitations under the License. */ -import {getTimestampWithProcessHRTime} from '../../common/time-util'; -import {validateArrayElementsNotNull, validateNotNull} from '../../common/validations'; -import {LabelKey, LabelValue, Metric, MetricDescriptor, MetricDescriptorType, TimeSeries, Timestamp} from '../export/types'; -import {Meter} from '../types'; -import {hashLabelValues, initializeDefaultLabels} from '../utils'; -import {CumulativePoint} from './types'; +import { getTimestampWithProcessHRTime } from '../../common/time-util'; +import { + validateArrayElementsNotNull, + validateNotNull, +} from '../../common/validations'; +import { + LabelKey, + LabelValue, + Metric, + MetricDescriptor, + MetricDescriptorType, + TimeSeries, + Timestamp, +} from '../export/types'; +import { Meter } from '../types'; +import { hashLabelValues, initializeDefaultLabels } from '../utils'; +import { CumulativePoint } from './types'; /** * Cumulative metric is used to record aggregated metrics that represents a @@ -44,15 +55,24 @@ export class Cumulative implements Meter { * @param constantLabels The map of constant labels for the Metric. */ constructor( - name: string, description: string, unit: string, - type: MetricDescriptorType, readonly labelKeys: LabelKey[], - readonly constantLabels: Map) { + name: string, + description: string, + unit: string, + type: MetricDescriptorType, + readonly labelKeys: LabelKey[], + readonly constantLabels: Map + ) { this.labelKeysLength = labelKeys.length; const keysAndConstantKeys = [...labelKeys, ...constantLabels.keys()]; this.constantLabelValues = [...constantLabels.values()]; - this.metricDescriptor = - {name, description, unit, type, labelKeys: keysAndConstantKeys}; + this.metricDescriptor = { + name, + description, + unit, + type, + labelKeys: keysAndConstantKeys, + }; this.defaultLabelValues = initializeDefaultLabels(this.labelKeysLength); } @@ -69,7 +89,9 @@ export class Cumulative implements Meter { */ getOrCreateTimeSeries(labelValues: LabelValue[]): CumulativePoint { validateArrayElementsNotNull( - validateNotNull(labelValues, 'labelValues'), 'labelValue'); + validateNotNull(labelValues, 'labelValues'), + 'labelValue' + ); return this.registerTimeSeries(labelValues); } @@ -118,11 +140,13 @@ export class Cumulative implements Meter { return this.registeredPoints.get(hash)!; } if (this.labelKeysLength !== labelValues.length) { - throw new Error('Label Keys and Label Values don\'t have same size'); + throw new Error("Label Keys and Label Values don't have same size"); } - const point = - new CumulativePointEntry([...labelValues, ...this.constantLabelValues]); + const point = new CumulativePointEntry([ + ...labelValues, + ...this.constantLabelValues, + ]); this.registeredPoints.set(hash, point); return point; } @@ -132,15 +156,16 @@ export class Cumulative implements Meter { * * @returns The Metric, or null if TimeSeries is not present in Metric. */ - getMetric(): Metric|null { + getMetric(): Metric | null { if (this.registeredPoints.size === 0) { return null; } const now: Timestamp = getTimestampWithProcessHRTime(); return { descriptor: this.metricDescriptor, - timeseries: Array.from( - this.registeredPoints, ([_, point]) => point.getTimeSeries(now)) + timeseries: Array.from(this.registeredPoints, ([_, point]) => + point.getTimeSeries(now) + ), }; } } @@ -175,7 +200,7 @@ export class CumulativePointEntry implements CumulativePoint { if (val && val < 0) { throw new Error('It is not possible to decrease a cumulative metric'); } - const incValue = (val === null || val === undefined) ? 1 : val; + const incValue = val === null || val === undefined ? 1 : val; this.value += incValue; } @@ -188,8 +213,8 @@ export class CumulativePointEntry implements CumulativePoint { getTimeSeries(now: Timestamp): TimeSeries { return { labelValues: this.labelValues, - points: [{value: this.value, timestamp: now}], - startTimestamp: this.startTimestamp + points: [{ value: this.value, timestamp: now }], + startTimestamp: this.startTimestamp, }; } } diff --git a/packages/opencensus-core/src/metrics/cumulative/derived-cumulative.ts b/packages/opencensus-core/src/metrics/cumulative/derived-cumulative.ts index acd7ff3b7..9f8c14e57 100644 --- a/packages/opencensus-core/src/metrics/cumulative/derived-cumulative.ts +++ b/packages/opencensus-core/src/metrics/cumulative/derived-cumulative.ts @@ -14,11 +14,22 @@ * limitations under the License. */ -import {getTimestampWithProcessHRTime} from '../../common/time-util'; -import {validateArrayElementsNotNull, validateNotNull} from '../../common/validations'; -import {LabelKey, LabelValue, Metric, MetricDescriptor, MetricDescriptorType, TimeSeries, Timestamp} from '../export/types'; -import {Meter} from '../types'; -import {AccessorInterface} from '../types'; +import { getTimestampWithProcessHRTime } from '../../common/time-util'; +import { + validateArrayElementsNotNull, + validateNotNull, +} from '../../common/validations'; +import { + LabelKey, + LabelValue, + Metric, + MetricDescriptor, + MetricDescriptorType, + TimeSeries, + Timestamp, +} from '../export/types'; +import { Meter } from '../types'; +import { AccessorInterface } from '../types'; import * as util from '../utils'; type ValueExtractor = () => number; @@ -61,16 +72,25 @@ export class DerivedCumulative implements Meter { * value. */ constructor( - name: string, description: string, unit: string, - type: MetricDescriptorType, labelKeys: LabelKey[], - readonly constantLabels: Map, - startTime: Timestamp) { + name: string, + description: string, + unit: string, + type: MetricDescriptorType, + labelKeys: LabelKey[], + readonly constantLabels: Map, + startTime: Timestamp + ) { this.labelKeysLength = labelKeys.length; const keysAndConstantKeys = [...labelKeys, ...constantLabels.keys()]; this.constantLabelValues = [...constantLabels.values()]; - this.metricDescriptor = - {name, description, unit, type, labelKeys: keysAndConstantKeys}; + this.metricDescriptor = { + name, + description, + unit, + type, + labelKeys: keysAndConstantKeys, + }; this.startTime = startTime; } @@ -87,19 +107,24 @@ export class DerivedCumulative implements Meter { * fn is the function that will be called to get the current value * of the cumulative. */ - createTimeSeries(labelValues: LabelValue[], objOrFn: AccessorInterface): - void { + createTimeSeries( + labelValues: LabelValue[], + objOrFn: AccessorInterface + ): void { validateArrayElementsNotNull( - validateNotNull(labelValues, 'labelValues'), 'labelValue'); + validateNotNull(labelValues, 'labelValues'), + 'labelValue' + ); validateNotNull(objOrFn, 'obj'); const hash = util.hashLabelValues(labelValues); if (this.registeredPoints.has(hash)) { throw new Error( - 'A different time series with the same labels already exists.'); + 'A different time series with the same labels already exists.' + ); } if (this.labelKeysLength !== labelValues.length) { - throw new Error('Label Keys and Label Values don\'t have same size'); + throw new Error("Label Keys and Label Values don't have same size"); } if (objOrFn instanceof Function) { @@ -118,8 +143,11 @@ export class DerivedCumulative implements Meter { throw new Error('Unknown interface/object type'); } - this.registeredPoints.set( - hash, {labelValues, extractor: this.extractor, prevValue: 0}); + this.registeredPoints.set(hash, { + labelValues, + extractor: this.extractor, + prevValue: 0, + }); } /** @@ -147,7 +175,7 @@ export class DerivedCumulative implements Meter { * * @returns The Metric, or null if TimeSeries is not present in Metric. */ - getMetric(): Metric|null { + getMetric(): Metric | null { if (this.registeredPoints.size === 0) { return null; } @@ -155,23 +183,25 @@ export class DerivedCumulative implements Meter { return { descriptor: this.metricDescriptor, timeseries: Array.from( - this.registeredPoints, - ([_, cumulativeEntry]): - TimeSeries => { - const newValue = cumulativeEntry.extractor(); - const value = newValue > cumulativeEntry.prevValue ? - newValue : - cumulativeEntry.prevValue; - cumulativeEntry.prevValue = value; + this.registeredPoints, + ([_, cumulativeEntry]): TimeSeries => { + const newValue = cumulativeEntry.extractor(); + const value = + newValue > cumulativeEntry.prevValue + ? newValue + : cumulativeEntry.prevValue; + cumulativeEntry.prevValue = value; - return { - labelValues: [ - ...cumulativeEntry.labelValues, ...this.constantLabelValues - ], - points: [{value, timestamp}], - startTimestamp: this.startTime - }; - }) + return { + labelValues: [ + ...cumulativeEntry.labelValues, + ...this.constantLabelValues, + ], + points: [{ value, timestamp }], + startTimestamp: this.startTime, + }; + } + ), }; } } diff --git a/packages/opencensus-core/src/metrics/cumulative/types.ts b/packages/opencensus-core/src/metrics/cumulative/types.ts index 8db6a323a..7ce68ae85 100644 --- a/packages/opencensus-core/src/metrics/cumulative/types.ts +++ b/packages/opencensus-core/src/metrics/cumulative/types.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {TimeSeries, Timestamp} from '../export/types'; +import { TimeSeries, Timestamp } from '../export/types'; export interface CumulativePoint { /** Reset cumulative metric. */ diff --git a/packages/opencensus-core/src/metrics/export/base-metric-producer.ts b/packages/opencensus-core/src/metrics/export/base-metric-producer.ts index 735cd7211..63065aca3 100644 --- a/packages/opencensus-core/src/metrics/export/base-metric-producer.ts +++ b/packages/opencensus-core/src/metrics/export/base-metric-producer.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {Metric, MetricProducer} from './types'; +import { Metric, MetricProducer } from './types'; /** * A MetricProducer producer that can be registered for exporting using diff --git a/packages/opencensus-core/src/metrics/export/metric-producer-manager.ts b/packages/opencensus-core/src/metrics/export/metric-producer-manager.ts index dd75278b1..a718c0e20 100644 --- a/packages/opencensus-core/src/metrics/export/metric-producer-manager.ts +++ b/packages/opencensus-core/src/metrics/export/metric-producer-manager.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {validateNotNull} from '../../common/validations'; -import {MetricProducer, MetricProducerManager} from './types'; +import { validateNotNull } from '../../common/validations'; +import { MetricProducer, MetricProducerManager } from './types'; /** * Keeps a set of MetricProducer that is used by exporters to determine the diff --git a/packages/opencensus-core/src/metrics/export/types.ts b/packages/opencensus-core/src/metrics/export/types.ts index dbeff405c..6e5270017 100644 --- a/packages/opencensus-core/src/metrics/export/types.ts +++ b/packages/opencensus-core/src/metrics/export/types.ts @@ -98,7 +98,7 @@ export enum MetricDescriptorType { * values, it calculates configurable percentiles over a sliding time * window. This is not recommended, since it cannot be aggregated. */ - SUMMARY + SUMMARY, } /** Properties of a LabelKey associated with a MetricDescriptor. */ @@ -137,7 +137,7 @@ export interface TimeSeries { /** The LabelValue type. null value indicates an unset. */ export interface LabelValue { /** The value for the label. */ - readonly value: string|null; + readonly value: string | null; } /** A timestamped measurement. */ @@ -153,7 +153,7 @@ export interface Point { * or distribution value * or summary value. This is not recommended, since it cannot be aggregated. */ - readonly value: number|DistributionValue|SummaryValue; + readonly value: number | DistributionValue | SummaryValue; } /** @@ -254,7 +254,7 @@ export interface Exemplar { /** The observation (sampling) time of the above value. */ readonly timestamp: Timestamp; /** Contextual information about the example value. */ - readonly attachments: {[key: string]: string}; + readonly attachments: { [key: string]: string }; } /** @@ -316,14 +316,14 @@ export interface Timestamp { * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to * 9999-12-31T23:59:59Z inclusive. */ - seconds: number|null; + seconds: number | null; /** * Non-negative fractions of a second at nanosecond resolution. Negative * second values with fractions must still have non-negative nanos values * that count forward in time. Must be from 0 to 999,999,999 * inclusive. */ - nanos: number|null; + nanos: number | null; } /** diff --git a/packages/opencensus-core/src/metrics/gauges/derived-gauge.ts b/packages/opencensus-core/src/metrics/gauges/derived-gauge.ts index 76ce4536b..89ab37a44 100644 --- a/packages/opencensus-core/src/metrics/gauges/derived-gauge.ts +++ b/packages/opencensus-core/src/metrics/gauges/derived-gauge.ts @@ -14,11 +14,22 @@ * limitations under the License. */ -import {getTimestampWithProcessHRTime} from '../../common/time-util'; -import {validateArrayElementsNotNull, validateNotNull} from '../../common/validations'; -import {LabelKey, LabelValue, Metric, MetricDescriptor, MetricDescriptorType, TimeSeries, Timestamp} from '../export/types'; +import { getTimestampWithProcessHRTime } from '../../common/time-util'; +import { + validateArrayElementsNotNull, + validateNotNull, +} from '../../common/validations'; +import { + LabelKey, + LabelValue, + Metric, + MetricDescriptor, + MetricDescriptorType, + TimeSeries, + Timestamp, +} from '../export/types'; import * as types from '../types'; -import {AccessorInterface} from '../types'; +import { AccessorInterface } from '../types'; import * as util from '../utils'; type ValueExtractor = () => number; @@ -42,11 +53,11 @@ export class DerivedGauge implements types.Meter { private static readonly LABEL_VALUES = 'labelValues'; private static readonly OBJECT = 'obj'; private static readonly ERROR_MESSAGE_INVALID_SIZE = - 'Label Keys and Label Values don\'t have same size'; + "Label Keys and Label Values don't have same size"; private static readonly ERROR_MESSAGE_DUPLICATE_TIME_SERIES = - 'A different time series with the same labels already exists.'; + 'A different time series with the same labels already exists.'; private static readonly ERROR_MESSAGE_UNKNOWN_INTERFACE = - 'Unknown interface/object type'; + 'Unknown interface/object type'; /** * Constructs a new DerivedGauge instance. @@ -59,15 +70,24 @@ export class DerivedGauge implements types.Meter { * @param constantLabels The map of constant labels for the Metric. */ constructor( - name: string, description: string, unit: string, - type: MetricDescriptorType, labelKeys: LabelKey[], - readonly constantLabels: Map) { + name: string, + description: string, + unit: string, + type: MetricDescriptorType, + labelKeys: LabelKey[], + readonly constantLabels: Map + ) { this.labelKeysLength = labelKeys.length; const keysAndConstantKeys = [...labelKeys, ...constantLabels.keys()]; this.constantLabelValues = [...constantLabels.values()]; - this.metricDescriptor = - {name, description, unit, type, labelKeys: keysAndConstantKeys}; + this.metricDescriptor = { + name, + description, + unit, + type, + labelKeys: keysAndConstantKeys, + }; } /** @@ -83,11 +103,14 @@ export class DerivedGauge implements types.Meter { * fn is the function that will be called to get the current value * of the gauge. */ - createTimeSeries(labelValues: LabelValue[], objOrFn: AccessorInterface): - void { + createTimeSeries( + labelValues: LabelValue[], + objOrFn: AccessorInterface + ): void { validateArrayElementsNotNull( - validateNotNull(labelValues, DerivedGauge.LABEL_VALUES), - DerivedGauge.LABEL_VALUE); + validateNotNull(labelValues, DerivedGauge.LABEL_VALUES), + DerivedGauge.LABEL_VALUE + ); validateNotNull(objOrFn, DerivedGauge.OBJECT); const hash = util.hashLabelValues(labelValues); @@ -114,7 +137,7 @@ export class DerivedGauge implements types.Meter { throw new Error(DerivedGauge.ERROR_MESSAGE_UNKNOWN_INTERFACE); } - this.registeredPoints.set(hash, {labelValues, extractor: this.extractor}); + this.registeredPoints.set(hash, { labelValues, extractor: this.extractor }); } /** @@ -142,7 +165,7 @@ export class DerivedGauge implements types.Meter { * * @returns The Metric, or null if TimeSeries is not present in Metric. */ - getMetric(): Metric|null { + getMetric(): Metric | null { if (this.registeredPoints.size === 0) { return null; } @@ -150,12 +173,12 @@ export class DerivedGauge implements types.Meter { return { descriptor: this.metricDescriptor, timeseries: Array.from( - this.registeredPoints, - ([_, gaugeEntry]): TimeSeries => ({ - labelValues: - [...gaugeEntry.labelValues, ...this.constantLabelValues], - points: [{value: gaugeEntry.extractor(), timestamp}] - })) + this.registeredPoints, + ([_, gaugeEntry]): TimeSeries => ({ + labelValues: [...gaugeEntry.labelValues, ...this.constantLabelValues], + points: [{ value: gaugeEntry.extractor(), timestamp }], + }) + ), }; } } diff --git a/packages/opencensus-core/src/metrics/gauges/gauge.ts b/packages/opencensus-core/src/metrics/gauges/gauge.ts index b291d3bb4..1e315c3d6 100644 --- a/packages/opencensus-core/src/metrics/gauges/gauge.ts +++ b/packages/opencensus-core/src/metrics/gauges/gauge.ts @@ -14,11 +14,22 @@ * limitations under the License. */ -import {getTimestampWithProcessHRTime} from '../../common/time-util'; -import {validateArrayElementsNotNull, validateNotNull} from '../../common/validations'; -import {LabelKey, LabelValue, Metric, MetricDescriptor, MetricDescriptorType, TimeSeries, Timestamp} from '../export/types'; -import {Meter} from '../types'; -import {hashLabelValues, initializeDefaultLabels} from '../utils'; +import { getTimestampWithProcessHRTime } from '../../common/time-util'; +import { + validateArrayElementsNotNull, + validateNotNull, +} from '../../common/validations'; +import { + LabelKey, + LabelValue, + Metric, + MetricDescriptor, + MetricDescriptorType, + TimeSeries, + Timestamp, +} from '../export/types'; +import { Meter } from '../types'; +import { hashLabelValues, initializeDefaultLabels } from '../utils'; import * as types from './types'; /** @@ -34,7 +45,7 @@ export class Gauge implements Meter { private static readonly LABEL_VALUE = 'labelValue'; private static readonly LABEL_VALUES = 'labelValues'; private static readonly ERROR_MESSAGE_INVALID_SIZE = - 'Label Keys and Label Values don\'t have same size'; + "Label Keys and Label Values don't have same size"; /** * Constructs a new Gauge instance. @@ -47,15 +58,24 @@ export class Gauge implements Meter { * @param constantLabels The map of constant labels for the Metric. */ constructor( - name: string, description: string, unit: string, - type: MetricDescriptorType, readonly labelKeys: LabelKey[], - readonly constantLabels: Map) { + name: string, + description: string, + unit: string, + type: MetricDescriptorType, + readonly labelKeys: LabelKey[], + readonly constantLabels: Map + ) { this.labelKeysLength = labelKeys.length; const keysAndConstantKeys = [...labelKeys, ...constantLabels.keys()]; this.constantLabelValues = [...constantLabels.values()]; - this.metricDescriptor = - {name, description, unit, type, labelKeys: keysAndConstantKeys}; + this.metricDescriptor = { + name, + description, + unit, + type, + labelKeys: keysAndConstantKeys, + }; this.defaultLabelValues = initializeDefaultLabels(this.labelKeysLength); } @@ -72,7 +92,9 @@ export class Gauge implements Meter { */ getOrCreateTimeSeries(labelValues: LabelValue[]): types.Point { validateArrayElementsNotNull( - validateNotNull(labelValues, Gauge.LABEL_VALUES), Gauge.LABEL_VALUE); + validateNotNull(labelValues, Gauge.LABEL_VALUES), + Gauge.LABEL_VALUE + ); return this.registerTimeSeries(labelValues); } @@ -134,15 +156,16 @@ export class Gauge implements Meter { * * @returns The Metric, or null if TimeSeries is not present in Metric. */ - getMetric(): Metric|null { + getMetric(): Metric | null { if (this.registeredPoints.size === 0) { return null; } const timestamp: Timestamp = getTimestampWithProcessHRTime(); return { descriptor: this.metricDescriptor, - timeseries: Array.from( - this.registeredPoints, ([_, point]) => point.getTimeSeries(timestamp)) + timeseries: Array.from(this.registeredPoints, ([_, point]) => + point.getTimeSeries(timestamp) + ), }; } } @@ -185,7 +208,7 @@ export class PointEntry implements types.Point { getTimeSeries(timestamp: Timestamp): TimeSeries { return { labelValues: this.labelValues, - points: [{value: this.value, timestamp}] + points: [{ value: this.value, timestamp }], }; } } diff --git a/packages/opencensus-core/src/metrics/gauges/types.ts b/packages/opencensus-core/src/metrics/gauges/types.ts index 0be99fc3f..f1b8c4766 100644 --- a/packages/opencensus-core/src/metrics/gauges/types.ts +++ b/packages/opencensus-core/src/metrics/gauges/types.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {TimeSeries, Timestamp} from '../export/types'; +import { TimeSeries, Timestamp } from '../export/types'; export interface Point { /** diff --git a/packages/opencensus-core/src/metrics/metric-component.ts b/packages/opencensus-core/src/metrics/metric-component.ts index fda92f802..cd99de428 100644 --- a/packages/opencensus-core/src/metrics/metric-component.ts +++ b/packages/opencensus-core/src/metrics/metric-component.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {metricProducerManagerInstance} from './export/metric-producer-manager'; -import {MetricRegistry} from './metric-registry'; +import { metricProducerManagerInstance } from './export/metric-producer-manager'; +import { MetricRegistry } from './metric-registry'; /** * Class that holds the implementation instance for MetricRegistry. diff --git a/packages/opencensus-core/src/metrics/metric-registry.ts b/packages/opencensus-core/src/metrics/metric-registry.ts index 914766558..1ab428634 100644 --- a/packages/opencensus-core/src/metrics/metric-registry.ts +++ b/packages/opencensus-core/src/metrics/metric-registry.ts @@ -14,16 +14,28 @@ * limitations under the License. */ -import {getTimestampWithProcessHRTime} from '../common/time-util'; -import {validateArrayElementsNotNull, validateDuplicateKeys, validateMapElementNotNull, validateNotNull} from '../common/validations'; -import {MeasureUnit} from '../stats/types'; -import {Cumulative} from './cumulative/cumulative'; -import {DerivedCumulative} from './cumulative/derived-cumulative'; -import {BaseMetricProducer} from './export/base-metric-producer'; -import {LabelKey, LabelValue, Metric, MetricDescriptorType, MetricProducer, Timestamp} from './export/types'; -import {DerivedGauge} from './gauges/derived-gauge'; -import {Gauge} from './gauges/gauge'; -import {Meter, MetricOptions} from './types'; +import { getTimestampWithProcessHRTime } from '../common/time-util'; +import { + validateArrayElementsNotNull, + validateDuplicateKeys, + validateMapElementNotNull, + validateNotNull, +} from '../common/validations'; +import { MeasureUnit } from '../stats/types'; +import { Cumulative } from './cumulative/cumulative'; +import { DerivedCumulative } from './cumulative/derived-cumulative'; +import { BaseMetricProducer } from './export/base-metric-producer'; +import { + LabelKey, + LabelValue, + Metric, + MetricDescriptorType, + MetricProducer, + Timestamp, +} from './export/types'; +import { DerivedGauge } from './gauges/derived-gauge'; +import { Gauge } from './gauges/gauge'; +import { Meter, MetricOptions } from './types'; /** * Creates and manages application's set of metrics. @@ -55,20 +67,26 @@ export class MetricRegistry { */ addInt64Gauge(name: string, options?: MetricOptions): Gauge { const description = - (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; + (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = - (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; - const constantLabels = (options && options.constantLabels) || - MetricRegistry.DEFAULT_CONSTANT_LABEL; + (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; + const constantLabels = + (options && options.constantLabels) || + MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const int64Gauge = new Gauge( - validateNotNull(name, MetricRegistry.NAME), description, unit, - MetricDescriptorType.GAUGE_INT64, labelKeysCopy, constantLabels); + validateNotNull(name, MetricRegistry.NAME), + description, + unit, + MetricDescriptorType.GAUGE_INT64, + labelKeysCopy, + constantLabels + ); this.registerMetric(name, int64Gauge); return int64Gauge; } @@ -84,20 +102,26 @@ export class MetricRegistry { */ addDoubleGauge(name: string, options?: MetricOptions): Gauge { const description = - (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; + (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = - (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; - const constantLabels = (options && options.constantLabels) || - MetricRegistry.DEFAULT_CONSTANT_LABEL; + (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; + const constantLabels = + (options && options.constantLabels) || + MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const doubleGauge = new Gauge( - validateNotNull(name, MetricRegistry.NAME), description, unit, - MetricDescriptorType.GAUGE_DOUBLE, labelKeysCopy, constantLabels); + validateNotNull(name, MetricRegistry.NAME), + description, + unit, + MetricDescriptorType.GAUGE_DOUBLE, + labelKeysCopy, + constantLabels + ); this.registerMetric(name, doubleGauge); return doubleGauge; } @@ -113,20 +137,26 @@ export class MetricRegistry { */ addDerivedInt64Gauge(name: string, options?: MetricOptions): DerivedGauge { const description = - (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; + (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = - (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; - const constantLabels = (options && options.constantLabels) || - MetricRegistry.DEFAULT_CONSTANT_LABEL; + (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; + const constantLabels = + (options && options.constantLabels) || + MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const derivedInt64Gauge = new DerivedGauge( - validateNotNull(name, MetricRegistry.NAME), description, unit, - MetricDescriptorType.GAUGE_INT64, labelKeysCopy, constantLabels); + validateNotNull(name, MetricRegistry.NAME), + description, + unit, + MetricDescriptorType.GAUGE_INT64, + labelKeysCopy, + constantLabels + ); this.registerMetric(name, derivedInt64Gauge); return derivedInt64Gauge; } @@ -142,20 +172,26 @@ export class MetricRegistry { */ addDerivedDoubleGauge(name: string, options?: MetricOptions): DerivedGauge { const description = - (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; + (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = - (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; - const constantLabels = (options && options.constantLabels) || - MetricRegistry.DEFAULT_CONSTANT_LABEL; + (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; + const constantLabels = + (options && options.constantLabels) || + MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const derivedDoubleGauge = new DerivedGauge( - validateNotNull(name, MetricRegistry.NAME), description, unit, - MetricDescriptorType.GAUGE_DOUBLE, labelKeysCopy, constantLabels); + validateNotNull(name, MetricRegistry.NAME), + description, + unit, + MetricDescriptorType.GAUGE_DOUBLE, + labelKeysCopy, + constantLabels + ); this.registerMetric(name, derivedDoubleGauge); return derivedDoubleGauge; } @@ -171,20 +207,26 @@ export class MetricRegistry { */ addInt64Cumulative(name: string, options?: MetricOptions): Cumulative { const description = - (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; + (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = - (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; - const constantLabels = (options && options.constantLabels) || - MetricRegistry.DEFAULT_CONSTANT_LABEL; + (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; + const constantLabels = + (options && options.constantLabels) || + MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const int64Cumulative = new Cumulative( - validateNotNull(name, MetricRegistry.NAME), description, unit, - MetricDescriptorType.CUMULATIVE_INT64, labelKeysCopy, constantLabels); + validateNotNull(name, MetricRegistry.NAME), + description, + unit, + MetricDescriptorType.CUMULATIVE_INT64, + labelKeysCopy, + constantLabels + ); this.registerMetric(name, int64Cumulative); return int64Cumulative; } @@ -200,20 +242,26 @@ export class MetricRegistry { */ addDoubleCumulative(name: string, options?: MetricOptions): Cumulative { const description = - (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; + (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = - (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; - const constantLabels = (options && options.constantLabels) || - MetricRegistry.DEFAULT_CONSTANT_LABEL; + (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; + const constantLabels = + (options && options.constantLabels) || + MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const doubleCumulative = new Cumulative( - validateNotNull(name, MetricRegistry.NAME), description, unit, - MetricDescriptorType.CUMULATIVE_DOUBLE, labelKeysCopy, constantLabels); + validateNotNull(name, MetricRegistry.NAME), + description, + unit, + MetricDescriptorType.CUMULATIVE_DOUBLE, + labelKeysCopy, + constantLabels + ); this.registerMetric(name, doubleCumulative); return doubleCumulative; } @@ -225,15 +273,18 @@ export class MetricRegistry { * @param options The options for the metric. * @returns A Int64 DerivedCumulative metric. */ - addDerivedInt64Cumulative(name: string, options?: MetricOptions): - DerivedCumulative { + addDerivedInt64Cumulative( + name: string, + options?: MetricOptions + ): DerivedCumulative { const description = - (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; + (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = - (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; - const constantLabels = (options && options.constantLabels) || - MetricRegistry.DEFAULT_CONSTANT_LABEL; + (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; + const constantLabels = + (options && options.constantLabels) || + MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); @@ -241,9 +292,14 @@ export class MetricRegistry { const labelKeysCopy = Object.assign([], labelKeys); const startTime: Timestamp = getTimestampWithProcessHRTime(); const derivedInt64Cumulative = new DerivedCumulative( - validateNotNull(name, MetricRegistry.NAME), description, unit, - MetricDescriptorType.CUMULATIVE_INT64, labelKeysCopy, constantLabels, - startTime); + validateNotNull(name, MetricRegistry.NAME), + description, + unit, + MetricDescriptorType.CUMULATIVE_INT64, + labelKeysCopy, + constantLabels, + startTime + ); this.registerMetric(name, derivedInt64Cumulative); return derivedInt64Cumulative; } @@ -255,15 +311,18 @@ export class MetricRegistry { * @param options The options for the metric. * @returns A Double DerivedCumulative metric. */ - addDerivedDoubleCumulative(name: string, options?: MetricOptions): - DerivedCumulative { + addDerivedDoubleCumulative( + name: string, + options?: MetricOptions + ): DerivedCumulative { const description = - (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; + (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = - (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; - const constantLabels = (options && options.constantLabels) || - MetricRegistry.DEFAULT_CONSTANT_LABEL; + (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; + const constantLabels = + (options && options.constantLabels) || + MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); @@ -271,9 +330,14 @@ export class MetricRegistry { const labelKeysCopy = Object.assign([], labelKeys); const startTime: Timestamp = getTimestampWithProcessHRTime(); const derivedDoubleCumulative = new DerivedCumulative( - validateNotNull(name, MetricRegistry.NAME), description, unit, - MetricDescriptorType.CUMULATIVE_DOUBLE, labelKeysCopy, constantLabels, - startTime); + validateNotNull(name, MetricRegistry.NAME), + description, + unit, + MetricDescriptorType.CUMULATIVE_DOUBLE, + labelKeysCopy, + constantLabels, + startTime + ); this.registerMetric(name, derivedDoubleCumulative); return derivedDoubleCumulative; } @@ -287,7 +351,8 @@ export class MetricRegistry { private registerMetric(name: string, meter: Meter): void { if (this.registeredMetrics.has(name)) { throw new Error( - `A metric with the name ${name} has already been registered.`); + `A metric with the name ${name} has already been registered.` + ); } this.registeredMetrics.set(name, meter); } @@ -303,7 +368,9 @@ export class MetricRegistry { /** Validates labelKeys and constantLabels. */ private validateLables( - labelKeys: LabelKey[], constantLabels: Map) { + labelKeys: LabelKey[], + constantLabels: Map + ) { validateArrayElementsNotNull(labelKeys, MetricRegistry.LABEL_KEY); validateMapElementNotNull(constantLabels, MetricRegistry.CONSTANT_LABELS); validateDuplicateKeys(labelKeys, constantLabels); @@ -329,7 +396,7 @@ class MetricProducerForRegistry extends BaseMetricProducer { */ getMetrics(): Metric[] { return Array.from(this.registeredMetrics.values()) - .map(meter => meter.getMetric()) - .filter(meter => !!meter) as Metric[]; + .map(meter => meter.getMetric()) + .filter(meter => !!meter) as Metric[]; } } diff --git a/packages/opencensus-core/src/metrics/metrics.ts b/packages/opencensus-core/src/metrics/metrics.ts index d5284b33f..444c28eda 100644 --- a/packages/opencensus-core/src/metrics/metrics.ts +++ b/packages/opencensus-core/src/metrics/metrics.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import {metricProducerManagerInstance} from './export/metric-producer-manager'; -import {MetricProducerManager} from './export/types'; -import {MetricsComponent} from './metric-component'; -import {MetricRegistry} from './metric-registry'; +import { metricProducerManagerInstance } from './export/metric-producer-manager'; +import { MetricProducerManager } from './export/types'; +import { MetricsComponent } from './metric-component'; +import { MetricRegistry } from './metric-registry'; /** * Class for accessing the default MetricsComponent. diff --git a/packages/opencensus-core/src/metrics/types.ts b/packages/opencensus-core/src/metrics/types.ts index d6d63c8b6..3f7fcdaac 100644 --- a/packages/opencensus-core/src/metrics/types.ts +++ b/packages/opencensus-core/src/metrics/types.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {MeasureUnit} from './../stats/types'; -import {LabelKey, LabelValue, Metric} from './export/types'; +import { MeasureUnit } from './../stats/types'; +import { LabelKey, LabelValue, Metric } from './export/types'; /** Provides a {@link Metric} with one or more {@link TimeSeries} */ export interface Meter { @@ -24,7 +24,7 @@ export interface Meter { * * @returns The Metric, or null if TimeSeries is not present in Metric. */ - getMetric(): Metric|null; + getMetric(): Metric | null; } /** Options for every metric added to the MetricRegistry. */ @@ -72,5 +72,9 @@ export interface AccessorFunction { } export type AccessorInterface = - LengthAttributeInterface|LengthMethodInterface|SizeAttributeInterface| - SizeMethodInterface|ToValueInterface|AccessorFunction; + | LengthAttributeInterface + | LengthMethodInterface + | SizeAttributeInterface + | SizeMethodInterface + | ToValueInterface + | AccessorFunction; diff --git a/packages/opencensus-core/src/metrics/utils.ts b/packages/opencensus-core/src/metrics/utils.ts index 13c3ef8a9..d6c48b3e9 100644 --- a/packages/opencensus-core/src/metrics/utils.ts +++ b/packages/opencensus-core/src/metrics/utils.ts @@ -14,12 +14,18 @@ * limitations under the License. */ -import {LabelValue} from './export/types'; -import {LengthAttributeInterface, LengthMethodInterface, SizeAttributeInterface, SizeMethodInterface, ToValueInterface} from './types'; +import { LabelValue } from './export/types'; +import { + LengthAttributeInterface, + LengthMethodInterface, + SizeAttributeInterface, + SizeMethodInterface, + ToValueInterface, +} from './types'; const COMMA_SEPARATOR = ','; const UNSET_LABEL_VALUE: LabelValue = { - value: null + value: null, }; /** @@ -29,7 +35,10 @@ const UNSET_LABEL_VALUE: LabelValue = { * @returns The hashed label values string. */ export function hashLabelValues(labelValues: LabelValue[]): string { - return labelValues.map(lv => lv.value).sort().join(COMMA_SEPARATOR); + return labelValues + .map(lv => lv.value) + .sort() + .join(COMMA_SEPARATOR); } /** @@ -49,23 +58,26 @@ export function initializeDefaultLabels(count: number): LabelValue[] { // element or any of its properties. // Checks if the specified collection is a LengthAttributeInterface. -// tslint:disable-next-line:no-any -export function isLengthAttributeInterface(obj: any): - obj is LengthAttributeInterface { +export function isLengthAttributeInterface( + // tslint:disable-next-line:no-any + obj: any +): obj is LengthAttributeInterface { return obj && typeof obj.length === 'number'; } // Checks if the specified collection is a LengthMethodInterface. -// tslint:disable-next-line:no-any -export function isLengthMethodInterface(obj: any): - obj is LengthMethodInterface { +export function isLengthMethodInterface( + // tslint:disable-next-line:no-any + obj: any +): obj is LengthMethodInterface { return obj && typeof obj.length === 'function'; } // Checks if the specified collection is a SizeAttributeInterface. -// tslint:disable-next-line:no-any -export function isSizeAttributeInterface(obj: any): - obj is SizeAttributeInterface { +export function isSizeAttributeInterface( + // tslint:disable-next-line:no-any + obj: any +): obj is SizeAttributeInterface { return obj && typeof obj.size === 'number'; } diff --git a/packages/opencensus-core/src/resource/resource.ts b/packages/opencensus-core/src/resource/resource.ts index 9e1131359..5de35edd2 100644 --- a/packages/opencensus-core/src/resource/resource.ts +++ b/packages/opencensus-core/src/resource/resource.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {StringUtils} from '../internal/string-utils'; -import {Labels, Resource} from './types'; +import { StringUtils } from '../internal/string-utils'; +import { Labels, Resource } from './types'; /** * Resource represents a resource, which capture identifying information about @@ -34,16 +34,20 @@ export class CoreResource { // OC_RESOURCE_LABELS contains key value pair separated by '='. private static readonly LABEL_KEY_VALUE_SPLITTER = '='; - private static ENV_TYPE = - CoreResource.parseResourceType(process.env.OC_RESOURCE_TYPE); - private static ENV_LABEL_MAP = - CoreResource.parseResourceLabels(process.env.OC_RESOURCE_LABELS); + private static ENV_TYPE = CoreResource.parseResourceType( + process.env.OC_RESOURCE_TYPE + ); + private static ENV_LABEL_MAP = CoreResource.parseResourceLabels( + process.env.OC_RESOURCE_LABELS + ); private static readonly ERROR_MESSAGE_INVALID_CHARS = - 'should be a ASCII string with a length greater than 0 and not exceed ' + - CoreResource.MAX_LENGTH + ' characters.'; + 'should be a ASCII string with a length greater than 0 and not exceed ' + + CoreResource.MAX_LENGTH + + ' characters.'; private static readonly ERROR_MESSAGE_INVALID_VALUE = - 'should be a ASCII string with a length not exceed ' + - CoreResource.MAX_LENGTH + ' characters.'; + 'should be a ASCII string with a length not exceed ' + + CoreResource.MAX_LENGTH + + ' characters.'; /** * Returns a Resource. This resource information is loaded from the @@ -52,7 +56,7 @@ export class CoreResource { * @returns The resource. */ static createFromEnvironmentVariables(): Resource { - return {type: CoreResource.ENV_TYPE, labels: CoreResource.ENV_LABEL_MAP}; + return { type: CoreResource.ENV_TYPE, labels: CoreResource.ENV_LABEL_MAP }; } /** @@ -64,7 +68,7 @@ export class CoreResource { * @returns The resource. */ static mergeResources(resources: Resource[]): Resource { - if (resources.length === 0) return {type: 'global', labels: {}}; + if (resources.length === 0) return { type: 'global', labels: {} }; let currentResource = resources[0]; for (let i = 1; i < resources.length; i++) { currentResource = this.merge(currentResource, resources[i]); @@ -81,7 +85,7 @@ export class CoreResource { * @param rawEnvType The resource type. * @returns The sanitized resource type. */ - private static parseResourceType(rawEnvType?: string): string|null { + private static parseResourceType(rawEnvType?: string): string | null { if (!rawEnvType) return null; if (!CoreResource.isValidAndNotEmpty(rawEnvType)) { throw new Error(`Type ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`); @@ -107,22 +111,29 @@ export class CoreResource { const labels: Labels = {}; const rawLabels: string[] = rawEnvLabels.split(this.COMMA_SEPARATOR, -1); for (const rawLabel of rawLabels) { - const keyValuePair: string[] = - rawLabel.split(this.LABEL_KEY_VALUE_SPLITTER, -1); + const keyValuePair: string[] = rawLabel.split( + this.LABEL_KEY_VALUE_SPLITTER, + -1 + ); if (keyValuePair.length !== 2) { continue; } let [key, value] = keyValuePair; // Leading and trailing whitespaces are trimmed. key = key.trim(); - value = value.trim().split('^"|"$').join(''); + value = value + .trim() + .split('^"|"$') + .join(''); if (!CoreResource.isValidAndNotEmpty(key)) { throw new Error( - `Label key ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`); + `Label key ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}` + ); } if (!CoreResource.isValid(value)) { throw new Error( - `Label value ${CoreResource.ERROR_MESSAGE_INVALID_VALUE}`); + `Label value ${CoreResource.ERROR_MESSAGE_INVALID_VALUE}` + ); } labels[key] = value; } @@ -146,11 +157,10 @@ export class CoreResource { } return { type: resource.type || otherResource.type, - labels: Object.assign({}, otherResource.labels, resource.labels) + labels: Object.assign({}, otherResource.labels, resource.labels), }; } - /** * Determines whether the given String is a valid printable ASCII string with * a length not exceed MAX_LENGTH characters. @@ -159,8 +169,10 @@ export class CoreResource { * @returns Whether the String is valid. */ private static isValid(name: string): boolean { - return name.length <= CoreResource.MAX_LENGTH && - StringUtils.isPrintableString(name); + return ( + name.length <= CoreResource.MAX_LENGTH && + StringUtils.isPrintableString(name) + ); } /** @@ -176,9 +188,11 @@ export class CoreResource { /** TEST_ONLY */ static setup() { - CoreResource.ENV_TYPE = - CoreResource.parseResourceType(process.env.OC_RESOURCE_TYPE); - CoreResource.ENV_LABEL_MAP = - CoreResource.parseResourceLabels(process.env.OC_RESOURCE_LABELS); + CoreResource.ENV_TYPE = CoreResource.parseResourceType( + process.env.OC_RESOURCE_TYPE + ); + CoreResource.ENV_LABEL_MAP = CoreResource.parseResourceLabels( + process.env.OC_RESOURCE_LABELS + ); } } diff --git a/packages/opencensus-core/src/resource/types.ts b/packages/opencensus-core/src/resource/types.ts index 4680ab51d..edeb5ade1 100644 --- a/packages/opencensus-core/src/resource/types.ts +++ b/packages/opencensus-core/src/resource/types.ts @@ -19,7 +19,7 @@ export interface Resource { /** * An optional string which describes a well-known type of resource. */ - readonly type: string|null; + readonly type: string | null; /** * A dictionary of labels with string keys and values that provide information diff --git a/packages/opencensus-core/src/stats/bucket-boundaries.ts b/packages/opencensus-core/src/stats/bucket-boundaries.ts index bfcb7d140..dedfe4d54 100644 --- a/packages/opencensus-core/src/stats/bucket-boundaries.ts +++ b/packages/opencensus-core/src/stats/bucket-boundaries.ts @@ -16,7 +16,7 @@ import * as defaultLogger from '../common/console-logger'; import * as loggerTypes from '../common/types'; -import {Bucket} from './types'; +import { Bucket } from './types'; export class BucketBoundaries { readonly buckets: Bucket[]; @@ -53,20 +53,22 @@ export class BucketBoundaries { let negative = 0; if (!bucketBoundaries) return []; const result = bucketBoundaries.reduce( - (accumulator: number[], boundary: number, index: number) => { - if (boundary > 0) { - const nextBoundary = bucketBoundaries[index + 1]; - this.validateBoundary(boundary, nextBoundary); - accumulator.push(boundary); - } else { - negative++; - } - return accumulator; - }, - []); + (accumulator: number[], boundary: number, index: number) => { + if (boundary > 0) { + const nextBoundary = bucketBoundaries[index + 1]; + this.validateBoundary(boundary, nextBoundary); + accumulator.push(boundary); + } else { + negative++; + } + return accumulator; + }, + [] + ); if (negative) { - this.logger.warn(`Dropping ${ - negative} negative bucket boundaries, the values must be strictly > 0.`); + this.logger.warn( + `Dropping ${negative} negative bucket boundaries, the values must be strictly > 0.` + ); } return result; } diff --git a/packages/opencensus-core/src/stats/metric-producer.ts b/packages/opencensus-core/src/stats/metric-producer.ts index 9c6e68697..1ad555a93 100644 --- a/packages/opencensus-core/src/stats/metric-producer.ts +++ b/packages/opencensus-core/src/stats/metric-producer.ts @@ -14,9 +14,9 @@ * limitations under the License. */ -import {BaseMetricProducer} from '../metrics/export/base-metric-producer'; -import {Metric} from '../metrics/export/types'; -import {Stats} from './types'; +import { BaseMetricProducer } from '../metrics/export/base-metric-producer'; +import { Metric } from '../metrics/export/types'; +import { Stats } from './types'; /** * A MetricProducer producer that can be registered for exporting using diff --git a/packages/opencensus-core/src/stats/metric-utils.ts b/packages/opencensus-core/src/stats/metric-utils.ts index 2fe17c535..0a054e371 100644 --- a/packages/opencensus-core/src/stats/metric-utils.ts +++ b/packages/opencensus-core/src/stats/metric-utils.ts @@ -14,10 +14,13 @@ * limitations under the License. */ - -import {LabelValue, MetricDescriptor, MetricDescriptorType} from '../metrics/export/types'; -import {TagValue} from '../tags/types'; -import {AggregationType, Measure, MeasureType, View} from './types'; +import { + LabelValue, + MetricDescriptor, + MetricDescriptorType, +} from '../metrics/export/types'; +import { TagValue } from '../tags/types'; +import { AggregationType, Measure, MeasureType, View } from './types'; /** Utils to convert Stats data models to Metric data models */ export class MetricUtils { @@ -27,8 +30,10 @@ export class MetricUtils { * @param aggregation The aggregation for which to find a metric type * @returns The Type of metric descriptor */ - private static getType(measure: Measure, aggregation: AggregationType): - MetricDescriptorType { + private static getType( + measure: Measure, + aggregation: AggregationType + ): MetricDescriptorType { if (aggregation === AggregationType.SUM) { switch (measure.type) { case MeasureType.INT64: @@ -67,8 +72,9 @@ export class MetricUtils { unit: view.measure.unit, type: MetricUtils.getType(view.measure, view.aggregation), labelKeys: view.getColumns().map( - // TODO(mayurkale): add description - tagKey => ({key: tagKey.name, description: ''})) + // TODO(mayurkale): add description + tagKey => ({ key: tagKey.name, description: '' }) + ), }; } @@ -77,8 +83,11 @@ export class MetricUtils { * @param tagValues the list of tag values * @returns The List of label values */ - static tagValuesToLabelValues(tagValues: Array): LabelValue[] { - return tagValues.map( - (tagValue) => ({value: tagValue ? tagValue.value : null})); + static tagValuesToLabelValues( + tagValues: Array + ): LabelValue[] { + return tagValues.map(tagValue => ({ + value: tagValue ? tagValue.value : null, + })); } } diff --git a/packages/opencensus-core/src/stats/recorder.ts b/packages/opencensus-core/src/stats/recorder.ts index c82cfc527..cb953d449 100644 --- a/packages/opencensus-core/src/stats/recorder.ts +++ b/packages/opencensus-core/src/stats/recorder.ts @@ -14,19 +14,31 @@ * limitations under the License. */ -import {TagKey, TagValue} from '../tags/types'; -import {AggregationData, AggregationType, CountData, DistributionData, LastValueData, Measurement, MeasureType, SumData} from './types'; - -const UNKNOWN_TAG_VALUE: TagValue|null = null; +import { TagKey, TagValue } from '../tags/types'; +import { + AggregationData, + AggregationType, + CountData, + DistributionData, + LastValueData, + Measurement, + MeasureType, + SumData, +} from './types'; + +const UNKNOWN_TAG_VALUE: TagValue | null = null; export class Recorder { static addMeasurement( - aggregationData: AggregationData, measurement: Measurement, - attachments?: {[key: string]: string}): AggregationData { + aggregationData: AggregationData, + measurement: Measurement, + attachments?: { [key: string]: string } + ): AggregationData { aggregationData.timestamp = Date.now(); - const value = measurement.measure.type === MeasureType.DOUBLE ? - measurement.value : - Math.trunc(measurement.value); + const value = + measurement.measure.type === MeasureType.DOUBLE + ? measurement.value + : Math.trunc(measurement.value); switch (aggregationData.type) { case AggregationType.DISTRIBUTION: @@ -44,28 +56,36 @@ export class Recorder { } /** Gets the tag values from tags and columns */ - static getTagValues(tags: Map, columns: TagKey[]): - Array { + static getTagValues( + tags: Map, + columns: TagKey[] + ): Array { return columns.map( - (tagKey) => - (tags.get(tagKey) || - /** replace not found key values by null. */ UNKNOWN_TAG_VALUE)); + tagKey => + tags.get(tagKey) || + /** replace not found key values by null. */ UNKNOWN_TAG_VALUE + ); } private static addToDistribution( - distributionData: DistributionData, value: number, - attachments?: {[key: string]: string}): DistributionData { + distributionData: DistributionData, + value: number, + attachments?: { [key: string]: string } + ): DistributionData { distributionData.count += 1; - let bucketIndex = - distributionData.buckets.findIndex(bucket => bucket > value); + let bucketIndex = distributionData.buckets.findIndex( + bucket => bucket > value + ); if (bucketIndex < 0) { bucketIndex = distributionData.buckets.length; } - if (distributionData.bucketCounts && - distributionData.bucketCounts.length > bucketIndex) { + if ( + distributionData.bucketCounts && + distributionData.bucketCounts.length > bucketIndex + ) { distributionData.bucketCounts[bucketIndex] += 1; } @@ -76,22 +96,27 @@ export class Recorder { distributionData.sum += value; const oldMean = distributionData.mean; - distributionData.mean = distributionData.mean + - (value - distributionData.mean) / distributionData.count; + distributionData.mean = + distributionData.mean + + (value - distributionData.mean) / distributionData.count; distributionData.sumOfSquaredDeviation = - distributionData.sumOfSquaredDeviation + - (value - oldMean) * (value - distributionData.mean); + distributionData.sumOfSquaredDeviation + + (value - oldMean) * (value - distributionData.mean); distributionData.stdDeviation = Math.sqrt( - distributionData.sumOfSquaredDeviation / distributionData.count); + distributionData.sumOfSquaredDeviation / distributionData.count + ); // No implicit recording for exemplars - if there are no attachments // (contextual information), don't record exemplars. - if (attachments && distributionData.exemplars && - distributionData.exemplars.length > bucketIndex) { + if ( + attachments && + distributionData.exemplars && + distributionData.exemplars.length > bucketIndex + ) { distributionData.exemplars[bucketIndex] = { value, timestamp: distributionData.timestamp, - attachments + attachments, }; } return distributionData; @@ -107,8 +132,10 @@ export class Recorder { return countData; } - private static addToLastValue(lastValueData: LastValueData, value: number): - LastValueData { + private static addToLastValue( + lastValueData: LastValueData, + value: number + ): LastValueData { lastValueData.value = value; return lastValueData; } diff --git a/packages/opencensus-core/src/stats/stats.ts b/packages/opencensus-core/src/stats/stats.ts index 291635bfb..324554484 100644 --- a/packages/opencensus-core/src/stats/stats.ts +++ b/packages/opencensus-core/src/stats/stats.ts @@ -16,22 +16,30 @@ import * as defaultLogger from '../common/console-logger'; import * as loggerTypes from '../common/types'; -import {StatsEventListener} from '../exporters/types'; +import { StatsEventListener } from '../exporters/types'; import * as cls from '../internal/cls'; -import {Metric} from '../metrics/export/types'; -import {Metrics} from '../metrics/metrics'; -import {TagMap} from '../tags/tag-map'; +import { Metric } from '../metrics/export/types'; +import { Metrics } from '../metrics/metrics'; +import { TagMap } from '../tags/tag-map'; import * as tagger from '../tags/tagger'; -import {TagKey} from '../tags/types'; -import {MetricProducerForStats} from './metric-producer'; -import {AggregationType, Measure, Measurement, MeasureType, MeasureUnit, Stats, View} from './types'; -import {BaseView} from './view'; +import { TagKey } from '../tags/types'; +import { MetricProducerForStats } from './metric-producer'; +import { + AggregationType, + Measure, + Measurement, + MeasureType, + MeasureUnit, + Stats, + View, +} from './types'; +import { BaseView } from './view'; export class BaseStats implements Stats { /** A list of Stats exporters */ private statsEventListeners: StatsEventListener[] = []; /** A map of Measures (name) to their corresponding Views */ - private registeredViews: {[key: string]: View[]} = {}; + private registeredViews: { [key: string]: View[] } = {}; /** An object to log information to */ private logger: loggerTypes.Logger; /** Singleton instance */ @@ -73,6 +81,7 @@ export class BaseStats implements Stats { // Notifies all exporters for (const exporter of this.statsEventListeners) { + // tslint:disable-next-line:deprecation exporter.onRegisterView(view); } } @@ -88,11 +97,21 @@ export class BaseStats implements Stats { * distribution aggregation type */ createView( - name: string, measure: Measure, aggregation: AggregationType, - tagKeys: TagKey[], description: string, - bucketBoundaries?: number[]): View { + name: string, + measure: Measure, + aggregation: AggregationType, + tagKeys: TagKey[], + description: string, + bucketBoundaries?: number[] + ): View { const view = new BaseView( - name, measure, aggregation, tagKeys, description, bucketBoundaries); + name, + measure, + aggregation, + tagKeys, + description, + bucketBoundaries + ); return view; } @@ -105,6 +124,7 @@ export class BaseStats implements Stats { for (const measureName of Object.keys(this.registeredViews)) { for (const view of this.registeredViews[measureName]) { + // tslint:disable-next-line:deprecation exporter.onRegisterView(view); } } @@ -119,7 +139,8 @@ export class BaseStats implements Stats { unregisterExporter(exporter: StatsEventListener): void { if (exporter) { this.statsEventListeners = this.statsEventListeners.filter( - currentExporter => currentExporter !== exporter); + currentExporter => currentExporter !== exporter + ); exporter.stop(); } } @@ -130,9 +151,12 @@ export class BaseStats implements Stats { * @param unit The measure unit * @param description An optional measure description */ - createMeasureDouble(name: string, unit: MeasureUnit, description?: string): - Measure { - return {name, unit, type: MeasureType.DOUBLE, description}; + createMeasureDouble( + name: string, + unit: MeasureUnit, + description?: string + ): Measure { + return { name, unit, type: MeasureType.DOUBLE, description }; } /** @@ -142,9 +166,12 @@ export class BaseStats implements Stats { * @param unit The measure unit * @param description An optional measure description */ - createMeasureInt64(name: string, unit: MeasureUnit, description?: string): - Measure { - return {name, unit, type: MeasureType.INT64, description}; + createMeasureInt64( + name: string, + unit: MeasureUnit, + description?: string + ): Measure { + return { name, unit, type: MeasureType.INT64, description }; } /** @@ -183,8 +210,10 @@ export class BaseStats implements Stats { * string pairs. */ record( - measurements: Measurement[], tags?: TagMap, - attachments?: {[key: string]: string}): void { + measurements: Measurement[], + tags?: TagMap, + attachments?: { [key: string]: string } + ): void { if (this.hasNegativeValue(measurements)) { this.logger.warn(`Dropping measurments ${measurements}, value to record must be non-negative.`); @@ -208,6 +237,7 @@ export class BaseStats implements Stats { // Notifies all exporters for (const exporter of this.statsEventListeners) { + // tslint:disable-next-line:deprecation exporter.onRecord(views, measurement, tags.tags); } } diff --git a/packages/opencensus-core/src/stats/types.ts b/packages/opencensus-core/src/stats/types.ts index d73725095..26ca8508c 100644 --- a/packages/opencensus-core/src/stats/types.ts +++ b/packages/opencensus-core/src/stats/types.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import {StatsEventListener} from '../exporters/types'; -import {Metric} from '../metrics/export/types'; -import {TagMap} from '../tags/tag-map'; -import {TagKey, TagValue} from '../tags/types'; +import { StatsEventListener } from '../exporters/types'; +import { Metric } from '../metrics/export/types'; +import { TagMap } from '../tags/tag-map'; +import { TagKey, TagValue } from '../tags/types'; /** Default type for functions */ // tslint:disable:no-any @@ -36,9 +36,13 @@ export interface Stats { * aggregation type */ createView( - name: string, measure: Measure, aggregation: AggregationType, - tagKeys: TagKey[], description: string, - bucketBoundaries?: number[]): View; + name: string, + measure: Measure, + aggregation: AggregationType, + tagKeys: TagKey[], + description: string, + bucketBoundaries?: number[] + ): View; /** * Registers a view to listen to new measurements in its measure. @@ -52,8 +56,11 @@ export interface Stats { * @param unit The measure unit * @param description The measure description */ - createMeasureDouble(name: string, unit: MeasureUnit, description?: string): - Measure; + createMeasureDouble( + name: string, + unit: MeasureUnit, + description?: string + ): Measure; /** * Creates a measure of type Int64. Values must be integers up to @@ -62,8 +69,11 @@ export interface Stats { * @param unit The measure unit * @param description The measure description */ - createMeasureInt64(name: string, unit: MeasureUnit, description?: string): - Measure; + createMeasureInt64( + name: string, + unit: MeasureUnit, + description?: string + ): Measure; /** * Updates all views with the new measurements. @@ -76,8 +86,10 @@ export interface Stats { * string pairs. */ record( - measurements: Measurement[], tags?: TagMap, - attachments?: {[key: string]: string}): void; + measurements: Measurement[], + tags?: TagMap, + attachments?: { [key: string]: string } + ): void; /** * Remove all registered Views and exporters from the stats. @@ -144,18 +156,18 @@ export interface Measure { * by http://unitsofmeasure.org/ucum.html. */ export enum MeasureUnit { - UNIT = '1', // for general counts - BYTE = 'by', // bytes - KBYTE = 'kb', // Kbytes - SEC = 's', // seconds - MS = 'ms', // millisecond - NS = 'ns' // nanosecond + UNIT = '1', // for general counts + BYTE = 'by', // bytes + KBYTE = 'kb', // Kbytes + SEC = 's', // seconds + MS = 'ms', // millisecond + NS = 'ns', // nanosecond } /** Describes the types of a Measure. It can be Int64 or a Double type. */ export enum MeasureType { INT64 = 'INT64', - DOUBLE = 'DOUBLE' + DOUBLE = 'DOUBLE', } /** Describes a data point to be collected for a Measure. */ @@ -207,13 +219,15 @@ export interface View { * string pairs. */ recordMeasurement( - measurement: Measurement, tags: TagMap, - attachments?: {[key: string]: string}): void; + measurement: Measurement, + tags: TagMap, + attachments?: { [key: string]: string } + ): void; /** * Returns a snapshot of an AggregationData for that tags/labels values. * @param tagValues The desired data's tag values. */ - getSnapshot(tagValues: Array): AggregationData; + getSnapshot(tagValues: Array): AggregationData; /** Gets the view's tag keys */ getColumns(): TagKey[]; /** Gets view`s metric */ @@ -228,7 +242,7 @@ export enum AggregationType { COUNT = 0, SUM = 1, LAST_VALUE = 2, - DISTRIBUTION = 3 + DISTRIBUTION = 3, } /** Defines how data is collected and aggregated */ @@ -236,7 +250,7 @@ export interface AggregationMetadata { /** The aggregation type of the aggregation data */ readonly type: AggregationType; /** The tagValues that this AggregationData collects and aggregates */ - readonly tagValues: Array; + readonly tagValues: Array; /** The latest timestamp a new data point was recorded */ timestamp: number; } @@ -313,8 +327,12 @@ export interface StatsExemplar { /** The observation (sampling) time of the above value. */ readonly timestamp: number; /** Contextual information about the example value. */ - readonly attachments: {[key: string]: string}; + readonly attachments: { [key: string]: string }; } export type Bucket = number; -export type AggregationData = SumData|CountData|LastValueData|DistributionData; +export type AggregationData = + | SumData + | CountData + | LastValueData + | DistributionData; diff --git a/packages/opencensus-core/src/stats/view.ts b/packages/opencensus-core/src/stats/view.ts index 37f9397e2..65c7edc64 100644 --- a/packages/opencensus-core/src/stats/view.ts +++ b/packages/opencensus-core/src/stats/view.ts @@ -15,16 +15,36 @@ */ import * as defaultLogger from '../common/console-logger'; -import {getTimestampWithProcessHRTime, timestampFromMillis} from '../common/time-util'; +import { + getTimestampWithProcessHRTime, + timestampFromMillis, +} from '../common/time-util'; import * as loggerTypes from '../common/types'; -import {Bucket as metricBucket, DistributionValue, LabelValue, Metric, MetricDescriptor, MetricDescriptorType, Point, TimeSeries, Timestamp} from '../metrics/export/types'; -import {TagMap} from '../tags/tag-map'; -import {TagKey, TagValue} from '../tags/types'; -import {isValidTagKey} from '../tags/validation'; -import {BucketBoundaries} from './bucket-boundaries'; -import {MetricUtils} from './metric-utils'; -import {Recorder} from './recorder'; -import {AggregationData, AggregationType, Measure, Measurement, StatsExemplar, View} from './types'; +import { + Bucket as metricBucket, + DistributionValue, + LabelValue, + Metric, + MetricDescriptor, + MetricDescriptorType, + Point, + TimeSeries, + Timestamp, +} from '../metrics/export/types'; +import { TagMap } from '../tags/tag-map'; +import { TagKey, TagValue } from '../tags/types'; +import { isValidTagKey } from '../tags/validation'; +import { BucketBoundaries } from './bucket-boundaries'; +import { MetricUtils } from './metric-utils'; +import { Recorder } from './recorder'; +import { + AggregationData, + AggregationType, + Measure, + Measurement, + StatsExemplar, + View, +} from './types'; const RECORD_SEPARATOR = String.fromCharCode(30); @@ -48,7 +68,7 @@ export class BaseView implements View { * If no Tags are provided, then, all data is recorded in a single * aggregation. */ - private tagValueAggregationMap: {[key: string]: AggregationData} = {}; + private tagValueAggregationMap: { [key: string]: AggregationData } = {}; /** * A list of tag keys that represents the possible column labels */ @@ -74,8 +94,7 @@ export class BaseView implements View { /** true if the view was registered */ registered = false; /** An object to log information to */ - // @ts-ignore - private logger: loggerTypes.Logger; + logger: loggerTypes.Logger; /** * Creates a new View instance. This constructor is used by Stats. User should @@ -90,9 +109,14 @@ export class BaseView implements View { * @param logger */ constructor( - name: string, measure: Measure, aggregation: AggregationType, - tagsKeys: TagKey[], description: string, bucketBoundaries?: number[], - logger = defaultLogger) { + name: string, + measure: Measure, + aggregation: AggregationType, + tagsKeys: TagKey[], + description: string, + bucketBoundaries?: number[], + logger = defaultLogger + ) { if (aggregation === AggregationType.DISTRIBUTION && !bucketBoundaries) { throw new Error('No bucketBoundaries specified'); } @@ -126,40 +150,48 @@ export class BaseView implements View { * string pairs. */ recordMeasurement( - measurement: Measurement, tags: TagMap, - attachments?: {[key: string]: string}) { + measurement: Measurement, + tags: TagMap, + attachments?: { [key: string]: string } + ) { const tagValues = Recorder.getTagValues(tags.tags, this.columns); const encodedTags = this.encodeTagValues(tagValues); if (!this.tagValueAggregationMap[encodedTags]) { - this.tagValueAggregationMap[encodedTags] = - this.createAggregationData(tagValues); + this.tagValueAggregationMap[encodedTags] = this.createAggregationData( + tagValues + ); } Recorder.addMeasurement( - this.tagValueAggregationMap[encodedTags], measurement, attachments); + this.tagValueAggregationMap[encodedTags], + measurement, + attachments + ); } /** * Encodes a TagValue object into a value sorted string. * @param tagValues The tagValues to encode */ - private encodeTagValues(tagValues: Array): string { - return tagValues.map((tagValue) => tagValue ? tagValue.value : null) - .sort() - .join(RECORD_SEPARATOR); + private encodeTagValues(tagValues: Array): string { + return tagValues + .map(tagValue => (tagValue ? tagValue.value : null)) + .sort() + .join(RECORD_SEPARATOR); } /** * Creates an empty aggregation data for a given tags. * @param tagValues The tags for that aggregation data */ - private createAggregationData(tagValues: Array): - AggregationData { - const aggregationMetadata = {tagValues, timestamp: Date.now()}; + private createAggregationData( + tagValues: Array + ): AggregationData { + const aggregationMetadata = { tagValues, timestamp: Date.now() }; switch (this.aggregation) { case AggregationType.DISTRIBUTION: - const {buckets, bucketCounts} = this.bucketBoundaries!; + const { buckets, bucketCounts } = this.bucketBoundaries!; const bucketsCopy = Object.assign([], buckets); const bucketCountsCopy = Object.assign([], bucketCounts); const exemplars = new Array(bucketCounts.length); @@ -175,17 +207,21 @@ export class BaseView implements View { sumOfSquaredDeviation: 0, buckets: bucketsCopy, bucketCounts: bucketCountsCopy, - exemplars + exemplars, }; case AggregationType.SUM: - return {...aggregationMetadata, type: AggregationType.SUM, value: 0}; + return { ...aggregationMetadata, type: AggregationType.SUM, value: 0 }; case AggregationType.COUNT: - return {...aggregationMetadata, type: AggregationType.COUNT, value: 0}; + return { + ...aggregationMetadata, + type: AggregationType.COUNT, + value: 0, + }; default: return { ...aggregationMetadata, type: AggregationType.LAST_VALUE, - value: 0 + value: 0, }; } } @@ -196,31 +232,34 @@ export class BaseView implements View { * @returns The Metric. */ getMetric(start: number): Metric { - const {type} = this.metricDescriptor; + const { type } = this.metricDescriptor; let startTimestamp: Timestamp; // The moment when this point was recorded. const now: Timestamp = getTimestampWithProcessHRTime(); - if (type !== MetricDescriptorType.GAUGE_INT64 && - type !== MetricDescriptorType.GAUGE_DOUBLE) { + if ( + type !== MetricDescriptorType.GAUGE_INT64 && + type !== MetricDescriptorType.GAUGE_DOUBLE + ) { startTimestamp = timestampFromMillis(start); } const timeseries: TimeSeries[] = []; Object.keys(this.tagValueAggregationMap).forEach(key => { - const {tagValues} = this.tagValueAggregationMap[key]; - const labelValues: LabelValue[] = - MetricUtils.tagValuesToLabelValues(tagValues); + const { tagValues } = this.tagValueAggregationMap[key]; + const labelValues: LabelValue[] = MetricUtils.tagValuesToLabelValues( + tagValues + ); const point: Point = this.toPoint(now, this.getSnapshot(tagValues)); if (startTimestamp) { - timeseries.push({startTimestamp, labelValues, points: [point]}); + timeseries.push({ startTimestamp, labelValues, points: [point] }); } else { - timeseries.push({labelValues, points: [point]}); + timeseries.push({ labelValues, points: [point] }); } }); - return {descriptor: this.metricDescriptor, timeseries}; + return { descriptor: this.metricDescriptor, timeseries }; } /** @@ -231,7 +270,7 @@ export class BaseView implements View { */ private toPoint(timestamp: Timestamp, data: AggregationData): Point { if (data.type === AggregationType.DISTRIBUTION) { - const {count, sum, sumOfSquaredDeviation, exemplars} = data; + const { count, sum, sumOfSquaredDeviation, exemplars } = data; const buckets = []; if (data.bucketCounts) { for (let bucket = 0; bucket < data.bucketCounts.length; bucket++) { @@ -245,12 +284,12 @@ export class BaseView implements View { sum, sumOfSquaredDeviation, buckets, - bucketOptions: {explicit: {bounds: data.buckets}}, + bucketOptions: { explicit: { bounds: data.buckets } }, }; - return {timestamp, value}; + return { timestamp, value }; } else { const value: number = data.value; - return {timestamp, value}; + return { timestamp, value }; } } @@ -259,13 +298,15 @@ export class BaseView implements View { * @param tags The desired data's tags * @returns The AggregationData. */ - getSnapshot(tagValues: Array): AggregationData { + getSnapshot(tagValues: Array): AggregationData { return this.tagValueAggregationMap[this.encodeTagValues(tagValues)]; } /** Returns a Bucket with count and examplar (if present) */ - private getMetricBucket(bucketCount: number, statsExemplar?: StatsExemplar): - metricBucket { + private getMetricBucket( + bucketCount: number, + statsExemplar?: StatsExemplar + ): metricBucket { if (statsExemplar) { // Bucket with an Exemplar. return { @@ -273,24 +314,25 @@ export class BaseView implements View { exemplar: { value: statsExemplar.value, timestamp: timestampFromMillis(statsExemplar.timestamp), - attachments: statsExemplar.attachments - } + attachments: statsExemplar.attachments, + }, }; } // Bucket with no Exemplar. - return {count: bucketCount}; + return { count: bucketCount }; } /** Determines whether the given TagKeys are valid. */ private validateTagKeys(tagKeys: TagKey[]): TagKey[] { const tagKeysCopy = Object.assign([], tagKeys); - tagKeysCopy.forEach((tagKey) => { + tagKeysCopy.forEach(tagKey => { if (!isValidTagKey(tagKey)) { throw new Error(`Invalid TagKey name: ${tagKey}`); } }); - const tagKeysSet = - new Set(tagKeysCopy.map((tagKey: TagKey) => tagKey.name)); + const tagKeysSet = new Set( + tagKeysCopy.map((tagKey: TagKey) => tagKey.name) + ); if (tagKeysSet.size !== tagKeysCopy.length) { throw new Error('Columns have duplicate'); } diff --git a/packages/opencensus-core/src/tags/propagation/binary-serializer.ts b/packages/opencensus-core/src/tags/propagation/binary-serializer.ts index 5f7f279e7..0092d0b6c 100644 --- a/packages/opencensus-core/src/tags/propagation/binary-serializer.ts +++ b/packages/opencensus-core/src/tags/propagation/binary-serializer.ts @@ -44,9 +44,9 @@ * */ -import {TagMap} from '../tag-map'; -import {TagKey, TagValue} from '../types'; -import {DecodeVarint, EncodeVarint} from './variant-encoding'; +import { TagMap } from '../tag-map'; +import { TagKey, TagValue } from '../types'; +import { DecodeVarint, EncodeVarint } from './variant-encoding'; // This size limit only applies to the bytes representing tag keys and values. export const TAG_MAP_SERIALIZED_SIZE_LIMIT = 8192; @@ -72,8 +72,9 @@ export function serializeBinary(tagMap: TagMap): Buffer { }); if (totalChars > TAG_MAP_SERIALIZED_SIZE_LIMIT) { - throw new Error(`Size of TagMap exceeds the maximum serialized size ${ - TAG_MAP_SERIALIZED_SIZE_LIMIT}`); + throw new Error( + `Size of TagMap exceeds the maximum serialized size ${TAG_MAP_SERIALIZED_SIZE_LIMIT}` + ); } return Buffer.from(byteArray); } @@ -88,8 +89,9 @@ export function deserializeBinary(buffer: Buffer): TagMap { } const versionId = buffer.readInt8(VERSION_ID_INDEX); if (versionId > VERSION_ID) { - throw new Error(`Wrong Version ID: ${ - versionId}. Currently supports version up to: ${VERSION_ID}`); + throw new Error( + `Wrong Version ID: ${versionId}. Currently supports version up to: ${VERSION_ID}` + ); } return parseTags(buffer); } @@ -131,10 +133,11 @@ function parseTags(buffer: Buffer): TagMap { currentIndex += 1; if (totalChars > TAG_MAP_SERIALIZED_SIZE_LIMIT) { - throw new Error(`Size of TagMap exceeds the maximum serialized size ${ - TAG_MAP_SERIALIZED_SIZE_LIMIT}`); + throw new Error( + `Size of TagMap exceeds the maximum serialized size ${TAG_MAP_SERIALIZED_SIZE_LIMIT}` + ); } else { - tags.set({name: key}, {value: val}); + tags.set({ name: key }, { value: val }); } } return tags; diff --git a/packages/opencensus-core/src/tags/propagation/text-format.ts b/packages/opencensus-core/src/tags/propagation/text-format.ts index 81d2a07b8..0a2d0f238 100644 --- a/packages/opencensus-core/src/tags/propagation/text-format.ts +++ b/packages/opencensus-core/src/tags/propagation/text-format.ts @@ -23,8 +23,8 @@ * https://github.com/w3c/correlation-context/blob/master/correlation_context/HTTP_HEADER_FORMAT.md */ -import {TagMap} from '../tag-map'; -import {TagKey, TagTtl, TagValue, TagValueWithMetadata} from '../types'; +import { TagMap } from '../tag-map'; +import { TagKey, TagTtl, TagValue, TagValueWithMetadata } from '../types'; export const MAX_NUMBER_OF_TAGS = 180; const TAG_SERIALIZED_SIZE_LIMIT = 4096; @@ -32,7 +32,7 @@ const TAGMAP_SERIALIZED_SIZE_LIMIT = 8192; const TAG_KEY_VALUE_DELIMITER = '='; const TAG_DELIMITER = ','; const UNLIMITED_PROPAGATION_MD = { - tagTtl: TagTtl.UNLIMITED_PROPAGATION + tagTtl: TagTtl.UNLIMITED_PROPAGATION, }; /** @@ -49,20 +49,22 @@ export function serializeTextFormat(tagMap: TagMap): string { if (tagsWithMetadata.tagMetadata.tagTtl !== TagTtl.NO_PROPAGATION) { if (ret.length > 0) ret += TAG_DELIMITER; totalChars += validateTag(tagKey, tagsWithMetadata.tagValue); - ret += tagKey.name + TAG_KEY_VALUE_DELIMITER + - tagsWithMetadata.tagValue.value; + ret += + tagKey.name + TAG_KEY_VALUE_DELIMITER + tagsWithMetadata.tagValue.value; totalTags++; } }); if (totalTags > MAX_NUMBER_OF_TAGS) { throw new Error( - `Number of tags in the TagMap exceeds limit ${MAX_NUMBER_OF_TAGS}`); + `Number of tags in the TagMap exceeds limit ${MAX_NUMBER_OF_TAGS}` + ); } if (totalChars > TAGMAP_SERIALIZED_SIZE_LIMIT) { - throw new Error(`Size of TagMap exceeds the maximum serialized size ${ - TAGMAP_SERIALIZED_SIZE_LIMIT}`); + throw new Error( + `Size of TagMap exceeds the maximum serialized size ${TAGMAP_SERIALIZED_SIZE_LIMIT}` + ); } return ret; @@ -76,12 +78,12 @@ export function deserializeTextFormat(str: string): TagMap { const tags = new TagMap(); if (!str) return tags; const listOfTags = str.split(TAG_DELIMITER); - listOfTags.forEach((tag) => { + listOfTags.forEach(tag => { const keyValuePair = tag.split(TAG_KEY_VALUE_DELIMITER); if (keyValuePair.length !== 2) throw new Error(`Malformed tag ${tag}`); const [name, value] = keyValuePair; - tags.set({name}, {value}, UNLIMITED_PROPAGATION_MD); + tags.set({ name }, { value }, UNLIMITED_PROPAGATION_MD); }); return tags; } @@ -90,7 +92,8 @@ function validateTag(tagKey: TagKey, tagValue: TagValue) { const charsOfTag = tagKey.name.length + tagValue.value.length; if (charsOfTag > TAG_SERIALIZED_SIZE_LIMIT) { throw new Error( - `Serialized size of tag exceeds limit ${TAG_SERIALIZED_SIZE_LIMIT}`); + `Serialized size of tag exceeds limit ${TAG_SERIALIZED_SIZE_LIMIT}` + ); } return charsOfTag; } diff --git a/packages/opencensus-core/src/tags/propagation/variant-encoding.ts b/packages/opencensus-core/src/tags/propagation/variant-encoding.ts index 8b45c3a6e..e390055b9 100644 --- a/packages/opencensus-core/src/tags/propagation/variant-encoding.ts +++ b/packages/opencensus-core/src/tags/propagation/variant-encoding.ts @@ -19,7 +19,7 @@ const MSB = 0x80; // The REST indicates the lower 7 bits of each byte. -const REST = 0x7F; +const REST = 0x7f; /** * Encodes a number in a variable-length encoding, 7 bits per byte. @@ -30,7 +30,7 @@ export function EncodeVarint(value: number) { do { const bits = value & REST; value >>>= 7; - const b = bits + ((value !== 0) ? MSB : 0); + const b = bits + (value !== 0 ? MSB : 0); ret.push(b); } while (value !== 0); return ret; diff --git a/packages/opencensus-core/src/tags/tag-map.ts b/packages/opencensus-core/src/tags/tag-map.ts index ed4735e58..d2376a2ea 100644 --- a/packages/opencensus-core/src/tags/tag-map.ts +++ b/packages/opencensus-core/src/tags/tag-map.ts @@ -14,18 +14,26 @@ * limitations under the License. */ -import {TagKey, TagMetadata, TagTtl, TagValue, TagValueWithMetadata} from './types'; -import {isValidTagKey, isValidTagValue} from './validation'; +import { + TagKey, + TagMetadata, + TagTtl, + TagValue, + TagValueWithMetadata, +} from './types'; +import { isValidTagKey, isValidTagValue } from './validation'; const UNLIMITED_PROPAGATION_MD = { - tagTtl: TagTtl.UNLIMITED_PROPAGATION + tagTtl: TagTtl.UNLIMITED_PROPAGATION, }; /** TagMap is maps of TagKey -> TagValueWithMetadata */ export class TagMap { // A map mapping TagKey to to its respective TagValueWithMetadata. - private readonly registeredTags: Map = - new Map(); + private readonly registeredTags: Map< + TagKey, + TagValueWithMetadata + > = new Map(); /** * Adds the key/value pair regardless of whether the key is present. @@ -79,11 +87,13 @@ export class TagMap { * For backwards-compatibility this method still produces propagating Tags * (UNLIMITED_PROPAGATION) if tagMetadata is not provided or missing. */ - private getValueWithMetadata(tagValue: TagValue, tagMetadata?: TagMetadata): - TagValueWithMetadata { + private getValueWithMetadata( + tagValue: TagValue, + tagMetadata?: TagMetadata + ): TagValueWithMetadata { if (tagMetadata) { - return {tagValue, tagMetadata}; + return { tagValue, tagMetadata }; } - return {tagValue, tagMetadata: UNLIMITED_PROPAGATION_MD}; + return { tagValue, tagMetadata: UNLIMITED_PROPAGATION_MD }; } } diff --git a/packages/opencensus-core/src/tags/tagger.ts b/packages/opencensus-core/src/tags/tagger.ts index 5a9f8d274..1ddbdbdb2 100644 --- a/packages/opencensus-core/src/tags/tagger.ts +++ b/packages/opencensus-core/src/tags/tagger.ts @@ -15,7 +15,7 @@ */ import * as cls from '../internal/cls'; -import {TagMap} from './tag-map'; +import { TagMap } from './tag-map'; export const EMPTY_TAG_MAP = new TagMap(); const CURRENT_TAG_MAP_KEY = 'current_tag_map'; @@ -34,7 +34,9 @@ export function getCurrentTagContext(contextManager: cls.Namespace): TagMap { * @param tags The TagMap. */ export function setCurrentTagContext( - contextManager: cls.Namespace, tags: TagMap) { + contextManager: cls.Namespace, + tags: TagMap +) { contextManager.set(CURRENT_TAG_MAP_KEY, makeDeepCopy(tags)); } @@ -46,7 +48,10 @@ export function setCurrentTagContext( * @returns The callback return. */ export function withTagContext( - contextManager: cls.Namespace, tags: TagMap, fn: cls.Func): T { + contextManager: cls.Namespace, + tags: TagMap, + fn: cls.Func +): T { const oldContext = getCurrentTagContext(contextManager); return contextManager.runAndReturn(() => { const newContext = new TagMap(); @@ -70,7 +75,10 @@ function makeDeepCopy(tags: TagMap) { const tagsCopy = new TagMap(); for (const [tagKey, valueWithMetadata] of tags.tagsWithMetadata) { tagsCopy.set( - tagKey, valueWithMetadata.tagValue, valueWithMetadata.tagMetadata); + tagKey, + valueWithMetadata.tagValue, + valueWithMetadata.tagMetadata + ); } return tagsCopy; } diff --git a/packages/opencensus-core/src/tags/types.ts b/packages/opencensus-core/src/tags/types.ts index 8cf0bb32b..e3cb1ca5e 100644 --- a/packages/opencensus-core/src/tags/types.ts +++ b/packages/opencensus-core/src/tags/types.ts @@ -58,5 +58,5 @@ export enum TagTtl { NO_PROPAGATION = 0, /** UNLIMITED_PROPAGATION can propagate unlimited hops. */ - UNLIMITED_PROPAGATION = -1 + UNLIMITED_PROPAGATION = -1, } diff --git a/packages/opencensus-core/src/tags/validation.ts b/packages/opencensus-core/src/tags/validation.ts index 4e9d18c89..752bd702e 100644 --- a/packages/opencensus-core/src/tags/validation.ts +++ b/packages/opencensus-core/src/tags/validation.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {TagKey, TagValue} from './types'; +import { TagKey, TagValue } from './types'; const nonPrintableCharsRegex = /[^\u0020-\u007e]/; const TAG_KEY_MAX_LENGTH = 255; @@ -24,8 +24,11 @@ export function isValidTagKey(tagKey: TagKey): boolean { if (!tagKey || !tagKey.name) { return false; } - return isPrintableString(tagKey.name) && tagKey.name.length > 0 && - tagKey.name.length <= TAG_KEY_MAX_LENGTH; + return ( + isPrintableString(tagKey.name) && + tagKey.name.length > 0 && + tagKey.name.length <= TAG_KEY_MAX_LENGTH + ); } /** Determines whether the given String is a valid tag value. */ @@ -33,8 +36,10 @@ export function isValidTagValue(tagValue: TagValue): boolean { if (!tagValue || tagValue.value === null || tagValue.value === undefined) { return false; } - return isPrintableString(tagValue.value) && - tagValue.value.length <= TAG_KEY_MAX_LENGTH; + return ( + isPrintableString(tagValue.value) && + tagValue.value.length <= TAG_KEY_MAX_LENGTH + ); } function isPrintableString(name: string): boolean { diff --git a/packages/opencensus-core/src/trace/config/types.ts b/packages/opencensus-core/src/trace/config/types.ts index 116778d18..266b2a98a 100644 --- a/packages/opencensus-core/src/trace/config/types.ts +++ b/packages/opencensus-core/src/trace/config/types.ts @@ -14,12 +14,12 @@ * limitations under the License. */ -import {Logger} from '../../common/types'; -import {Exporter} from '../../exporters/types'; -import {Stats} from '../../stats/types'; -import {PluginNames} from '../instrumentation/types'; -import {Attributes} from '../model/types'; -import {Propagation} from '../propagation/types'; +import { Logger } from '../../common/types'; +import { Exporter } from '../../exporters/types'; +import { Stats } from '../../stats/types'; +import { PluginNames } from '../instrumentation/types'; +import { Attributes } from '../model/types'; +import { Propagation } from '../propagation/types'; /** Interface configuration for a buffer. */ export interface BufferConfig { @@ -93,4 +93,4 @@ export interface TraceParams { numberOfLinksPerSpan?: number; } -export type Config = TracingConfig&TracerConfig&BufferConfig; +export type Config = TracingConfig & TracerConfig & BufferConfig; diff --git a/packages/opencensus-core/src/trace/instrumentation/base-plugin.ts b/packages/opencensus-core/src/trace/instrumentation/base-plugin.ts index 9bc6d44b9..228cef1bc 100644 --- a/packages/opencensus-core/src/trace/instrumentation/base-plugin.ts +++ b/packages/opencensus-core/src/trace/instrumentation/base-plugin.ts @@ -16,19 +16,19 @@ import * as path from 'path'; import * as semver from 'semver'; -import {noopLogger} from '../../common/noop-logger'; -import {Logger} from '../../common/types'; -import {Stats} from '../../stats/types'; +import { noopLogger } from '../../common/noop-logger'; +import { Logger } from '../../common/types'; +import { Stats } from '../../stats/types'; import * as modelTypes from '../model/types'; import * as types from './types'; /** * Maps a name (key) representing a internal file module and its exports */ -export type ModuleExportsMapping = { +export interface ModuleExportsMapping { // tslint:disable-next-line:no-any [key: string]: any; -}; +} /** This class represent the base to patch plugin. */ export abstract class BasePlugin implements types.Plugin { @@ -72,9 +72,14 @@ export abstract class BasePlugin implements types.Plugin { * @param stats a stats instance */ private setPluginContext( - // tslint:disable-next-line:no-any - moduleExports: any, tracer: modelTypes.Tracer, version: string, - options: types.PluginConfig, basedir?: string, stats?: Stats) { + // tslint:disable-next-line:no-any + moduleExports: any, + tracer: modelTypes.Tracer, + version: string, + options: types.PluginConfig, + basedir?: string, + stats?: Stats + ) { this.moduleExports = moduleExports; this.tracer = tracer; this.version = version; @@ -100,10 +105,21 @@ export abstract class BasePlugin implements types.Plugin { * @param stats an optional stats instance */ enable( - moduleExports: T, tracer: modelTypes.Tracer, version: string, - options: types.PluginConfig, basedir?: string, stats?: Stats) { + moduleExports: T, + tracer: modelTypes.Tracer, + version: string, + options: types.PluginConfig, + basedir?: string, + stats?: Stats + ) { this.setPluginContext( - moduleExports, tracer, version, options, basedir, stats); + moduleExports, + tracer, + version, + options, + basedir, + stats + ); return this.applyPatch(); } @@ -123,7 +139,6 @@ export abstract class BasePlugin implements types.Plugin { protected abstract applyPatch(): any; protected abstract applyUnpatch(): void; - /** * Load internal files according to version range */ @@ -135,43 +150,54 @@ export abstract class BasePlugin implements types.Plugin { if (semver.satisfies(this.version, versionRange)) { if (result) { this.logger.warn( - 'Plugin for %s@%s, has overlap version range (%s) for internal files: %o', - this.moduleName, this.version, versionRange, - this.internalFileList); + 'Plugin for %s@%s, has overlap version range (%s) for internal files: %o', + this.moduleName, + this.version, + versionRange, + this.internalFileList + ); } result = this.loadInternalModuleFiles( - this.internalFileList[versionRange], this.basedir); + this.internalFileList[versionRange], + this.basedir + ); } }); if (Object.keys(result).length === 0) { this.logger.debug( - 'No internal file could be loaded for %s@%s', this.moduleName, - this.version); + 'No internal file could be loaded for %s@%s', + this.moduleName, + this.version + ); } } return result; } - /** * Load internal files from a module and set internalFilesExports */ private loadInternalModuleFiles( - extraModulesList: types.PluginInternalFilesVersion, - basedir: string): ModuleExportsMapping { + extraModulesList: types.PluginInternalFilesVersion, + basedir: string + ): ModuleExportsMapping { const extraModules: ModuleExportsMapping = {}; if (extraModulesList) { Object.keys(extraModulesList).forEach(moduleName => { try { this.logger.debug('loading File %s', extraModulesList[moduleName]); - extraModules[moduleName] = - require(path.join(basedir, extraModulesList[moduleName])); + extraModules[moduleName] = require(path.join( + basedir, + extraModulesList[moduleName] + )); } catch (e) { this.logger.error( - 'Could not load internal file %s of module %s. Error: %s', - path.join(basedir, extraModulesList[moduleName]), this.moduleName, - e.message); + 'Could not load internal file %s of module %s. Error: %s', + path.join(basedir, extraModulesList[moduleName]), + this.moduleName, + e.message + ); } }); } diff --git a/packages/opencensus-core/src/trace/instrumentation/types.ts b/packages/opencensus-core/src/trace/instrumentation/types.ts index 8e4deb0b5..66851f4fd 100644 --- a/packages/opencensus-core/src/trace/instrumentation/types.ts +++ b/packages/opencensus-core/src/trace/instrumentation/types.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {Stats} from '../../stats/types'; -import {Span, TracerBase} from '../model/types'; +import { Stats } from '../../stats/types'; +import { Span, TracerBase } from '../model/types'; /** Interface Plugin to apply patch. */ export interface Plugin { @@ -30,8 +30,13 @@ export interface Plugin { * @param stats an optional stats instance */ enable( - moduleExports: T, tracer: TracerBase, version: string, - options: PluginConfig, basedir?: string, stats?: Stats): T; + moduleExports: T, + tracer: TracerBase, + version: string, + options: PluginConfig, + basedir?: string, + stats?: Stats + ): T; /** Method to disable the instrumentation */ disable(): void; } @@ -45,33 +50,34 @@ export interface CustomAttributeFunction { (span: Span, ...rest: any[]): void; } -export type PluginConfig = { +export interface PluginConfig { // tslint:disable-next-line:no-any [key: string]: any; applyCustomAttributesOnSpan?: CustomAttributeFunction; -}; +} -export type NamedPluginConfig = { - module: string; config: PluginConfig; -}; +export interface NamedPluginConfig { + module: string; + config: PluginConfig; +} /** * Type PluginNames: each key should be the name of the module to trace, * and its value should be the name of the package which has the * plugin implementation. */ -export type PluginNames = { - [pluginName: string]: string|NamedPluginConfig; -}; +export interface PluginNames { + [pluginName: string]: string | NamedPluginConfig; +} -export type PluginInternalFilesVersion = { +export interface PluginInternalFilesVersion { [pluginName: string]: string; -}; +} /** * Each key should be the name of the module to trace, and its value * a mapping of a property name to a internal plugin file name. */ -export type PluginInternalFiles = { +export interface PluginInternalFiles { [versions: string]: PluginInternalFilesVersion; -}; +} diff --git a/packages/opencensus-core/src/trace/model/no-record/no-record-root-span.ts b/packages/opencensus-core/src/trace/model/no-record/no-record-root-span.ts index 7b673bc7b..0e821ad1a 100644 --- a/packages/opencensus-core/src/trace/model/no-record/no-record-root-span.ts +++ b/packages/opencensus-core/src/trace/model/no-record/no-record-root-span.ts @@ -16,7 +16,7 @@ import * as logger from '../../../common/console-logger'; import * as types from '../types'; -import {NoRecordSpan} from './no-record-span'; +import { NoRecordSpan } from './no-record-span'; /** Implementation for the Span class that does not record trace events. */ export class NoRecordRootSpan extends NoRecordSpan { @@ -43,8 +43,13 @@ export class NoRecordRootSpan extends NoRecordSpan { * @param traceState Optional traceState. */ constructor( - tracer: types.TracerBase, name: string, kind: types.SpanKind, - traceId: string, parentSpanId: string, traceState?: types.TraceState) { + tracer: types.TracerBase, + name: string, + kind: types.SpanKind, + traceId: string, + parentSpanId: string, + traceState?: types.TraceState + ) { super(); this.tracer = tracer; this.traceIdLocal = traceId; @@ -73,7 +78,7 @@ export class NoRecordRootSpan extends NoRecordSpan { } /** No-op implementation of this method. */ - get traceState(): types.TraceState|undefined { + get traceState(): types.TraceState | undefined { return this.traceStateLocal; } diff --git a/packages/opencensus-core/src/trace/model/no-record/no-record-span.ts b/packages/opencensus-core/src/trace/model/no-record/no-record-span.ts index 42bb1c80c..270ee94d3 100644 --- a/packages/opencensus-core/src/trace/model/no-record/no-record-span.ts +++ b/packages/opencensus-core/src/trace/model/no-record/no-record-span.ts @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {noopLogger} from '../../../common/noop-logger'; -import {Logger} from '../../../common/types'; -import {randomSpanId} from '../../../internal/util'; +import { noopLogger } from '../../../common/noop-logger'; +import { Logger } from '../../../common/types'; +import { randomSpanId } from '../../../internal/util'; import * as configTypes from '../../config/types'; import * as types from '../types'; const STATUS_OK = { - code: types.CanonicalCode.OK + code: types.CanonicalCode.OK, }; /** Implementation for the SpanBase class that does not record trace events. */ @@ -29,9 +29,6 @@ export class NoRecordSpan implements types.Span { private startedLocal = false; /** Indicates if this span was ended */ private endedLocal = false; - /** Indicates if this span was forced to end */ - // @ts-ignore - private truncated = false; /** The Span ID of this span */ readonly id: string; /** An object to log information to */ @@ -91,7 +88,7 @@ export class NoRecordSpan implements types.Span { } /** Gets the trace state */ - get traceState(): types.TraceState|undefined { + get traceState(): types.TraceState | undefined { return undefined; } @@ -144,7 +141,7 @@ export class NoRecordSpan implements types.Span { traceId: this.traceId, spanId: this.id, options: 0, - traceState: this.traceState + traceState: this.traceState, }; } @@ -154,21 +151,31 @@ export class NoRecordSpan implements types.Span { } /** No-op implementation of this method. */ - addAttribute(key: string, value: string|number|boolean|object) {} + addAttribute(key: string, value: string | number | boolean | object) {} /** No-op implementation of this method. */ addAnnotation( - description: string, attributes?: types.Attributes, timestamp = 0) {} + description: string, + attributes?: types.Attributes, + timestamp = 0 + ) {} /** No-op implementation of this method. */ addLink( - traceId: string, spanId: string, type: types.LinkType, - attributes?: types.Attributes) {} + traceId: string, + spanId: string, + type: types.LinkType, + attributes?: types.Attributes + ) {} /** No-op implementation of this method. */ addMessageEvent( - type: types.MessageEventType, id: number, timestamp = 0, - uncompressedSize?: number, compressedSize?: number) {} + type: types.MessageEventType, + id: number, + timestamp = 0, + uncompressedSize?: number, + compressedSize?: number + ) {} /** No-op implementation of this method. */ setStatus(code: types.CanonicalCode, message?: string) {} diff --git a/packages/opencensus-core/src/trace/model/root-span.ts b/packages/opencensus-core/src/trace/model/root-span.ts index 300f3bf9f..784951eb3 100644 --- a/packages/opencensus-core/src/trace/model/root-span.ts +++ b/packages/opencensus-core/src/trace/model/root-span.ts @@ -15,7 +15,7 @@ */ import * as logger from '../../common/console-logger'; -import {Span} from './span'; +import { Span } from './span'; import * as types from './types'; /** Defines a root span */ @@ -41,8 +41,13 @@ export class RootSpan extends Span { * @param traceState An optional traceState. */ constructor( - tracer: types.TracerBase, name: string, kind: types.SpanKind, - traceId: string, parentSpanId: string, traceState?: types.TraceState) { + tracer: types.TracerBase, + name: string, + kind: types.SpanKind, + traceId: string, + parentSpanId: string, + traceState?: types.TraceState + ) { super(tracer); this.traceIdLocal = traceId; this.name = name; @@ -66,7 +71,7 @@ export class RootSpan extends Span { } /** Gets trace state from rootspan instance */ - get traceState(): types.TraceState|undefined { + get traceState(): types.TraceState | undefined { return this.traceStateLocal; } diff --git a/packages/opencensus-core/src/trace/model/span.ts b/packages/opencensus-core/src/trace/model/span.ts index d8f6cd6ac..a285b761a 100644 --- a/packages/opencensus-core/src/trace/model/span.ts +++ b/packages/opencensus-core/src/trace/model/span.ts @@ -13,17 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {noopLogger} from '../../common/noop-logger'; -import {Logger} from '../../common/types'; -import {Clock} from '../../internal/clock'; -import {randomSpanId} from '../../internal/util'; +import { noopLogger } from '../../common/noop-logger'; +import { Logger } from '../../common/types'; +import { Clock } from '../../internal/clock'; +import { randomSpanId } from '../../internal/util'; import * as configTypes from '../config/types'; -import {NoRecordSpan} from './no-record/no-record-span'; +import { NoRecordSpan } from './no-record/no-record-span'; import * as types from './types'; const STATUS_OK = { - code: types.CanonicalCode.OK + code: types.CanonicalCode.OK, }; /** Defines a base model for spans. */ @@ -37,9 +37,6 @@ export class Span implements types.Span { private startedLocal = false; /** Indicates if this span was ended */ private endedLocal = false; - /** Indicates if this span was forced to end */ - // @ts-ignore - private truncated = false; /** A list of child spans which are immediate, local children of this span */ private spansLocal: types.Span[]; /** The Span ID of this span */ @@ -105,7 +102,7 @@ export class Span implements types.Span { } /** Gets the trace state */ - get traceState(): types.TraceState|undefined { + get traceState(): types.TraceState | undefined { return this.root.traceState; } @@ -193,8 +190,8 @@ export class Span implements types.Span { return { traceId: this.traceId, spanId: this.id, - options: 0x1, // always traced - traceState: this.traceState + options: 0x1, // always traced + traceState: this.traceState, }; } @@ -204,13 +201,15 @@ export class Span implements types.Span { * @param value The result of an operation. If the value is a typeof object * it has to be JSON.stringify-able, cannot contain circular dependencies. */ - addAttribute(key: string, value: string|number|boolean|object) { + addAttribute(key: string, value: string | number | boolean | object) { if (this.attributes[key]) { delete this.attributes[key]; } - if (Object.keys(this.attributes).length >= - this.activeTraceParams.numberOfAttributesPerSpan!) { + if ( + Object.keys(this.attributes).length >= + this.activeTraceParams.numberOfAttributesPerSpan! + ) { this.droppedAttributesCount++; const attributeKeyToDelete = Object.keys(this.attributes).shift(); if (attributeKeyToDelete) { @@ -218,7 +217,7 @@ export class Span implements types.Span { } } const serializedValue = - typeof value === 'object' ? JSON.stringify(value) : value; + typeof value === 'object' ? JSON.stringify(value) : value; this.attributes[key] = serializedValue; } @@ -229,14 +228,18 @@ export class Span implements types.Span { * @param timestamp A time, in milliseconds. Defaults to Date.now() */ addAnnotation( - description: string, attributes: types.Attributes = {}, - timestamp = Date.now()) { - if (this.annotations.length >= - this.activeTraceParams.numberOfAnnontationEventsPerSpan!) { + description: string, + attributes: types.Attributes = {}, + timestamp = Date.now() + ) { + if ( + this.annotations.length >= + this.activeTraceParams.numberOfAnnontationEventsPerSpan! + ) { this.annotations.shift(); this.droppedAnnotationsCount++; } - this.annotations.push({description, attributes, timestamp}); + this.annotations.push({ description, attributes, timestamp }); } /** @@ -247,14 +250,17 @@ export class Span implements types.Span { * @param attributes A set of attributes on the link. */ addLink( - traceId: string, spanId: string, type: types.LinkType, - attributes: types.Attributes = {}) { + traceId: string, + spanId: string, + type: types.LinkType, + attributes: types.Attributes = {} + ) { if (this.links.length >= this.activeTraceParams.numberOfLinksPerSpan!) { this.links.shift(); this.droppedLinksCount++; } - this.links.push({traceId, spanId, type, attributes}); + this.links.push({ traceId, spanId, type, attributes }); } /** @@ -267,10 +273,16 @@ export class Span implements types.Span { * zero or undefined, assumed to be the same size as uncompressed. */ addMessageEvent( - type: types.MessageEventType, id: number, timestamp = Date.now(), - uncompressedSize?: number, compressedSize?: number) { - if (this.messageEvents.length >= - this.activeTraceParams.numberOfMessageEventsPerSpan!) { + type: types.MessageEventType, + id: number, + timestamp = Date.now(), + uncompressedSize?: number, + compressedSize?: number + ) { + if ( + this.messageEvents.length >= + this.activeTraceParams.numberOfMessageEventsPerSpan! + ) { this.messageEvents.shift(); this.droppedMessageEventsCount++; } @@ -290,15 +302,18 @@ export class Span implements types.Span { * @param message optional A developer-facing error message. */ setStatus(code: types.CanonicalCode, message?: string) { - this.status = {code, message}; + this.status = { code, message }; } /** Starts the span. */ start() { if (this.started) { this.logger.debug( - 'calling %s.start() on already started %s %o', this.className, - this.className, {id: this.id, name: this.name, type: this.kind}); + 'calling %s.start() on already started %s %o', + this.className, + this.className, + { id: this.id, name: this.name, type: this.kind } + ); return; } this.clock = new Clock(); @@ -308,7 +323,7 @@ export class Span implements types.Span { id: this.id, name: this.name, parentSpanId: this.parentSpanId, - traceState: this.traceState + traceState: this.traceState, }); if (this.isRootSpan()) this.tracer.setCurrentRootSpan(this); @@ -319,14 +334,20 @@ export class Span implements types.Span { end(): void { if (this.ended) { this.logger.debug( - 'calling %s.end() on already ended %s %o', this.className, - this.className, {id: this.id, name: this.name, type: this.kind}); + 'calling %s.end() on already ended %s %o', + this.className, + this.className, + { id: this.id, name: this.name, type: this.kind } + ); return; } if (!this.started) { this.logger.error( - 'calling %s.end() on un-started %s %o', this.className, - this.className, {id: this.id, name: this.name, type: this.kind}); + 'calling %s.end() on un-started %s %o', + this.className, + this.className, + { id: this.id, name: this.name, type: this.kind } + ); return; } this.startedLocal = false; @@ -346,10 +367,11 @@ export class Span implements types.Span { /** Forces the span to end. */ truncate() { - this.truncated = true; this.end(); - this.logger.debug( - 'truncating %s %o', this.className, {id: this.id, name: this.name}); + this.logger.debug('truncating %s %o', this.className, { + id: this.id, + name: this.name, + }); } /** @@ -359,14 +381,20 @@ export class Span implements types.Span { startChildSpan(options?: types.SpanOptions): types.Span { if (this.ended) { this.logger.debug( - 'calling %s.startSpan() on ended %s %o', this.className, - this.className, {id: this.id, name: this.name, kind: this.kind}); + 'calling %s.startSpan() on ended %s %o', + this.className, + this.className, + { id: this.id, name: this.name, kind: this.kind } + ); return new NoRecordSpan(); } if (!this.started) { this.logger.debug( - 'calling %s.startSpan() on un-started %s %o', this.className, - this.className, {id: this.id, name: this.name, kind: this.kind}); + 'calling %s.startSpan() on un-started %s %o', + this.className, + this.className, + { id: this.id, name: this.name, kind: this.kind } + ); return new NoRecordSpan(); } diff --git a/packages/opencensus-core/src/trace/model/tracer-base.ts b/packages/opencensus-core/src/trace/model/tracer-base.ts index fc3edc0cd..8a80a0621 100644 --- a/packages/opencensus-core/src/trace/model/tracer-base.ts +++ b/packages/opencensus-core/src/trace/model/tracer-base.ts @@ -18,14 +18,18 @@ import * as uuid from 'uuid'; import * as logger from '../../common/console-logger'; import * as loggerTypes from '../../common/types'; import * as configTypes from '../config/types'; -import {TraceParams} from '../config/types'; -import {noopPropagation} from '../propagation/noop-propagation'; -import {Propagation} from '../propagation/types'; -import {DEFAULT_SAMPLING_RATE, SamplerBuilder, TraceParamsBuilder} from '../sampler/sampler'; +import { TraceParams } from '../config/types'; +import { noopPropagation } from '../propagation/noop-propagation'; +import { Propagation } from '../propagation/types'; +import { + DEFAULT_SAMPLING_RATE, + SamplerBuilder, + TraceParamsBuilder, +} from '../sampler/sampler'; import * as samplerTypes from '../sampler/types'; -import {NoRecordRootSpan} from './no-record/no-record-root-span'; -import {NoRecordSpan} from './no-record/no-record-span'; -import {RootSpan} from './root-span'; +import { NoRecordRootSpan } from './no-record/no-record-root-span'; +import { NoRecordSpan } from './no-record/no-record-span'; +import { RootSpan } from './root-span'; import * as types from './types'; /** @@ -74,19 +78,22 @@ export class CoreTracerBase implements types.TracerBase { this.activeLocal = true; this.config = config; this.logger = this.config.logger || logger.logger(); - this.sampler = - SamplerBuilder.getSampler(config.samplingRate || DEFAULT_SAMPLING_RATE); + this.sampler = SamplerBuilder.getSampler( + config.samplingRate || DEFAULT_SAMPLING_RATE + ); if (config.traceParams) { - this.activeTraceParams.numberOfAnnontationEventsPerSpan = - TraceParamsBuilder.getNumberOfAnnotationEventsPerSpan( - config.traceParams); - this.activeTraceParams.numberOfAttributesPerSpan = - TraceParamsBuilder.getNumberOfAttributesPerSpan(config.traceParams); - this.activeTraceParams.numberOfMessageEventsPerSpan = - TraceParamsBuilder.getNumberOfMessageEventsPerSpan( - config.traceParams); - this.activeTraceParams.numberOfLinksPerSpan = - TraceParamsBuilder.getNumberOfLinksPerSpan(config.traceParams); + this.activeTraceParams.numberOfAnnontationEventsPerSpan = TraceParamsBuilder.getNumberOfAnnotationEventsPerSpan( + config.traceParams + ); + this.activeTraceParams.numberOfAttributesPerSpan = TraceParamsBuilder.getNumberOfAttributesPerSpan( + config.traceParams + ); + this.activeTraceParams.numberOfMessageEventsPerSpan = TraceParamsBuilder.getNumberOfMessageEventsPerSpan( + config.traceParams + ); + this.activeTraceParams.numberOfLinksPerSpan = TraceParamsBuilder.getNumberOfLinksPerSpan( + config.traceParams + ); } return this; } @@ -112,10 +119,17 @@ export class CoreTracerBase implements types.TracerBase { * @param options A TraceOptions object to start a root span. * @param fn A callback function to run after starting a root span. */ - startRootSpan(options: types.TraceOptions, fn: (root: types.Span) => T): - T { - const spanContext: types.SpanContext = options.spanContext || - {spanId: '', traceId: uuid.v4().split('-').join('')}; + startRootSpan( + options: types.TraceOptions, + fn: (root: types.Span) => T + ): T { + const spanContext: types.SpanContext = options.spanContext || { + spanId: '', + traceId: uuid + .v4() + .split('-') + .join(''), + }; const parentSpanId = spanContext.spanId; const traceId = spanContext.traceId; const name = options.name || 'span'; @@ -127,12 +141,18 @@ export class CoreTracerBase implements types.TracerBase { const sampleDecision = this.makeSamplingDecision(options, traceId); // Sampling is on if (sampleDecision) { - const rootSpan = - new RootSpan(this, name, kind, traceId, parentSpanId, traceState); + const rootSpan = new RootSpan( + this, + name, + kind, + traceId, + parentSpanId, + traceState + ); // Add default attributes const defaultAttributes = this.config && this.config.defaultAttributes; if (defaultAttributes) { - Object.keys(defaultAttributes).forEach((key) => { + Object.keys(defaultAttributes).forEach(key => { rootSpan.addAttribute(key, defaultAttributes[key]); }); } @@ -147,7 +167,13 @@ export class CoreTracerBase implements types.TracerBase { } const noRecordRootSpan = new NoRecordRootSpan( - this, name, kind, traceId, parentSpanId, traceState); + this, + name, + kind, + traceId, + parentSpanId, + traceState + ); return fn(noRecordRootSpan); } @@ -203,7 +229,8 @@ export class CoreTracerBase implements types.TracerBase { startChildSpan(options?: types.SpanOptions): types.Span { if (!options || !options.childOf) { this.logger.debug( - 'no current trace found - must start a new root span first'); + 'no current trace found - must start a new root span first' + ); return new NoRecordSpan(); } const span = options.childOf.startChildSpan(options); @@ -211,7 +238,7 @@ export class CoreTracerBase implements types.TracerBase { // Add default attributes const defaultAttributes = this.config && this.config.defaultAttributes; if (defaultAttributes) { - Object.keys(defaultAttributes).forEach((key) => { + Object.keys(defaultAttributes).forEach(key => { span.addAttribute(key, defaultAttributes[key]); }); } @@ -219,13 +246,19 @@ export class CoreTracerBase implements types.TracerBase { } /** Determine whether to sample request or not. */ - private makeSamplingDecision(options: types.TraceOptions, traceId: string): - boolean { + private makeSamplingDecision( + options: types.TraceOptions, + traceId: string + ): boolean { // If users set a specific sampler in the TraceOptions, use it. - if (options && options.samplingRate !== undefined && - options.samplingRate !== null) { - return SamplerBuilder.getSampler(options.samplingRate) - .shouldSample(traceId); + if ( + options && + options.samplingRate !== undefined && + options.samplingRate !== null + ) { + return SamplerBuilder.getSampler(options.samplingRate).shouldSample( + traceId + ); } let propagatedSample = null; // if there is a context propagation, keep the decision diff --git a/packages/opencensus-core/src/trace/model/tracer.ts b/packages/opencensus-core/src/trace/model/tracer.ts index 14d345262..90425c6e9 100644 --- a/packages/opencensus-core/src/trace/model/tracer.ts +++ b/packages/opencensus-core/src/trace/model/tracer.ts @@ -15,8 +15,8 @@ */ import * as cls from '../../internal/cls'; -import {NoRecordSpan} from './no-record/no-record-span'; -import {CoreTracerBase} from './tracer-base'; +import { NoRecordSpan } from './no-record/no-record-span'; +import { CoreTracerBase } from './tracer-base'; import * as types from './types'; /** @@ -61,11 +61,13 @@ export class CoreTracer extends CoreTracerBase implements types.Tracer { * @param options A TraceOptions object to start a root span. * @param fn A callback function to run after starting a root span. */ - startRootSpan(options: types.TraceOptions, fn: (root: types.Span) => T): - T { + startRootSpan( + options: types.TraceOptions, + fn: (root: types.Span) => T + ): T { const self = this; return self.contextManager.runAndReturn(() => { - return super.startRootSpan(options, (root) => { + return super.startRootSpan(options, root => { return fn(root); }); }); @@ -74,10 +76,13 @@ export class CoreTracer extends CoreTracerBase implements types.Tracer { /** Notifies listeners of the span start. */ onStartSpan(span: types.Span): void { if (!this.active) return; - if (!this.currentRootSpan || - this.currentRootSpan.traceId !== span.traceId) { + if ( + !this.currentRootSpan || + this.currentRootSpan.traceId !== span.traceId + ) { this.logger.debug( - 'currentRootSpan != root on notifyStart. Need more investigation.'); + 'currentRootSpan != root on notifyStart. Need more investigation.' + ); } return super.onStartSpan(span); } @@ -85,19 +90,22 @@ export class CoreTracer extends CoreTracerBase implements types.Tracer { /** Notifies listeners of the span end. */ onEndSpan(span: types.Span): void { if (!this.active) return; - if (!this.currentRootSpan || - this.currentRootSpan.traceId !== span.traceId) { + if ( + !this.currentRootSpan || + this.currentRootSpan.traceId !== span.traceId + ) { this.logger.debug( - 'currentRootSpan != root on notifyEnd. Need more investigation.'); + 'currentRootSpan != root on notifyEnd. Need more investigation.' + ); } super.onEndSpan(span); } /** Clears the current root span. */ clearCurrentTrace() { - // TODO: Remove null reference and ts-ignore check. - //@ts-ignore - this.currentRootSpan = null; + if (this.contextManager.active) { + this.contextManager.set('rootspan', null); + } } /** @@ -107,11 +115,16 @@ export class CoreTracer extends CoreTracerBase implements types.Tracer { startChildSpan(options?: types.SpanOptions): types.Span { if (!this.currentRootSpan) { this.logger.debug( - 'no current trace found - must start a new root span first'); + 'no current trace found - must start a new root span first' + ); } - return super.startChildSpan(Object.assign( - {childOf: this.currentRootSpan || new NoRecordSpan()}, options)); + return super.startChildSpan( + Object.assign( + { childOf: this.currentRootSpan || new NoRecordSpan() }, + options + ) + ); } /** diff --git a/packages/opencensus-core/src/trace/model/types.ts b/packages/opencensus-core/src/trace/model/types.ts index 01e409faa..68bf5451a 100644 --- a/packages/opencensus-core/src/trace/model/types.ts +++ b/packages/opencensus-core/src/trace/model/types.ts @@ -16,7 +16,7 @@ import * as loggerTypes from '../../common/types'; import * as configTypes from '../config/types'; -import {Propagation} from '../propagation/types'; +import { Propagation } from '../propagation/types'; import * as samplerTypes from '../sampler/types'; /** Default type for functions */ @@ -25,7 +25,7 @@ export type Func = (...args: any[]) => T; /** Maps a label to a string, number or boolean. */ export interface Attributes { - [attributeKey: string]: string|number|boolean; + [attributeKey: string]: string | number | boolean; } /** @@ -272,7 +272,7 @@ export enum MessageEventType { /** Indicates a sent message. */ SENT = 1, /** Indicates a received message. */ - RECEIVED = 2 + RECEIVED = 2, } /** @@ -291,7 +291,7 @@ export enum SpanKind { * Indicates that the span covers the client-side wrapper around an RPC or * other remote request. */ - CLIENT = 2 + CLIENT = 2, } /** @@ -307,7 +307,7 @@ export enum LinkType { /** The linked span is a child of the current span. */ CHILD_LINKED_SPAN = 1, /** The linked span is a parent of the current span. */ - PARENT_LINKED_SPAN = 2 + PARENT_LINKED_SPAN = 2, } /** Interface for Span */ @@ -407,7 +407,7 @@ export interface Span { * @param key Describes the value added. * @param value The result of an operation. */ - addAttribute(key: string, value: string|number|boolean|object): void; + addAttribute(key: string, value: string | number | boolean | object): void; /** * Adds an annotation to the span. @@ -416,7 +416,10 @@ export interface Span { * @param timestamp A timestamp for this event. */ addAnnotation( - description: string, attributes?: Attributes, timestamp?: number): void; + description: string, + attributes?: Attributes, + timestamp?: number + ): void; /** * Adds a link to the span. @@ -426,8 +429,11 @@ export interface Span { * @param attributes A set of attributes on the link. */ addLink( - traceId: string, spanId: string, type: LinkType, - attributes?: Attributes): void; + traceId: string, + spanId: string, + type: LinkType, + attributes?: Attributes + ): void; /** * Adds a message event to the span. @@ -439,8 +445,12 @@ export interface Span { * zero or undefined, assumed to be the same size as uncompressed. */ addMessageEvent( - type: MessageEventType, id: number, timestamp?: number, - uncompressedSize?: number, compressedSize?: number): void; + type: MessageEventType, + id: number, + timestamp?: number, + uncompressedSize?: number, + compressedSize?: number + ): void; /** * Sets a status to the span. diff --git a/packages/opencensus-core/src/trace/propagation/noop-propagation.ts b/packages/opencensus-core/src/trace/propagation/noop-propagation.ts index 5a623c5f3..288018244 100644 --- a/packages/opencensus-core/src/trace/propagation/noop-propagation.ts +++ b/packages/opencensus-core/src/trace/propagation/noop-propagation.ts @@ -16,12 +16,12 @@ import * as crypto from 'crypto'; import * as uuid from 'uuid'; -import {SpanContext} from '../model/types'; -import {HeaderGetter, HeaderSetter, Propagation} from './types'; +import { SpanContext } from '../model/types'; +import { HeaderGetter, HeaderSetter, Propagation } from './types'; /** No-op implementation of Propagation */ class NoopPropagation implements Propagation { - extract(getter: HeaderGetter): SpanContext|null { + extract(getter: HeaderGetter): SpanContext | null { return null; } @@ -29,7 +29,10 @@ class NoopPropagation implements Propagation { generate(): SpanContext { return { - traceId: uuid.v4().split('-').join(''), + traceId: uuid + .v4() + .split('-') + .join(''), spanId: crypto.randomBytes(8).toString('hex'), }; } diff --git a/packages/opencensus-core/src/trace/propagation/types.ts b/packages/opencensus-core/src/trace/propagation/types.ts index 2cbd613d4..696160461 100644 --- a/packages/opencensus-core/src/trace/propagation/types.ts +++ b/packages/opencensus-core/src/trace/propagation/types.ts @@ -14,13 +14,13 @@ * limitations under the License. */ -import {SpanContext} from '../model/types'; +import { SpanContext } from '../model/types'; /** * An transport and environment neutral API for getting request headers. */ export interface HeaderGetter { - getHeader(name: string): string|string[]|undefined; + getHeader(name: string): string | string[] | undefined; } /** @@ -34,7 +34,7 @@ export interface HeaderSetter { * Propagation interface */ export interface Propagation { - extract(getter: HeaderGetter): SpanContext|null; + extract(getter: HeaderGetter): SpanContext | null; inject(setter: HeaderSetter, spanContext: SpanContext): void; generate(): SpanContext; } diff --git a/packages/opencensus-core/src/trace/sampler/sampler.ts b/packages/opencensus-core/src/trace/sampler/sampler.ts index 5bfe5464d..d5a452d65 100644 --- a/packages/opencensus-core/src/trace/sampler/sampler.ts +++ b/packages/opencensus-core/src/trace/sampler/sampler.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {TraceParams} from '../config/types'; -import {Sampler} from './types'; +import { TraceParams } from '../config/types'; +import { Sampler } from './types'; // We use 52-bits as our max number because it remains a javascript "safe // integer" for arithmetic and parsing while using the full hex range for @@ -54,7 +54,6 @@ export class ProbabilitySampler implements Sampler { this.idUpperBound = probability * MAX_NUMBER; } - /** * Checks if trace belong the sample. * @param traceId Used to check the probability @@ -62,8 +61,9 @@ export class ProbabilitySampler implements Sampler { * False if the traceId is not in probability. */ shouldSample(traceId: string): boolean { - const LOWER_BYTES = - traceId ? ('0000000000000' + traceId).slice(-LOWER_BYTE_COUNT) : '0'; + const LOWER_BYTES = traceId + ? ('0000000000000' + traceId).slice(-LOWER_BYTE_COUNT) + : '0'; // tslint:disable-next-line:ban Needed to parse hexadecimal. const LOWER_LONG = parseInt(LOWER_BYTES, 16); @@ -75,7 +75,6 @@ export class ProbabilitySampler implements Sampler { } } - /** Builder class of Samplers */ export class SamplerBuilder { private static readonly ALWAYS = new AlwaysSampler(); @@ -116,37 +115,46 @@ export const DEFAULT_SPAN_MAX_NUM_LINKS = 32; /** Builder Class of TraceParams */ export class TraceParamsBuilder { - static getNumberOfAnnotationEventsPerSpan(traceParameters: TraceParams): - number { - if (!traceParameters.numberOfAnnontationEventsPerSpan || - traceParameters.numberOfAnnontationEventsPerSpan > - DEFAULT_SPAN_MAX_NUM_ANNOTATIONS) { + static getNumberOfAnnotationEventsPerSpan( + traceParameters: TraceParams + ): number { + if ( + !traceParameters.numberOfAnnontationEventsPerSpan || + traceParameters.numberOfAnnontationEventsPerSpan > + DEFAULT_SPAN_MAX_NUM_ANNOTATIONS + ) { return DEFAULT_SPAN_MAX_NUM_ANNOTATIONS; } return traceParameters.numberOfAnnontationEventsPerSpan; } static getNumberOfAttributesPerSpan(traceParameters: TraceParams): number { - if (!traceParameters.numberOfAttributesPerSpan || - traceParameters.numberOfAttributesPerSpan > - DEFAULT_SPAN_MAX_NUM_ATTRIBUTES) { + if ( + !traceParameters.numberOfAttributesPerSpan || + traceParameters.numberOfAttributesPerSpan > + DEFAULT_SPAN_MAX_NUM_ATTRIBUTES + ) { return DEFAULT_SPAN_MAX_NUM_ATTRIBUTES; } return traceParameters.numberOfAttributesPerSpan; } static getNumberOfMessageEventsPerSpan(traceParameters: TraceParams): number { - if (!traceParameters.numberOfMessageEventsPerSpan || - traceParameters.numberOfMessageEventsPerSpan > - DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS) { + if ( + !traceParameters.numberOfMessageEventsPerSpan || + traceParameters.numberOfMessageEventsPerSpan > + DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS + ) { return DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS; } return traceParameters.numberOfMessageEventsPerSpan; } static getNumberOfLinksPerSpan(traceParameters: TraceParams): number { - if (!traceParameters.numberOfLinksPerSpan || - traceParameters.numberOfLinksPerSpan > DEFAULT_SPAN_MAX_NUM_LINKS) { + if ( + !traceParameters.numberOfLinksPerSpan || + traceParameters.numberOfLinksPerSpan > DEFAULT_SPAN_MAX_NUM_LINKS + ) { return DEFAULT_SPAN_MAX_NUM_LINKS; } return traceParameters.numberOfLinksPerSpan; diff --git a/packages/opencensus-core/test/test-binary-serializer.ts b/packages/opencensus-core/test/test-binary-serializer.ts index 79817630c..8b3db4d1c 100644 --- a/packages/opencensus-core/test/test-binary-serializer.ts +++ b/packages/opencensus-core/test/test-binary-serializer.ts @@ -15,33 +15,37 @@ */ import * as assert from 'assert'; -import {deserializeBinary, serializeBinary, TAG_MAP_SERIALIZED_SIZE_LIMIT} from '../src/tags/propagation/binary-serializer'; -import {TagMap} from '../src/tags/tag-map'; +import { + deserializeBinary, + serializeBinary, + TAG_MAP_SERIALIZED_SIZE_LIMIT, +} from '../src/tags/propagation/binary-serializer'; +import { TagMap } from '../src/tags/tag-map'; const K1 = { - name: 'k1' + name: 'k1', }; const K2 = { - name: 'k2' + name: 'k2', }; const K3 = { - name: 'k3' + name: 'k3', }; const K4 = { - name: 'k4' + name: 'k4', }; const V1 = { - value: 'v1' + value: 'v1', }; const V2 = { - value: 'v2' + value: 'v2', }; const V3 = { - value: 'v3' + value: 'v3', }; const V4 = { - value: 'v4' + value: 'v4', }; describe('Binary Format Serializer', () => { @@ -79,11 +83,11 @@ describe('Binary Format Serializer', () => { // length of it is 8. const pad = '0000'.substring(0, 4 - `${i}`.length); const str = `${pad}${i}`; - tags.set({name: str}, {value: str}); + tags.set({ name: str }, { value: str }); } // The last tag will be of size 9, so the total size of the TagMap // (8193) will be one byte more than limit. - tags.set({name: 'last'}, {value: 'last1'}); + tags.set({ name: 'last' }, { value: 'last1' }); assert.throws(() => { serializeBinary(tags); @@ -93,8 +97,16 @@ describe('Binary Format Serializer', () => { describe('deserializeBinary', () => { it('should throw an error when invalid tagKey', () => { - const buff = - Buffer.from([0x01, 0x00, 0x02, 0x6b, 0x31, 0x02, 0x76, 0x31]); + const buff = Buffer.from([ + 0x01, + 0x00, + 0x02, + 0x6b, + 0x31, + 0x02, + 0x76, + 0x31, + ]); assert.throws(() => { deserializeBinary(buff); }, /^Error: Wrong Version ID: 1. Currently supports version up to: 0/); @@ -105,8 +117,21 @@ describe('Binary Format Serializer', () => { expectedTags.set(K1, V1); const buff = Buffer.from([ - 0x00, 0x00, 0x02, 0x6b, 0x31, 0x02, 0x76, 0x31, 0x01, 0x02, 0x6b, 0x32, - 0x02, 0x76, 0x32 + 0x00, + 0x00, + 0x02, + 0x6b, + 0x31, + 0x02, + 0x76, + 0x31, + 0x01, + 0x02, + 0x6b, + 0x32, + 0x02, + 0x76, + 0x32, ]); const tags = deserializeBinary(buff); assert.strictEqual(tags.tags.size, 1); diff --git a/packages/opencensus-core/test/test-bucket-boundaries.ts b/packages/opencensus-core/test/test-bucket-boundaries.ts index adbd34068..c9b036bb8 100644 --- a/packages/opencensus-core/test/test-bucket-boundaries.ts +++ b/packages/opencensus-core/test/test-bucket-boundaries.ts @@ -15,7 +15,7 @@ */ import * as assert from 'assert'; -import {BucketBoundaries} from '../src'; +import { BucketBoundaries } from '../src'; describe('BucketBoundaries', () => { it('should return boundaries', () => { @@ -37,4 +37,4 @@ describe('BucketBoundaries', () => { assert.deepStrictEqual(buckets.getCounts(), [0, 0, 0, 0]); }); }); -}); \ No newline at end of file +}); diff --git a/packages/opencensus-core/test/test-console-exporter.ts b/packages/opencensus-core/test/test-console-exporter.ts index 52fd998cd..45df65007 100644 --- a/packages/opencensus-core/test/test-console-exporter.ts +++ b/packages/opencensus-core/test/test-console-exporter.ts @@ -15,15 +15,18 @@ */ import * as assert from 'assert'; -import {SpanKind} from '../src'; -import {ConsoleExporter, NoopExporter} from '../src/exporters/console-exporter'; -import {RootSpan} from '../src/trace/model/root-span'; -import {CoreTracer} from '../src/trace/model/tracer'; +import { SpanKind } from '../src'; +import { + ConsoleExporter, + NoopExporter, +} from '../src/exporters/console-exporter'; +import { RootSpan } from '../src/trace/model/root-span'; +import { CoreTracer } from '../src/trace/model/tracer'; -const tracer = new CoreTracer().start({samplingRate: 1.0}); +const tracer = new CoreTracer().start({ samplingRate: 1.0 }); const defaultBufferConfig = { bufferSize: 1, - bufferTimeout: 20000 // time in milliseconds + bufferTimeout: 20000, // time in milliseconds }; const name = 'MySpanName'; const kind = SpanKind.SERVER; @@ -91,7 +94,7 @@ describe('ConsoleLogExporter', () => { const exporter = new ConsoleExporter(defaultBufferConfig); const rootSpan = new RootSpan(tracer, name, kind, traceId, parentSpanId); rootSpan.start(); - rootSpan.startChildSpan({name: 'name', kind: SpanKind.UNSPECIFIED}); + rootSpan.startChildSpan({ name: 'name', kind: SpanKind.UNSPECIFIED }); const queue: RootSpan[] = [rootSpan]; return exporter.publish(queue).then(() => { diff --git a/packages/opencensus-core/test/test-console-logger.ts b/packages/opencensus-core/test/test-console-logger.ts index ee964ebac..ecf8853b6 100644 --- a/packages/opencensus-core/test/test-console-logger.ts +++ b/packages/opencensus-core/test/test-console-logger.ts @@ -16,8 +16,7 @@ import * as assert from 'assert'; import * as logger from '../src/common/console-logger'; -import {ConsoleLogger} from '../src/common/console-logger'; - +import { ConsoleLogger } from '../src/common/console-logger'; const LEVELS = ['silent', 'error', 'warn', 'info', 'debug']; let consoleTxt = ''; diff --git a/packages/opencensus-core/test/test-cumulative.ts b/packages/opencensus-core/test/test-cumulative.ts index bcf1f737c..b21722c32 100644 --- a/packages/opencensus-core/test/test-cumulative.ts +++ b/packages/opencensus-core/test/test-cumulative.ts @@ -15,43 +15,56 @@ */ import * as assert from 'assert'; -import {TEST_ONLY} from '../src/common/time-util'; -import {Cumulative} from '../src/metrics/cumulative/cumulative'; -import {LabelKey, LabelValue, MetricDescriptorType, Timestamp} from '../src/metrics/export/types'; +import { TEST_ONLY } from '../src/common/time-util'; +import { Cumulative } from '../src/metrics/cumulative/cumulative'; +import { + LabelKey, + LabelValue, + MetricDescriptorType, + Timestamp, +} from '../src/metrics/export/types'; const METRIC_NAME = 'metric-name'; const METRIC_DESCRIPTION = 'metric-description'; const UNIT = '1'; const CUMULATIVE_INT64 = MetricDescriptorType.CUMULATIVE_INT64; const CUMULATIVE_DOUBLE = MetricDescriptorType.CUMULATIVE_DOUBLE; -const LABEL_KEYS: LabelKey[] = [{key: 'code', description: 'desc'}]; -const LABEL_VALUES_200: LabelValue[] = [{value: '200'}]; -const LABEL_VALUES_400: LabelValue[] = [{value: '400'}]; -const LABEL_VALUES_EXRTA: LabelValue[] = [{value: '200'}, {value: '400'}]; +const LABEL_KEYS: LabelKey[] = [{ key: 'code', description: 'desc' }]; +const LABEL_VALUES_200: LabelValue[] = [{ value: '200' }]; +const LABEL_VALUES_400: LabelValue[] = [{ value: '400' }]; +const LABEL_VALUES_EXRTA: LabelValue[] = [{ value: '200' }, { value: '400' }]; const UNSET_LABEL_VALUE: LabelValue = { - value: null + value: null, }; const EMPTY_CONSTANT_LABELS = new Map(); const CONSTANT_LABELS = new Map(); -CONSTANT_LABELS.set({key: 'host', description: 'host'}, {value: 'localhost'}); +CONSTANT_LABELS.set( + { key: 'host', description: 'host' }, + { value: 'localhost' } +); describe('CUMULATIVE', () => { let instance: Cumulative; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; const expectedMetricDescriptor = { name: METRIC_NAME, description: METRIC_DESCRIPTION, unit: UNIT, type: CUMULATIVE_INT64, - labelKeys: LABEL_KEYS + labelKeys: LABEL_KEYS, }; beforeEach(() => { instance = new Cumulative( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, CUMULATIVE_INT64, LABEL_KEYS, - EMPTY_CONSTANT_LABELS); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + CUMULATIVE_INT64, + LABEL_KEYS, + EMPTY_CONSTANT_LABELS + ); process.hrtime = () => [100, 1e7]; Date.now = () => 1450000000000; @@ -74,11 +87,13 @@ describe('CUMULATIVE', () => { let metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 1, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 1, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); // inc value and create new timeseries. point.inc(5); @@ -90,23 +105,22 @@ describe('CUMULATIVE', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: LABEL_VALUES_200, - points: [{value: 6, timestamp: mockedTime}], - startTimestamp: mockedTime + points: [{ value: 6, timestamp: mockedTime }], + startTimestamp: mockedTime, }, { labelValues: LABEL_VALUES_400, - points: [{value: 1, timestamp: mockedTime}], - startTimestamp: mockedTime - } + points: [{ value: 1, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, ]); }); - it('should throw an error when the keys and values dont have same size', - () => { - assert.throws(() => { - instance.getOrCreateTimeSeries(LABEL_VALUES_EXRTA); - }, /^Error: Label Keys and Label Values don't have same size$/); - }); + it('should throw an error when the keys and values dont have same size', () => { + assert.throws(() => { + instance.getOrCreateTimeSeries(LABEL_VALUES_EXRTA); + }, /^Error: Label Keys and Label Values don't have same size$/); + }); it('should throw an error when the inc number is negative', () => { const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200); @@ -137,11 +151,13 @@ describe('CUMULATIVE', () => { const metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 1, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 1, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); }); it('should not create same timeseries again', () => { @@ -150,22 +166,26 @@ describe('CUMULATIVE', () => { let metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 10, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 10, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); // create timeseries with same labels. const point1 = instance.getOrCreateTimeSeries(LABEL_VALUES_200); point1.inc(30); metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 40, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 40, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); }); }); @@ -182,24 +202,38 @@ describe('CUMULATIVE', () => { const metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: [UNSET_LABEL_VALUE], - points: [{value: 10, timestamp: {seconds: 1480000100, nanos: 1e7}}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [UNSET_LABEL_VALUE], + points: [ + { value: 10, timestamp: { seconds: 1480000100, nanos: 1e7 } }, + ], + startTimestamp: mockedTime, + }, + ]); }); it('should return same timeseries for interchanged labels', () => { instance = new Cumulative( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, CUMULATIVE_INT64, - [{key: 'k1', description: 'desc'}, {key: 'k2', description: 'desc'}], - EMPTY_CONSTANT_LABELS); - const point = - instance.getOrCreateTimeSeries([{value: '200'}, {value: '400'}]); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + CUMULATIVE_INT64, + [ + { key: 'k1', description: 'desc' }, + { key: 'k2', description: 'desc' }, + ], + EMPTY_CONSTANT_LABELS + ); + const point = instance.getOrCreateTimeSeries([ + { value: '200' }, + { value: '400' }, + ]); point.inc(200); - const point1 = - instance.getOrCreateTimeSeries([{value: '400'}, {value: '200'}]); + const point1 = instance.getOrCreateTimeSeries([ + { value: '400' }, + { value: '200' }, + ]); point1.inc(400); const metric = instance.getMetric(); assert.strictEqual(metric!.timeseries.length, 1); @@ -207,48 +241,72 @@ describe('CUMULATIVE', () => { it('should add constant labels', () => { instance = new Cumulative( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, CUMULATIVE_DOUBLE, - [{key: 'k1', description: 'desc'}, {key: 'k2', description: 'desc'}], - CONSTANT_LABELS); - const point = - instance.getOrCreateTimeSeries([{value: '200'}, {value: '400'}]); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + CUMULATIVE_DOUBLE, + [ + { key: 'k1', description: 'desc' }, + { key: 'k2', description: 'desc' }, + ], + CONSTANT_LABELS + ); + const point = instance.getOrCreateTimeSeries([ + { value: '200' }, + { value: '400' }, + ]); point.inc(200); const metric = instance.getMetric(); assert.strictEqual(metric!.descriptor.type, 5); assert.strictEqual(metric!.timeseries.length, 1); assert.deepStrictEqual(metric!.descriptor.labelKeys, [ - {key: 'k1', description: 'desc'}, {key: 'k2', description: 'desc'}, - {key: 'host', description: 'host'} + { key: 'k1', description: 'desc' }, + { key: 'k2', description: 'desc' }, + { key: 'host', description: 'host' }, + ]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [ + { value: '200' }, + { value: '400' }, + { value: 'localhost' }, + ], + points: [{ value: 200, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, ]); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: [{value: '200'}, {value: '400'}, {value: 'localhost'}], - points: [{value: 200, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); }); it('should create same labelValues as labelKeys', () => { instance = new Cumulative( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, CUMULATIVE_DOUBLE, - [ - {key: 'k1', description: 'desc'}, {key: 'k2', description: 'desc'}, - {key: 'k3', description: 'desc'} - ], - EMPTY_CONSTANT_LABELS); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + CUMULATIVE_DOUBLE, + [ + { key: 'k1', description: 'desc' }, + { key: 'k2', description: 'desc' }, + { key: 'k3', description: 'desc' }, + ], + EMPTY_CONSTANT_LABELS + ); const point = instance.getDefaultTimeSeries(); point.inc(200); const metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor.labelKeys.length, 3); assert.deepStrictEqual(metric!.descriptor.type, 5); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: - [UNSET_LABEL_VALUE, UNSET_LABEL_VALUE, UNSET_LABEL_VALUE], - points: [{value: 200, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [ + UNSET_LABEL_VALUE, + UNSET_LABEL_VALUE, + UNSET_LABEL_VALUE, + ], + points: [{ value: 200, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); }); it('should use previously created default timeseries', () => { @@ -257,22 +315,26 @@ describe('CUMULATIVE', () => { let metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: [UNSET_LABEL_VALUE], - points: [{value: 300, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [UNSET_LABEL_VALUE], + points: [{ value: 300, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); // get default timeseries again. const point1 = instance.getDefaultTimeSeries(); point1.inc(400); metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: [UNSET_LABEL_VALUE], - points: [{value: 700, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [UNSET_LABEL_VALUE], + points: [{ value: 700, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); }); }); diff --git a/packages/opencensus-core/test/test-derived-cumulative.ts b/packages/opencensus-core/test/test-derived-cumulative.ts index 77f4a6b5b..3ee191b17 100644 --- a/packages/opencensus-core/test/test-derived-cumulative.ts +++ b/packages/opencensus-core/test/test-derived-cumulative.ts @@ -15,41 +15,55 @@ */ import * as assert from 'assert'; -import {TEST_ONLY} from '../src/common/time-util'; -import {DerivedCumulative} from '../src/metrics/cumulative/derived-cumulative'; -import {LabelKey, LabelValue, MetricDescriptorType, Timestamp} from '../src/metrics/export/types'; +import { TEST_ONLY } from '../src/common/time-util'; +import { DerivedCumulative } from '../src/metrics/cumulative/derived-cumulative'; +import { + LabelKey, + LabelValue, + MetricDescriptorType, + Timestamp, +} from '../src/metrics/export/types'; const METRIC_NAME = 'metric-name'; const METRIC_DESCRIPTION = 'metric-description'; const UNIT = '1'; const CUMULATIVE_INT64 = MetricDescriptorType.CUMULATIVE_INT64; const CUMULATIVE_DOUBLE = MetricDescriptorType.CUMULATIVE_DOUBLE; -const LABEL_KEYS: LabelKey[] = [{key: 'code', description: 'desc'}]; -const LABEL_VALUES_200: LabelValue[] = [{value: '200'}]; -const LABEL_VALUES_400: LabelValue[] = [{value: '400'}]; -const LABEL_VALUES_EXRTA: LabelValue[] = [{value: '200'}, {value: '400'}]; +const LABEL_KEYS: LabelKey[] = [{ key: 'code', description: 'desc' }]; +const LABEL_VALUES_200: LabelValue[] = [{ value: '200' }]; +const LABEL_VALUES_400: LabelValue[] = [{ value: '400' }]; +const LABEL_VALUES_EXRTA: LabelValue[] = [{ value: '200' }, { value: '400' }]; const EMPTY_CONSTANT_LABELS = new Map(); const CONSTANT_LABELS = new Map(); -CONSTANT_LABELS.set({key: 'host', description: 'host'}, {value: 'localhost'}); +CONSTANT_LABELS.set( + { key: 'host', description: 'host' }, + { value: 'localhost' } +); describe('DerivedCumulative', () => { let instance: DerivedCumulative; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; const expectedMetricDescriptor = { name: METRIC_NAME, description: METRIC_DESCRIPTION, unit: UNIT, type: CUMULATIVE_INT64, - labelKeys: LABEL_KEYS + labelKeys: LABEL_KEYS, }; - const startime: Timestamp = {seconds: 1400000100, nanos: 1e7}; + const startime: Timestamp = { seconds: 1400000100, nanos: 1e7 }; beforeEach(() => { instance = new DerivedCumulative( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, CUMULATIVE_INT64, LABEL_KEYS, - EMPTY_CONSTANT_LABELS, startime); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + CUMULATIVE_INT64, + LABEL_KEYS, + EMPTY_CONSTANT_LABELS, + startime + ); process.hrtime = () => [100, 1e7]; Date.now = () => 1450000000000; @@ -65,12 +79,11 @@ describe('DerivedCumulative', () => { }); describe('createTimeSeries()', () => { - it('should throw an error when the keys and values dont have same size', - () => { - assert.throws(() => { - instance.createTimeSeries(LABEL_VALUES_EXRTA, new Map()); - }, /^Error: Label Keys and Label Values don't have same size$/); - }); + it('should throw an error when the keys and values dont have same size', () => { + assert.throws(() => { + instance.createTimeSeries(LABEL_VALUES_EXRTA, new Map()); + }, /^Error: Label Keys and Label Values don't have same size$/); + }); it('should return a Metric', () => { const map = new Map(); @@ -82,11 +95,13 @@ describe('DerivedCumulative', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 2, timestamp: mockedTime}], - startTimestamp: startime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 2, timestamp: mockedTime }], + startTimestamp: startime, + }, + ]); // add data in collection map.set('key2', 'value2'); map.set('key3', 'value3'); @@ -103,14 +118,14 @@ describe('DerivedCumulative', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: LABEL_VALUES_200, - points: [{value: 4, timestamp: mockedTime}], - startTimestamp: startime + points: [{ value: 4, timestamp: mockedTime }], + startTimestamp: startime, }, { labelValues: LABEL_VALUES_400, - points: [{value: 5, timestamp: mockedTime}], - startTimestamp: startime - } + points: [{ value: 5, timestamp: mockedTime }], + startTimestamp: startime, + }, ]); }); @@ -126,11 +141,13 @@ describe('DerivedCumulative', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 45, timestamp: mockedTime}], - startTimestamp: startime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 45, timestamp: mockedTime }], + startTimestamp: startime, + }, + ]); }); it('should return a Metric value from a function', () => { @@ -153,19 +170,22 @@ describe('DerivedCumulative', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 1, timestamp: mockedTime}], - startTimestamp: startime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 1, timestamp: mockedTime }], + startTimestamp: startime, + }, + ]); // Simulate a adding multiple jobs in queue queue.addJob(); queue.addJob(); queue.addJob(); metric = instance.getMetric(); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries[0].points, [{value: 4, timestamp: mockedTime}]); + assert.deepStrictEqual(metric!.timeseries[0].points, [ + { value: 4, timestamp: mockedTime }, + ]); }); it('should return a Metric (Double) - custom object', () => { @@ -176,8 +196,14 @@ describe('DerivedCumulative', () => { } const queue = new QueueManager(); const doubleInstance = new DerivedCumulative( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, CUMULATIVE_DOUBLE, LABEL_KEYS, - EMPTY_CONSTANT_LABELS, startime); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + CUMULATIVE_DOUBLE, + LABEL_KEYS, + EMPTY_CONSTANT_LABELS, + startime + ); doubleInstance.createTimeSeries(LABEL_VALUES_200, queue); const metric = doubleInstance.getMetric(); assert.notStrictEqual(metric, null); @@ -186,14 +212,16 @@ describe('DerivedCumulative', () => { description: METRIC_DESCRIPTION, unit: UNIT, type: CUMULATIVE_DOUBLE, - labelKeys: LABEL_KEYS + labelKeys: LABEL_KEYS, }); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 0.7, timestamp: mockedTime}], - startTimestamp: startime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 0.7, timestamp: mockedTime }], + startTimestamp: startime, + }, + ]); }); it('should ignore dropping (decreasing) value', () => { @@ -204,20 +232,24 @@ describe('DerivedCumulative', () => { let metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 2, timestamp: mockedTime}], - startTimestamp: startime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 2, timestamp: mockedTime }], + startTimestamp: startime, + }, + ]); map.clear(); metric = instance.getMetric(); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 2, timestamp: mockedTime}], - startTimestamp: startime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 2, timestamp: mockedTime }], + startTimestamp: startime, + }, + ]); }); it('should not create same timeseries again', () => { @@ -228,11 +260,13 @@ describe('DerivedCumulative', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual(metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 1, timestamp: mockedTime}], - startTimestamp: startime - }]); + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 1, timestamp: mockedTime }], + startTimestamp: startime, + }, + ]); // create timeseries with same labels. assert.throws(() => { diff --git a/packages/opencensus-core/test/test-derived-gauge.ts b/packages/opencensus-core/test/test-derived-gauge.ts index 9e3a65557..c61140ba3 100644 --- a/packages/opencensus-core/test/test-derived-gauge.ts +++ b/packages/opencensus-core/test/test-derived-gauge.ts @@ -15,40 +15,53 @@ */ import * as assert from 'assert'; -import {TEST_ONLY} from '../src/common/time-util'; -import {LabelKey, LabelValue, MetricDescriptorType, Timestamp} from '../src/metrics/export/types'; -import {DerivedGauge} from '../src/metrics/gauges/derived-gauge'; +import { TEST_ONLY } from '../src/common/time-util'; +import { + LabelKey, + LabelValue, + MetricDescriptorType, + Timestamp, +} from '../src/metrics/export/types'; +import { DerivedGauge } from '../src/metrics/gauges/derived-gauge'; const METRIC_NAME = 'metric-name'; const METRIC_DESCRIPTION = 'metric-description'; const UNIT = '1'; const GAUGE_INT64 = MetricDescriptorType.GAUGE_INT64; const GAUGE_DOUBLE = MetricDescriptorType.GAUGE_DOUBLE; -const LABEL_KEYS: LabelKey[] = [{key: 'code', description: 'desc'}]; -const LABEL_VALUES_200: LabelValue[] = [{value: '200'}]; -const LABEL_VALUES_400: LabelValue[] = [{value: '400'}]; -const LABEL_VALUES_EXRTA: LabelValue[] = [{value: '200'}, {value: '400'}]; +const LABEL_KEYS: LabelKey[] = [{ key: 'code', description: 'desc' }]; +const LABEL_VALUES_200: LabelValue[] = [{ value: '200' }]; +const LABEL_VALUES_400: LabelValue[] = [{ value: '400' }]; +const LABEL_VALUES_EXRTA: LabelValue[] = [{ value: '200' }, { value: '400' }]; const EMPTY_CONSTANT_LABELS = new Map(); const CONSTANT_LABELS = new Map(); -CONSTANT_LABELS.set({key: 'host', description: 'host'}, {value: 'localhost'}); +CONSTANT_LABELS.set( + { key: 'host', description: 'host' }, + { value: 'localhost' } +); describe('DerivedGauge', () => { let instance: DerivedGauge; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; const expectedMetricDescriptor = { name: METRIC_NAME, description: METRIC_DESCRIPTION, unit: UNIT, type: GAUGE_INT64, - labelKeys: LABEL_KEYS + labelKeys: LABEL_KEYS, }; beforeEach(() => { instance = new DerivedGauge( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, GAUGE_INT64, LABEL_KEYS, - EMPTY_CONSTANT_LABELS); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + GAUGE_INT64, + LABEL_KEYS, + EMPTY_CONSTANT_LABELS + ); process.hrtime = () => [100, 1e7]; Date.now = () => 1450000000000; @@ -64,12 +77,11 @@ describe('DerivedGauge', () => { }); describe('createTimeSeries()', () => { - it('should throw an error when the keys and values dont have same size', - () => { - assert.throws(() => { - instance.createTimeSeries(LABEL_VALUES_EXRTA, new Map()); - }, /^Error: Label Keys and Label Values don't have same size$/); - }); + it('should throw an error when the keys and values dont have same size', () => { + assert.throws(() => { + instance.createTimeSeries(LABEL_VALUES_EXRTA, new Map()); + }, /^Error: Label Keys and Label Values don't have same size$/); + }); it('should return a Metric', () => { const map = new Map(); map.set('key', 'value'); @@ -80,15 +92,20 @@ describe('DerivedGauge', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [ + { value: 2, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); // add data in collection map.set('key2', 'value2'); map.set('key3', 'value3'); @@ -105,20 +122,28 @@ describe('DerivedGauge', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: LABEL_VALUES_200, - points: [{ - value: 4, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] + points: [ + { + value: 4, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], }, { labelValues: LABEL_VALUES_400, - points: [{ - value: 5, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - } + points: [ + { + value: 5, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); }); it('should return a Metric (INT64) - custom object', () => { @@ -133,15 +158,20 @@ describe('DerivedGauge', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [ + { value: 45, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); }); it('should return a Metric value from a function', () => { @@ -164,27 +194,32 @@ describe('DerivedGauge', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [ + { value: 1, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); // Simulate a adding multiple jobs in queue queue.addJob(); queue.addJob(); queue.addJob(); metric = instance.getMetric(); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries[0].points, [{ - value: 4, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }]); + assert.deepStrictEqual(metric!.timeseries[0].points, [ + { + value: 4, + timestamp: { nanos: mockedTime.nanos, seconds: mockedTime.seconds }, + }, + ]); }); it('should return a Metric (Double) - custom object', () => { @@ -195,8 +230,13 @@ describe('DerivedGauge', () => { } const obj = new QueueManager(); const doubleInstance = new DerivedGauge( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, GAUGE_DOUBLE, LABEL_KEYS, - EMPTY_CONSTANT_LABELS); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + GAUGE_DOUBLE, + LABEL_KEYS, + EMPTY_CONSTANT_LABELS + ); doubleInstance.createTimeSeries(LABEL_VALUES_200, obj); const metric = doubleInstance.getMetric(); assert.notStrictEqual(metric, null); @@ -205,18 +245,23 @@ describe('DerivedGauge', () => { description: METRIC_DESCRIPTION, unit: UNIT, type: GAUGE_DOUBLE, - labelKeys: LABEL_KEYS + labelKeys: LABEL_KEYS, }); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [ + { value: 0.7, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); }); it('should return a Metric (Double) - custom object', () => { @@ -227,8 +272,13 @@ describe('DerivedGauge', () => { } const obj = new QueueManager(); const doubleInstance = new DerivedGauge( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, GAUGE_DOUBLE, LABEL_KEYS, - CONSTANT_LABELS); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + GAUGE_DOUBLE, + LABEL_KEYS, + CONSTANT_LABELS + ); doubleInstance.createTimeSeries(LABEL_VALUES_200, obj); const metric = doubleInstance.getMetric(); assert.notStrictEqual(metric, null); @@ -237,19 +287,26 @@ describe('DerivedGauge', () => { description: METRIC_DESCRIPTION, unit: UNIT, type: GAUGE_DOUBLE, - labelKeys: [...LABEL_KEYS, ...Array.from(CONSTANT_LABELS.keys())] + labelKeys: [...LABEL_KEYS, ...Array.from(CONSTANT_LABELS.keys())], }); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: - [...LABEL_VALUES_200, ...Array.from(CONSTANT_LABELS.values())], - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [ + ...LABEL_VALUES_200, + ...Array.from(CONSTANT_LABELS.values()), + ], + points: [ + { value: 0.7, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); }); it('should not create same timeseries again', () => { @@ -260,15 +317,20 @@ describe('DerivedGauge', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [ + { value: 1, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); // create timeseries with same labels. assert.throws(() => { diff --git a/packages/opencensus-core/test/test-exporter-buffer.ts b/packages/opencensus-core/test/test-exporter-buffer.ts index aa7bc42fa..cc93ca9e5 100644 --- a/packages/opencensus-core/test/test-exporter-buffer.ts +++ b/packages/opencensus-core/test/test-exporter-buffer.ts @@ -15,22 +15,22 @@ */ import * as assert from 'assert'; -import {SpanKind} from '../src'; +import { SpanKind } from '../src'; import * as logger from '../src/common/console-logger'; -import {NoopExporter} from '../src/exporters/console-exporter'; -import {ExporterBuffer} from '../src/exporters/exporter-buffer'; -import {RootSpan} from '../src/trace/model/root-span'; -import {CoreTracer} from '../src/trace/model/tracer'; +import { NoopExporter } from '../src/exporters/console-exporter'; +import { ExporterBuffer } from '../src/exporters/exporter-buffer'; +import { RootSpan } from '../src/trace/model/root-span'; +import { CoreTracer } from '../src/trace/model/tracer'; const exporter = new NoopExporter(); const DEFAULT_BUFFER_SIZE = 3; -const DEFAULT_BUFFER_TIMEOUT = 2000; // time in milliseconds +const DEFAULT_BUFFER_TIMEOUT = 2000; // time in milliseconds const tracer = new CoreTracer().start({}); const defaultBufferConfig = { bufferSize: DEFAULT_BUFFER_SIZE, bufferTimeout: DEFAULT_BUFFER_TIMEOUT, - logger: logger.logger() + logger: logger.logger(), }; const name = 'MySpanName'; @@ -41,12 +41,19 @@ const parentSpanId = ''; const createRootSpans = (num: number): RootSpan[] => { const rootSpans = []; for (let i = 0; i < num; i++) { - const rootSpan = - new RootSpan(tracer, `rootSpan.${i}`, kind, traceId, parentSpanId); + const rootSpan = new RootSpan( + tracer, + `rootSpan.${i}`, + kind, + traceId, + parentSpanId + ); rootSpan.start(); for (let j = 0; j < 10; j++) { - rootSpan.startChildSpan( - {name: `childSpan.${i}.${j}`, kind: SpanKind.CLIENT}); + rootSpan.startChildSpan({ + name: `childSpan.${i}.${j}`, + kind: SpanKind.CLIENT, + }); } rootSpans.push(rootSpan); } @@ -85,7 +92,8 @@ describe('ExporterBuffer', () => { it('should add one item to the Buffer', () => { const buffer = new ExporterBuffer(exporter, defaultBufferConfig); buffer.addToBuffer( - new RootSpan(tracer, name, kind, traceId, parentSpanId)); + new RootSpan(tracer, name, kind, traceId, parentSpanId) + ); assert.strictEqual(buffer.getQueue().length, 1); }); }); @@ -102,7 +110,8 @@ describe('ExporterBuffer', () => { } assert.strictEqual(buffer.getQueue().length, buffer.getBufferSize()); buffer.addToBuffer( - new RootSpan(tracer, name, kind, traceId, parentSpanId)); + new RootSpan(tracer, name, kind, traceId, parentSpanId) + ); assert.strictEqual(buffer.getQueue().length, 0); }); }); @@ -111,10 +120,11 @@ describe('ExporterBuffer', () => { * Should flush by timeout */ describe('addToBuffer force flush by timeout ', () => { - it('should flush by timeout', (done) => { + it('should flush by timeout', done => { const buffer = new ExporterBuffer(exporter, defaultBufferConfig); buffer.addToBuffer( - new RootSpan(tracer, name, kind, traceId, parentSpanId)); + new RootSpan(tracer, name, kind, traceId, parentSpanId) + ); assert.strictEqual(buffer.getQueue().length, 1); setTimeout(() => { assert.strictEqual(buffer.getQueue().length, 0); diff --git a/packages/opencensus-core/test/test-gauge.ts b/packages/opencensus-core/test/test-gauge.ts index 2af8f06b7..701d12cfb 100644 --- a/packages/opencensus-core/test/test-gauge.ts +++ b/packages/opencensus-core/test/test-gauge.ts @@ -16,43 +16,56 @@ import * as assert from 'assert'; -import {TEST_ONLY} from '../src/common/time-util'; -import {LabelKey, LabelValue, MetricDescriptorType, Timestamp} from '../src/metrics/export/types'; -import {Gauge} from '../src/metrics/gauges/gauge'; +import { TEST_ONLY } from '../src/common/time-util'; +import { + LabelKey, + LabelValue, + MetricDescriptorType, + Timestamp, +} from '../src/metrics/export/types'; +import { Gauge } from '../src/metrics/gauges/gauge'; const METRIC_NAME = 'metric-name'; const METRIC_DESCRIPTION = 'metric-description'; const UNIT = '1'; const GAUGE_INT64 = MetricDescriptorType.GAUGE_INT64; const GAUGE_DOUBLE = MetricDescriptorType.GAUGE_DOUBLE; -const LABEL_KEYS: LabelKey[] = [{key: 'code', description: 'desc'}]; -const LABEL_VALUES_200: LabelValue[] = [{value: '200'}]; -const LABEL_VALUES_400: LabelValue[] = [{value: '400'}]; -const LABEL_VALUES_EXRTA: LabelValue[] = [{value: '200'}, {value: '400'}]; +const LABEL_KEYS: LabelKey[] = [{ key: 'code', description: 'desc' }]; +const LABEL_VALUES_200: LabelValue[] = [{ value: '200' }]; +const LABEL_VALUES_400: LabelValue[] = [{ value: '400' }]; +const LABEL_VALUES_EXRTA: LabelValue[] = [{ value: '200' }, { value: '400' }]; const UNSET_LABEL_VALUE: LabelValue = { - value: null + value: null, }; const EMPTY_CONSTANT_LABELS = new Map(); const CONSTANT_LABELS = new Map(); -CONSTANT_LABELS.set({key: 'host', description: 'host'}, {value: 'localhost'}); +CONSTANT_LABELS.set( + { key: 'host', description: 'host' }, + { value: 'localhost' } +); describe('GAUGE_INT64', () => { let instance: Gauge; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; const expectedMetricDescriptor = { name: METRIC_NAME, description: METRIC_DESCRIPTION, unit: UNIT, type: GAUGE_INT64, - labelKeys: LABEL_KEYS + labelKeys: LABEL_KEYS, }; beforeEach(() => { instance = new Gauge( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, GAUGE_INT64, LABEL_KEYS, - EMPTY_CONSTANT_LABELS); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + GAUGE_INT64, + LABEL_KEYS, + EMPTY_CONSTANT_LABELS + ); process.hrtime = () => [100, 1e7]; Date.now = () => 1450000000000; @@ -68,12 +81,11 @@ describe('GAUGE_INT64', () => { }); describe('getOrCreateTimeSeries()', () => { - it('should throw an error when the keys and values dont have same size', - () => { - assert.throws(() => { - instance.getOrCreateTimeSeries(LABEL_VALUES_EXRTA); - }, /^Error: Label Keys and Label Values don't have same size$/); - }); + it('should throw an error when the keys and values dont have same size', () => { + assert.throws(() => { + instance.getOrCreateTimeSeries(LABEL_VALUES_EXRTA); + }, /^Error: Label Keys and Label Values don't have same size$/); + }); it('should return a Metric', () => { const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200); point.add(10); @@ -82,15 +94,20 @@ describe('GAUGE_INT64', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [ + { value: 10, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); // add value and create new timeseries. point.add(5); @@ -102,20 +119,28 @@ describe('GAUGE_INT64', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: LABEL_VALUES_200, - points: [{ - value: 15, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] + points: [ + { + value: 15, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], }, { labelValues: LABEL_VALUES_400, - points: [{ - value: -8, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - } + points: [ + { + value: -8, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); }); it('should not create same timeseries again', () => { @@ -125,30 +150,40 @@ describe('GAUGE_INT64', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [ + { value: 10, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); // create timeseries with same labels. const point1 = instance.getOrCreateTimeSeries(LABEL_VALUES_200); point1.add(30); metric = instance.getMetric(); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [ + { value: 40, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); }); }); describe('getDefaultTimeSeries()', () => { @@ -159,26 +194,42 @@ describe('GAUGE_INT64', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: [UNSET_LABEL_VALUE], - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [UNSET_LABEL_VALUE], + points: [ + { value: 10, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); }); it('should return same timeseries for interchanged labels', () => { instance = new Gauge( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, GAUGE_INT64, - [{key: 'k1', description: 'desc'}, {key: 'k2', description: 'desc'}], - EMPTY_CONSTANT_LABELS); - const point = - instance.getOrCreateTimeSeries([{value: '200'}, {value: '400'}]); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + GAUGE_INT64, + [ + { key: 'k1', description: 'desc' }, + { key: 'k2', description: 'desc' }, + ], + EMPTY_CONSTANT_LABELS + ); + const point = instance.getOrCreateTimeSeries([ + { value: '200' }, + { value: '400' }, + ]); point.add(200); - const point1 = - instance.getOrCreateTimeSeries([{value: '400'}, {value: '200'}]); + const point1 = instance.getOrCreateTimeSeries([ + { value: '400' }, + { value: '200' }, + ]); point1.add(400); const metric = instance.getMetric(); assert.strictEqual(metric!.timeseries.length, 1); @@ -186,37 +237,61 @@ describe('GAUGE_INT64', () => { it('should add constant labels', () => { instance = new Gauge( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, GAUGE_INT64, - [{key: 'k1', description: 'desc'}, {key: 'k2', description: 'desc'}], - CONSTANT_LABELS); - const point = - instance.getOrCreateTimeSeries([{value: '200'}, {value: '400'}]); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + GAUGE_INT64, + [ + { key: 'k1', description: 'desc' }, + { key: 'k2', description: 'desc' }, + ], + CONSTANT_LABELS + ); + const point = instance.getOrCreateTimeSeries([ + { value: '200' }, + { value: '400' }, + ]); point.add(200); const metric = instance.getMetric(); assert.strictEqual(metric!.timeseries.length, 1); assert.deepStrictEqual(metric!.descriptor.labelKeys, [ - {key: 'k1', description: 'desc'}, {key: 'k2', description: 'desc'}, - {key: 'host', description: 'host'} + { key: 'k1', description: 'desc' }, + { key: 'k2', description: 'desc' }, + { key: 'host', description: 'host' }, ]); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: [{value: '200'}, {value: '400'}, {value: 'localhost'}], - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [ + { value: '200' }, + { value: '400' }, + { value: 'localhost' }, + ], + points: [ + { value: 200, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); }); it('should create same labelValues as labelKeys', () => { instance = new Gauge( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, GAUGE_INT64, - [ - {key: 'k1', description: 'desc'}, {key: 'k2', description: 'desc'}, - {key: 'k3', description: 'desc'} - ], - EMPTY_CONSTANT_LABELS); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + GAUGE_INT64, + [ + { key: 'k1', description: 'desc' }, + { key: 'k2', description: 'desc' }, + { key: 'k3', description: 'desc' }, + ], + EMPTY_CONSTANT_LABELS + ); const point = instance.getDefaultTimeSeries(); point.add(200); const metric = instance.getMetric(); @@ -224,16 +299,24 @@ describe('GAUGE_INT64', () => { assert.deepStrictEqual(metric!.descriptor.labelKeys.length, 3); assert.deepStrictEqual(metric!.descriptor.type, 1); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: - [UNSET_LABEL_VALUE, UNSET_LABEL_VALUE, UNSET_LABEL_VALUE], - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [ + UNSET_LABEL_VALUE, + UNSET_LABEL_VALUE, + UNSET_LABEL_VALUE, + ], + points: [ + { value: 200, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); }); it('should use previously created default timeseries', () => { const point = instance.getDefaultTimeSeries(); @@ -242,15 +325,20 @@ describe('GAUGE_INT64', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: [UNSET_LABEL_VALUE], - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [UNSET_LABEL_VALUE], + points: [ + { value: 300, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); // get default timeseries again. const point1 = instance.getDefaultTimeSeries(); point1.add(400); @@ -258,15 +346,20 @@ describe('GAUGE_INT64', () => { assert.notStrictEqual(metric, null); assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor); assert.strictEqual(metric!.timeseries.length, 1); - assert.deepStrictEqual( - metric!.timeseries, [{ - labelValues: [UNSET_LABEL_VALUE], - points: [{ + assert.deepStrictEqual(metric!.timeseries, [ + { + labelValues: [UNSET_LABEL_VALUE], + points: [ + { value: 700, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - }]); + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, + ]); }); }); describe('removeTimeSeries()', () => { @@ -302,19 +395,24 @@ describe('GAUGE_DOUBLE', () => { let instance: Gauge; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; const expectedMetricDescriptor = { name: METRIC_NAME, description: METRIC_DESCRIPTION, unit: UNIT, type: GAUGE_DOUBLE, - labelKeys: LABEL_KEYS + labelKeys: LABEL_KEYS, }; beforeEach(() => { instance = new Gauge( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, GAUGE_DOUBLE, LABEL_KEYS, - EMPTY_CONSTANT_LABELS); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + GAUGE_DOUBLE, + LABEL_KEYS, + EMPTY_CONSTANT_LABELS + ); process.hrtime = () => [100, 1e7]; Date.now = () => 1450000000000; @@ -330,12 +428,11 @@ describe('GAUGE_DOUBLE', () => { }); describe('getOrCreateTimeSeries()', () => { - it('should throw an error when the keys and values dont have same size', - () => { - assert.throws(() => { - instance.getOrCreateTimeSeries(LABEL_VALUES_EXRTA); - }, /^Error: Label Keys and Label Values don't have same size$/); - }); + it('should throw an error when the keys and values dont have same size', () => { + assert.throws(() => { + instance.getOrCreateTimeSeries(LABEL_VALUES_EXRTA); + }, /^Error: Label Keys and Label Values don't have same size$/); + }); it('should return a Metric', () => { const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200); point.add(10.34); @@ -347,11 +444,16 @@ describe('GAUGE_DOUBLE', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: LABEL_VALUES_200, - points: [{ - value: 10.34, - timestamp: {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }], - } + points: [ + { + value: 10.34, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); // add value and create new timeseries. point.add(5.12); @@ -362,20 +464,28 @@ describe('GAUGE_DOUBLE', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: LABEL_VALUES_200, - points: [{ - value: 15.46, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] + points: [ + { + value: 15.46, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], }, { labelValues: LABEL_VALUES_400, - points: [{ - value: -8.3, - timestamp: - {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }] - } + points: [ + { + value: -8.3, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); }); it('should not create same timeseries again', () => { @@ -388,11 +498,16 @@ describe('GAUGE_DOUBLE', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: LABEL_VALUES_200, - points: [{ - value: 12.1, - timestamp: {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }], - } + points: [ + { + value: 12.1, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); // create timeseries with same labels. const point1 = instance.getOrCreateTimeSeries(LABEL_VALUES_200); @@ -403,11 +518,16 @@ describe('GAUGE_DOUBLE', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: LABEL_VALUES_200, - points: [{ - value: 42.28, - timestamp: {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }], - } + points: [ + { + value: 42.28, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); }); }); @@ -422,11 +542,16 @@ describe('GAUGE_DOUBLE', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: [UNSET_LABEL_VALUE], - points: [{ - value: 10.1, - timestamp: {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }], - } + points: [ + { + value: 10.1, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); }); it('should use previously created default timeseries', () => { @@ -439,11 +564,16 @@ describe('GAUGE_DOUBLE', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: [UNSET_LABEL_VALUE], - points: [{ - value: 300.1, - timestamp: {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }], - } + points: [ + { + value: 300.1, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); // get default timeseries again. const point1 = instance.getDefaultTimeSeries(); @@ -455,21 +585,31 @@ describe('GAUGE_DOUBLE', () => { assert.deepStrictEqual(metric!.timeseries, [ { labelValues: [UNSET_LABEL_VALUE], - points: [{ - value: 700.2, - timestamp: {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }], - } + points: [ + { + value: 700.2, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); }); it('should create same labelValues as labelKeys', () => { instance = new Gauge( - METRIC_NAME, METRIC_DESCRIPTION, UNIT, GAUGE_DOUBLE, - [ - {key: 'k1', description: 'desc'}, {key: 'k2', description: 'desc'}, - {key: 'k3', description: 'desc'} - ], - EMPTY_CONSTANT_LABELS); + METRIC_NAME, + METRIC_DESCRIPTION, + UNIT, + GAUGE_DOUBLE, + [ + { key: 'k1', description: 'desc' }, + { key: 'k2', description: 'desc' }, + { key: 'k3', description: 'desc' }, + ], + EMPTY_CONSTANT_LABELS + ); const point = instance.getDefaultTimeSeries(); point.add(10.1); const metric = instance.getMetric(); @@ -479,13 +619,21 @@ describe('GAUGE_DOUBLE', () => { assert.strictEqual(metric!.timeseries.length, 1); assert.deepStrictEqual(metric!.timeseries, [ { - labelValues: - [UNSET_LABEL_VALUE, UNSET_LABEL_VALUE, UNSET_LABEL_VALUE], - points: [{ - value: 10.1, - timestamp: {nanos: mockedTime.nanos, seconds: mockedTime.seconds} - }], - } + labelValues: [ + UNSET_LABEL_VALUE, + UNSET_LABEL_VALUE, + UNSET_LABEL_VALUE, + ], + points: [ + { + value: 10.1, + timestamp: { + nanos: mockedTime.nanos, + seconds: mockedTime.seconds, + }, + }, + ], + }, ]); }); }); diff --git a/packages/opencensus-core/test/test-metric-component.ts b/packages/opencensus-core/test/test-metric-component.ts index 4ddcc90fe..09dbe1cd9 100644 --- a/packages/opencensus-core/test/test-metric-component.ts +++ b/packages/opencensus-core/test/test-metric-component.ts @@ -15,9 +15,9 @@ */ import * as assert from 'assert'; -import {metricProducerManagerInstance} from '../src/metrics/export/metric-producer-manager'; -import {MetricsComponent} from '../src/metrics/metric-component'; -import {MetricRegistry} from '../src/metrics/metric-registry'; +import { metricProducerManagerInstance } from '../src/metrics/export/metric-producer-manager'; +import { MetricsComponent } from '../src/metrics/metric-component'; +import { MetricRegistry } from '../src/metrics/metric-registry'; describe('MetricsComponent()', () => { let metricsComponent: MetricsComponent; @@ -33,8 +33,13 @@ describe('MetricsComponent()', () => { it('should register metricRegistry to MetricProducerManger', () => { assert.strictEqual( - metricProducerManagerInstance.getAllMetricProducer().size, 1); - assert.ok(metricProducerManagerInstance.getAllMetricProducer().has( - metricsComponent.getMetricRegistry().getMetricProducer())); + metricProducerManagerInstance.getAllMetricProducer().size, + 1 + ); + assert.ok( + metricProducerManagerInstance + .getAllMetricProducer() + .has(metricsComponent.getMetricRegistry().getMetricProducer()) + ); }); }); diff --git a/packages/opencensus-core/test/test-metric-producer-manager.ts b/packages/opencensus-core/test/test-metric-producer-manager.ts index a051c04ca..311abe97f 100644 --- a/packages/opencensus-core/test/test-metric-producer-manager.ts +++ b/packages/opencensus-core/test/test-metric-producer-manager.ts @@ -15,8 +15,8 @@ */ import * as assert from 'assert'; -import {metricProducerManagerInstance} from '../src/metrics/export/metric-producer-manager'; -import {MetricRegistry} from '../src/metrics/metric-registry'; +import { metricProducerManagerInstance } from '../src/metrics/export/metric-producer-manager'; +import { MetricRegistry } from '../src/metrics/metric-registry'; describe('MetricProducerManager()', () => { const registry: MetricRegistry = new MetricRegistry(); @@ -31,44 +31,38 @@ describe('MetricProducerManager()', () => { describe('add()', () => { it('add metricproducer', () => { metricProducerManagerInstance.add(metricProducer); - const metricProducerList = - metricProducerManagerInstance.getAllMetricProducer(); + const metricProducerList = metricProducerManagerInstance.getAllMetricProducer(); assert.notStrictEqual(metricProducerList, null); assert.strictEqual(metricProducerList.size, 1); }); - it('should not add same metricproducer metricProducerManagerInstance', - () => { - metricProducerManagerInstance.add(metricProducer); - metricProducerManagerInstance.add(metricProducer); - metricProducerManagerInstance.add(metricProducer); - const metricProducerList = - metricProducerManagerInstance.getAllMetricProducer(); + it('should not add same metricproducer metricProducerManagerInstance', () => { + metricProducerManagerInstance.add(metricProducer); + metricProducerManagerInstance.add(metricProducer); + metricProducerManagerInstance.add(metricProducer); + const metricProducerList = metricProducerManagerInstance.getAllMetricProducer(); - assert.strictEqual(metricProducerList.size, 1); - assert.ok(metricProducerList.has(metricProducer)); - }); + assert.strictEqual(metricProducerList.size, 1); + assert.ok(metricProducerList.has(metricProducer)); + }); - it('should add different metricproducer metricProducerManagerInstance', - () => { - metricProducerManagerInstance.add(metricProducer); - metricProducerManagerInstance.add(metricProducerOther); - const metricProducerList = - metricProducerManagerInstance.getAllMetricProducer(); + it('should add different metricproducer metricProducerManagerInstance', () => { + metricProducerManagerInstance.add(metricProducer); + metricProducerManagerInstance.add(metricProducerOther); + const metricProducerList = metricProducerManagerInstance.getAllMetricProducer(); - assert.strictEqual(metricProducerList.size, 2); - assert.ok(metricProducerList.has(metricProducer)); - assert.ok(metricProducerList.has(metricProducerOther)); - }); + assert.strictEqual(metricProducerList.size, 2); + assert.ok(metricProducerList.has(metricProducer)); + assert.ok(metricProducerList.has(metricProducerOther)); + }); }); describe('remove()', () => { it('remove metricproducer', () => { metricProducerManagerInstance.add(metricProducer); - const metricProducerList = - metricProducerManagerInstance.getAllMetricProducer(); + const metricProducerList = metricProducerManagerInstance.getAllMetricProducer(); assert.strictEqual(metricProducerList.size, 1); assert.ok(metricProducerList.has(metricProducer)); diff --git a/packages/opencensus-core/test/test-metric-producer.ts b/packages/opencensus-core/test/test-metric-producer.ts index 2641221a5..105e286ae 100644 --- a/packages/opencensus-core/test/test-metric-producer.ts +++ b/packages/opencensus-core/test/test-metric-producer.ts @@ -16,9 +16,20 @@ import * as assert from 'assert'; -import {AggregationType, globalStats, Measurement, MeasureUnit, TagMap, View} from '../src'; -import {LabelKey, LabelValue, MetricDescriptorType} from '../src/metrics/export/types'; -import {MetricProducerForStats} from '../src/stats/metric-producer'; +import { + AggregationType, + globalStats, + Measurement, + MeasureUnit, + TagMap, + View, +} from '../src'; +import { + LabelKey, + LabelValue, + MetricDescriptorType, +} from '../src/metrics/export/types'; +import { MetricProducerForStats } from '../src/stats/metric-producer'; describe('Metric producer for stats', () => { const metricProducerForStats = new MetricProducerForStats(globalStats); @@ -30,19 +41,24 @@ describe('Metric producer for stats', () => { const description = 'test description'; const measureDouble = globalStats.createMeasureDouble( - 'opencensus.io/test/double', MeasureUnit.UNIT, 'Measure Double'); - const tagKeys = [{name: 'testKey1'}, {name: 'testKey2'}]; + 'opencensus.io/test/double', + MeasureUnit.UNIT, + 'Measure Double' + ); + const tagKeys = [{ name: 'testKey1' }, { name: 'testKey2' }]; const tagMap = new TagMap(); - tagMap.set(tagKeys[0], {value: 'testValue1'}); - tagMap.set(tagKeys[1], {value: 'testValue2'}); + tagMap.set(tagKeys[0], { value: 'testValue1' }); + tagMap.set(tagKeys[1], { value: 'testValue2' }); const labelKeys: LabelKey[] = [ - {'key': 'testKey1', 'description': ''}, - {'key': 'testKey2', 'description': ''} + { key: 'testKey1', description: '' }, + { key: 'testKey2', description: '' }, ]; - const labelValues: LabelValue[] = - [{'value': 'testValue1'}, {'value': 'testValue2'}]; - const measurement1: Measurement = {measure: measureDouble, value: 25}; - const measurement2: Measurement = {measure: measureDouble, value: 300}; + const labelValues: LabelValue[] = [ + { value: 'testValue1' }, + { value: 'testValue2' }, + ]; + const measurement1: Measurement = { measure: measureDouble, value: 25 }; + const measurement2: Measurement = { measure: measureDouble, value: 300 }; // expected constants const expectedMetricDescriptor1 = { @@ -76,59 +92,68 @@ describe('Metric producer for stats', () => { it('should add sum stats', () => { const view: View = globalStats.createView( - viewName1, measureDouble, AggregationType.SUM, tagKeys, description); + viewName1, + measureDouble, + AggregationType.SUM, + tagKeys, + description + ); globalStats.registerView(view); view.recordMeasurement(measurement1, tagMap); const metrics = metricProducerForStats.getMetrics(); assert.strictEqual(metrics.length, 1); - const [{ - descriptor: actualMetricDescriptor1, - timeseries: actualTimeSeries1 - }] = metrics; + const [ + { descriptor: actualMetricDescriptor1, timeseries: actualTimeSeries1 }, + ] = metrics; assert.deepStrictEqual(actualMetricDescriptor1, expectedMetricDescriptor1); assert.strictEqual(actualTimeSeries1.length, 1); assert.deepStrictEqual(actualTimeSeries1[0].labelValues, labelValues); assert.strictEqual(actualTimeSeries1[0].points[0].value, 25); }); - it('should add count stats', - () => { - const view: View = globalStats.createView( - viewName2, measureDouble, AggregationType.COUNT, tagKeys, - description); - globalStats.registerView(view); - view.recordMeasurement(measurement1, tagMap); - - let metrics = metricProducerForStats.getMetrics(); - - assert.strictEqual(metrics.length, 2); - const - [{descriptor: actualMetricDescriptor1, timeseries: actualTimeSeries1}, - {descriptor: actualMetricDescriptor2, timeseries: actualTimeSeries2}] = - metrics; - assert.deepStrictEqual( - actualMetricDescriptor1, expectedMetricDescriptor1); - assert.strictEqual(actualTimeSeries1.length, 1); - assert.deepStrictEqual(actualTimeSeries1[0].labelValues, labelValues); - assert.strictEqual(actualTimeSeries1[0].points[0].value, 25); - assert.deepStrictEqual( - actualMetricDescriptor2, expectedMetricDescriptor2); - assert.strictEqual(actualTimeSeries2.length, 1); - assert.deepStrictEqual(actualTimeSeries2[0].labelValues, labelValues); - assert.strictEqual(actualTimeSeries2[0].points[0].value, 1); - - // update count view - view.recordMeasurement(measurement2, tagMap); - metrics = metricProducerForStats.getMetrics(); - assert.deepStrictEqual(metrics[1].timeseries[0].points[0].value, 2); - }); + it('should add count stats', () => { + const view: View = globalStats.createView( + viewName2, + measureDouble, + AggregationType.COUNT, + tagKeys, + description + ); + globalStats.registerView(view); + view.recordMeasurement(measurement1, tagMap); + + let metrics = metricProducerForStats.getMetrics(); + + assert.strictEqual(metrics.length, 2); + const [ + { descriptor: actualMetricDescriptor1, timeseries: actualTimeSeries1 }, + { descriptor: actualMetricDescriptor2, timeseries: actualTimeSeries2 }, + ] = metrics; + assert.deepStrictEqual(actualMetricDescriptor1, expectedMetricDescriptor1); + assert.strictEqual(actualTimeSeries1.length, 1); + assert.deepStrictEqual(actualTimeSeries1[0].labelValues, labelValues); + assert.strictEqual(actualTimeSeries1[0].points[0].value, 25); + assert.deepStrictEqual(actualMetricDescriptor2, expectedMetricDescriptor2); + assert.strictEqual(actualTimeSeries2.length, 1); + assert.deepStrictEqual(actualTimeSeries2[0].labelValues, labelValues); + assert.strictEqual(actualTimeSeries2[0].points[0].value, 1); + + // update count view + view.recordMeasurement(measurement2, tagMap); + metrics = metricProducerForStats.getMetrics(); + assert.deepStrictEqual(metrics[1].timeseries[0].points[0].value, 2); + }); it('should add lastValue stats', () => { const view: View = globalStats.createView( - viewName3, measureDouble, AggregationType.LAST_VALUE, tagKeys, - description); + viewName3, + measureDouble, + AggregationType.LAST_VALUE, + tagKeys, + description + ); globalStats.registerView(view); view.recordMeasurement(measurement1, tagMap); view.recordMeasurement(measurement2, tagMap); @@ -136,11 +161,11 @@ describe('Metric producer for stats', () => { const metrics = metricProducerForStats.getMetrics(); assert.strictEqual(metrics.length, 3); - const - [{descriptor: actualMetricDescriptor1, timeseries: actualTimeSeries1}, - {descriptor: actualMetricDescriptor2, timeseries: actualTimeSeries2}, - {descriptor: actualMetricDescriptor3, timeseries: actualTimeSeries3}] = - metrics; + const [ + { descriptor: actualMetricDescriptor1, timeseries: actualTimeSeries1 }, + { descriptor: actualMetricDescriptor2, timeseries: actualTimeSeries2 }, + { descriptor: actualMetricDescriptor3, timeseries: actualTimeSeries3 }, + ] = metrics; assert.deepStrictEqual(actualMetricDescriptor1, expectedMetricDescriptor1); assert.strictEqual(actualTimeSeries1.length, 1); assert.strictEqual(actualTimeSeries1.length, 1); @@ -158,23 +183,28 @@ describe('Metric producer for stats', () => { const measurementValues = [1.1, 2.3, 3.2, 4.3, 5.2]; const buckets = [2, 4, 6]; const view: View = globalStats.createView( - viewName3, measureDouble, AggregationType.DISTRIBUTION, tagKeys, - description, buckets); + viewName3, + measureDouble, + AggregationType.DISTRIBUTION, + tagKeys, + description, + buckets + ); globalStats.registerView(view); for (const value of measurementValues) { - const measurement: Measurement = {measure: measureDouble, value}; + const measurement: Measurement = { measure: measureDouble, value }; view.recordMeasurement(measurement, tagMap); } const metrics = metricProducerForStats.getMetrics(); assert.strictEqual(metrics.length, 4); - const - [{descriptor: actualMetricDescriptor1, timeseries: actualTimeSeries1}, - {descriptor: actualMetricDescriptor2, timeseries: actualTimeSeries2}, - {descriptor: actualMetricDescriptor3, timeseries: actualTimeSeries3}, - {descriptor: actualMetricDescriptor4, timeseries: actualTimeSeries4}] = - metrics; + const [ + { descriptor: actualMetricDescriptor1, timeseries: actualTimeSeries1 }, + { descriptor: actualMetricDescriptor2, timeseries: actualTimeSeries2 }, + { descriptor: actualMetricDescriptor3, timeseries: actualTimeSeries3 }, + { descriptor: actualMetricDescriptor4, timeseries: actualTimeSeries4 }, + ] = metrics; assert.deepStrictEqual(actualMetricDescriptor1, expectedMetricDescriptor1); assert.strictEqual(actualTimeSeries1.length, 1); assert.deepStrictEqual(actualTimeSeries1[0].labelValues, labelValues); @@ -189,11 +219,11 @@ describe('Metric producer for stats', () => { assert.strictEqual(actualTimeSeries4.length, 1); assert.deepStrictEqual(actualTimeSeries4[0].labelValues, labelValues); assert.deepStrictEqual(actualTimeSeries4[0].points[0].value, { - 'bucketOptions': {'explicit': {'bounds': [2, 4, 6]}}, - 'buckets': [{count: 1}, {count: 2}, {count: 2}, {count: 0}], - 'count': 5, - 'sum': 16.099999999999998, - 'sumOfSquaredDeviation': 10.427999999999997 + bucketOptions: { explicit: { bounds: [2, 4, 6] } }, + buckets: [{ count: 1 }, { count: 2 }, { count: 2 }, { count: 0 }], + count: 5, + sum: 16.099999999999998, + sumOfSquaredDeviation: 10.427999999999997, }); }); }); diff --git a/packages/opencensus-core/test/test-metric-registry.ts b/packages/opencensus-core/test/test-metric-registry.ts index 288511311..7e645cbcf 100644 --- a/packages/opencensus-core/test/test-metric-registry.ts +++ b/packages/opencensus-core/test/test-metric-registry.ts @@ -15,29 +15,34 @@ */ import * as assert from 'assert'; -import {TEST_ONLY} from '../src/common/time-util'; -import {LabelKey, LabelValue, MetricDescriptorType, Timestamp} from '../src/metrics/export/types'; -import {MetricRegistry} from '../src/metrics/metric-registry'; -import {MeasureUnit} from '../src/stats/types'; +import { TEST_ONLY } from '../src/common/time-util'; +import { + LabelKey, + LabelValue, + MetricDescriptorType, + Timestamp, +} from '../src/metrics/export/types'; +import { MetricRegistry } from '../src/metrics/metric-registry'; +import { MeasureUnit } from '../src/stats/types'; const METRIC_NAME = 'metric-name'; const METRIC_DESCRIPTION = 'metric-description'; const UNIT = MeasureUnit.UNIT; -const LABEL_KEYS: LabelKey[] = [{key: 'code', description: 'desc'}]; -const LABEL_VALUES_200: LabelValue[] = [{value: '200'}]; -const LABEL_VALUES_400: LabelValue[] = [{value: '400'}]; +const LABEL_KEYS: LabelKey[] = [{ key: 'code', description: 'desc' }]; +const LABEL_VALUES_200: LabelValue[] = [{ value: '200' }]; +const LABEL_VALUES_400: LabelValue[] = [{ value: '400' }]; const METRIC_OPTIONS = { description: METRIC_DESCRIPTION, unit: UNIT, - labelKeys: LABEL_KEYS + labelKeys: LABEL_KEYS, }; describe('addInt64Gauge', () => { let registry: MetricRegistry; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; beforeEach(() => { registry = new MetricRegistry(); @@ -62,21 +67,22 @@ describe('addInt64Gauge', () => { const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.GAUGE_INT64 + type: MetricDescriptorType.GAUGE_INT64, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 100); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); }); it('should return a metric without options', () => { @@ -86,39 +92,39 @@ describe('addInt64Gauge', () => { const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: '', labelKeys: [], unit: '1', - type: MetricDescriptorType.GAUGE_INT64 + type: MetricDescriptorType.GAUGE_INT64, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 100); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); - }); - - it('should throw an error when the duplicate keys in labelKeys and constantLabels', - () => { - const constantLabels = new Map(); - constantLabels.set({key: 'k1'}, {value: 'v1'}); - const labelKeys = [{key: 'k1', description: 'desc'}]; - assert.throws(() => { - registry.addInt64Gauge(METRIC_NAME, {constantLabels, labelKeys}); - }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); - }); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); + }); + + it('should throw an error when the duplicate keys in labelKeys and constantLabels', () => { + const constantLabels = new Map(); + constantLabels.set({ key: 'k1' }, { value: 'v1' }); + const labelKeys = [{ key: 'k1', description: 'desc' }]; + assert.throws(() => { + registry.addInt64Gauge(METRIC_NAME, { constantLabels, labelKeys }); + }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); + }); }); describe('addDoubleGauge', () => { let registry: MetricRegistry; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; beforeEach(() => { registry = new MetricRegistry(); @@ -146,21 +152,22 @@ describe('addDoubleGauge', () => { const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.GAUGE_DOUBLE + type: MetricDescriptorType.GAUGE_DOUBLE, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 0.7); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); }); it('should throw an error when the register same metric', () => { @@ -172,15 +179,15 @@ describe('addDoubleGauge', () => { it('should throw an error when the constant labels elements are null', () => { let constantLabels = new Map(); - constantLabels.set({key: 'k1'}, null); + constantLabels.set({ key: 'k1' }, null); assert.throws(() => { - registry.addDoubleGauge(METRIC_NAME, {constantLabels}); + registry.addDoubleGauge(METRIC_NAME, { constantLabels }); }, /^Error: constantLabels elements should not be a NULL$/); constantLabels = new Map(); constantLabels.set(null, null); assert.throws(() => { - registry.addDoubleGauge(METRIC_NAME, {constantLabels}); + registry.addDoubleGauge(METRIC_NAME, { constantLabels }); }, /^Error: constantLabels elements should not be a NULL$/); }); @@ -191,21 +198,22 @@ describe('addDoubleGauge', () => { const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: '', labelKeys: [], unit: '1', - type: MetricDescriptorType.GAUGE_DOUBLE + type: MetricDescriptorType.GAUGE_DOUBLE, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 5.5); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); }); }); @@ -213,7 +221,7 @@ describe('addDerivedInt64Gauge', () => { let registry: MetricRegistry; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; beforeEach(() => { registry = new MetricRegistry(); @@ -234,28 +242,31 @@ describe('addDerivedInt64Gauge', () => { it('should return a metric', () => { const map = new Map(); map.set('key', 'value'); - const derivedInt64Gauge = - registry.addDerivedInt64Gauge(METRIC_NAME, METRIC_OPTIONS); + const derivedInt64Gauge = registry.addDerivedInt64Gauge( + METRIC_NAME, + METRIC_OPTIONS + ); derivedInt64Gauge.createTimeSeries(LABEL_VALUES_200, map); map.set('key1', 'value1'); const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.GAUGE_INT64 + type: MetricDescriptorType.GAUGE_INT64, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 2); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); }); it('should throw an error when the register same metric', () => { @@ -265,22 +276,20 @@ describe('addDerivedInt64Gauge', () => { }, /^Error: A metric with the name metric-name has already been registered.$/); }); - it('should throw an error when the duplicate keys in labelKeys and constantLabels', - () => { - const constantLabels = new Map(); - constantLabels.set({key: 'k1'}, {value: 'v1'}); - const labelKeys = [{key: 'k1', description: 'desc'}]; - assert.throws(() => { - registry.addDerivedInt64Gauge( - METRIC_NAME, {constantLabels, labelKeys}); - }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); - }); + it('should throw an error when the duplicate keys in labelKeys and constantLabels', () => { + const constantLabels = new Map(); + constantLabels.set({ key: 'k1' }, { value: 'v1' }); + const labelKeys = [{ key: 'k1', description: 'desc' }]; + assert.throws(() => { + registry.addDerivedInt64Gauge(METRIC_NAME, { constantLabels, labelKeys }); + }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); + }); it('should throw an error when the constant labels elements are null', () => { const constantLabels = new Map(); - constantLabels.set({key: 'k1'}, null); + constantLabels.set({ key: 'k1' }, null); assert.throws(() => { - registry.addDerivedInt64Gauge(METRIC_NAME, {constantLabels}); + registry.addDerivedInt64Gauge(METRIC_NAME, { constantLabels }); }, /^Error: constantLabels elements should not be a NULL$/); }); @@ -293,21 +302,22 @@ describe('addDerivedInt64Gauge', () => { const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: '', labelKeys: [], unit: '1', - type: MetricDescriptorType.GAUGE_INT64 + type: MetricDescriptorType.GAUGE_INT64, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 2); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); }); }); @@ -315,7 +325,7 @@ describe('addDerivedDoubleGauge', () => { let registry: MetricRegistry; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; beforeEach(() => { registry = new MetricRegistry(); @@ -339,27 +349,30 @@ describe('addDerivedDoubleGauge', () => { return 0.7; } } - const derivedDoubleGauge = - registry.addDerivedDoubleGauge(METRIC_NAME, METRIC_OPTIONS); + const derivedDoubleGauge = registry.addDerivedDoubleGauge( + METRIC_NAME, + METRIC_OPTIONS + ); derivedDoubleGauge.createTimeSeries(LABEL_VALUES_200, new QueueManager()); const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.GAUGE_DOUBLE + type: MetricDescriptorType.GAUGE_DOUBLE, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 0.7); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); }); it('should throw an error when the register same metric', () => { @@ -374,7 +387,7 @@ describe('addInt64Cumulative', () => { let registry: MetricRegistry; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; beforeEach(() => { registry = new MetricRegistry(); @@ -399,21 +412,22 @@ describe('addInt64Cumulative', () => { const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.CUMULATIVE_INT64 + type: MetricDescriptorType.CUMULATIVE_INT64, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 1); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); }); it('should return a metric without options', () => { @@ -423,39 +437,39 @@ describe('addInt64Cumulative', () => { const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: '', labelKeys: [], unit: UNIT, - type: MetricDescriptorType.CUMULATIVE_INT64 + type: MetricDescriptorType.CUMULATIVE_INT64, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 100); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); - }); - - it('should throw an error when the duplicate keys in labelKeys and constantLabels', - () => { - const constantLabels = new Map(); - constantLabels.set({key: 'k1'}, {value: 'v1'}); - const labelKeys = [{key: 'k1', description: 'desc'}]; - assert.throws(() => { - registry.addInt64Cumulative(METRIC_NAME, {constantLabels, labelKeys}); - }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); - }); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); + }); + + it('should throw an error when the duplicate keys in labelKeys and constantLabels', () => { + const constantLabels = new Map(); + constantLabels.set({ key: 'k1' }, { value: 'v1' }); + const labelKeys = [{ key: 'k1', description: 'desc' }]; + assert.throws(() => { + registry.addInt64Cumulative(METRIC_NAME, { constantLabels, labelKeys }); + }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); + }); }); describe('addDoubleCumulative', () => { let registry: MetricRegistry; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; beforeEach(() => { registry = new MetricRegistry(); @@ -474,28 +488,31 @@ describe('addDoubleCumulative', () => { }); it('should return a metric', () => { - const int64Gauge = - registry.addDoubleCumulative(METRIC_NAME, METRIC_OPTIONS); + const int64Gauge = registry.addDoubleCumulative( + METRIC_NAME, + METRIC_OPTIONS + ); const pointEntry = int64Gauge.getOrCreateTimeSeries(LABEL_VALUES_200); pointEntry.inc(1.1); const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.CUMULATIVE_DOUBLE + type: MetricDescriptorType.CUMULATIVE_DOUBLE, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 1.1); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); }); it('should return a metric without options', () => { @@ -506,39 +523,39 @@ describe('addDoubleCumulative', () => { const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: '', labelKeys: [], unit: UNIT, - type: MetricDescriptorType.CUMULATIVE_DOUBLE + type: MetricDescriptorType.CUMULATIVE_DOUBLE, }); assert.strictEqual(timeseries.length, 1); - const [{points}] = timeseries; + const [{ points }] = timeseries; const [point] = points; assert.strictEqual(point.value, 101.12); - assert.deepStrictEqual( - point.timestamp, - {seconds: mockedTime.seconds, nanos: mockedTime.nanos}); - }); - - it('should throw an error when the duplicate keys in labelKeys and constantLabels', - () => { - const constantLabels = new Map(); - constantLabels.set({key: 'k1'}, {value: 'v1'}); - const labelKeys = [{key: 'k1', description: 'desc'}]; - assert.throws(() => { - registry.addDoubleCumulative(METRIC_NAME, {constantLabels, labelKeys}); - }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); - }); + assert.deepStrictEqual(point.timestamp, { + seconds: mockedTime.seconds, + nanos: mockedTime.nanos, + }); + }); + + it('should throw an error when the duplicate keys in labelKeys and constantLabels', () => { + const constantLabels = new Map(); + constantLabels.set({ key: 'k1' }, { value: 'v1' }); + const labelKeys = [{ key: 'k1', description: 'desc' }]; + assert.throws(() => { + registry.addDoubleCumulative(METRIC_NAME, { constantLabels, labelKeys }); + }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); + }); }); describe('addDerivedInt64Cumulative', () => { let registry: MetricRegistry; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; beforeEach(() => { registry = new MetricRegistry(); @@ -559,27 +576,31 @@ describe('addDerivedInt64Cumulative', () => { it('should return a metric', () => { const map = new Map(); map.set('key', 'value'); - const derivedInt64Cumulative = - registry.addDerivedInt64Cumulative(METRIC_NAME, METRIC_OPTIONS); + const derivedInt64Cumulative = registry.addDerivedInt64Cumulative( + METRIC_NAME, + METRIC_OPTIONS + ); derivedInt64Cumulative.createTimeSeries(LABEL_VALUES_200, map); map.set('key1', 'value1'); const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.CUMULATIVE_INT64 + type: MetricDescriptorType.CUMULATIVE_INT64, }); assert.strictEqual(timeseries.length, 1); - assert.deepStrictEqual(timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 2, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 2, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); }); it('should throw an error when the register same metric', () => { @@ -589,49 +610,53 @@ describe('addDerivedInt64Cumulative', () => { }, /^Error: A metric with the name metric-name has already been registered.$/); }); - it('should throw an error when the duplicate keys in labelKeys and constantLabels', - () => { - const constantLabels = new Map(); - constantLabels.set({key: 'k1'}, {value: 'v1'}); - const labelKeys = [{key: 'k1', description: 'desc'}]; - assert.throws(() => { - registry.addDerivedInt64Cumulative( - METRIC_NAME, {constantLabels, labelKeys}); - }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); - }); + it('should throw an error when the duplicate keys in labelKeys and constantLabels', () => { + const constantLabels = new Map(); + constantLabels.set({ key: 'k1' }, { value: 'v1' }); + const labelKeys = [{ key: 'k1', description: 'desc' }]; + assert.throws(() => { + registry.addDerivedInt64Cumulative(METRIC_NAME, { + constantLabels, + labelKeys, + }); + }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); + }); it('should throw an error when the constant labels elements are null', () => { const constantLabels = new Map(); - constantLabels.set({key: 'k1'}, null); + constantLabels.set({ key: 'k1' }, null); assert.throws(() => { - registry.addDerivedInt64Cumulative(METRIC_NAME, {constantLabels}); + registry.addDerivedInt64Cumulative(METRIC_NAME, { constantLabels }); }, /^Error: constantLabels elements should not be a NULL$/); }); it('should return a metric without options', () => { const map = new Map(); map.set('key', 'value'); - const derivedInt64Cumulative = - registry.addDerivedInt64Cumulative(METRIC_NAME); + const derivedInt64Cumulative = registry.addDerivedInt64Cumulative( + METRIC_NAME + ); derivedInt64Cumulative.createTimeSeries([], map); map.set('key1', 'value1'); const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: '', labelKeys: [], unit: '1', - type: MetricDescriptorType.CUMULATIVE_INT64 + type: MetricDescriptorType.CUMULATIVE_INT64, }); assert.strictEqual(timeseries.length, 1); - assert.deepStrictEqual(timeseries, [{ - labelValues: [], - points: [{value: 2, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(timeseries, [ + { + labelValues: [], + points: [{ value: 2, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); }); }); @@ -639,7 +664,7 @@ describe('addDerivedDoubleCumulative', () => { let registry: MetricRegistry; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; beforeEach(() => { registry = new MetricRegistry(); @@ -664,28 +689,32 @@ describe('addDerivedDoubleCumulative', () => { } } const queue = new QueueManager(); - const derivedDoubleCumulative = - registry.addDerivedDoubleCumulative(METRIC_NAME, METRIC_OPTIONS); + const derivedDoubleCumulative = registry.addDerivedDoubleCumulative( + METRIC_NAME, + METRIC_OPTIONS + ); derivedDoubleCumulative.createTimeSeries(LABEL_VALUES_200, () => { return queue.Value; }); const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.CUMULATIVE_DOUBLE + type: MetricDescriptorType.CUMULATIVE_DOUBLE, }); assert.strictEqual(timeseries.length, 1); - assert.deepStrictEqual(timeseries, [{ - labelValues: LABEL_VALUES_200, - points: [{value: 45.5, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(timeseries, [ + { + labelValues: LABEL_VALUES_200, + points: [{ value: 45.5, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); }); it('should throw an error when the register same metric', () => { @@ -695,22 +724,23 @@ describe('addDerivedDoubleCumulative', () => { }, /^Error: A metric with the name metric-name has already been registered.$/); }); - it('should throw an error when the duplicate keys in labelKeys and constantLabels', - () => { - const constantLabels = new Map(); - constantLabels.set({key: 'k1'}, {value: 'v1'}); - const labelKeys = [{key: 'k1', description: 'desc'}]; - assert.throws(() => { - registry.addDerivedDoubleCumulative( - METRIC_NAME, {constantLabels, labelKeys}); - }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); - }); + it('should throw an error when the duplicate keys in labelKeys and constantLabels', () => { + const constantLabels = new Map(); + constantLabels.set({ key: 'k1' }, { value: 'v1' }); + const labelKeys = [{ key: 'k1', description: 'desc' }]; + assert.throws(() => { + registry.addDerivedDoubleCumulative(METRIC_NAME, { + constantLabels, + labelKeys, + }); + }, /^Error: The keys from LabelKeys should not be present in constantLabels or LabelKeys should not contains duplicate keys$/); + }); it('should throw an error when the constant labels elements are null', () => { const constantLabels = new Map(); - constantLabels.set({key: 'k1'}, null); + constantLabels.set({ key: 'k1' }, null); assert.throws(() => { - registry.addDerivedDoubleCumulative(METRIC_NAME, {constantLabels}); + registry.addDerivedDoubleCumulative(METRIC_NAME, { constantLabels }); }, /^Error: constantLabels elements should not be a NULL$/); }); @@ -725,8 +755,9 @@ describe('addDerivedDoubleCumulative', () => { } } const mem = new MemoryInfo(); - const derivedDoubleCumulative = - registry.addDerivedDoubleCumulative(METRIC_NAME); + const derivedDoubleCumulative = registry.addDerivedDoubleCumulative( + METRIC_NAME + ); derivedDoubleCumulative.createTimeSeries([], () => { return mem.Value; }); @@ -734,20 +765,22 @@ describe('addDerivedDoubleCumulative', () => { const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 1); - const [{descriptor, timeseries}] = metrics; + const [{ descriptor, timeseries }] = metrics; assert.deepStrictEqual(descriptor, { name: METRIC_NAME, description: '', labelKeys: [], unit: '1', - type: MetricDescriptorType.CUMULATIVE_DOUBLE + type: MetricDescriptorType.CUMULATIVE_DOUBLE, }); assert.strictEqual(timeseries.length, 1); - assert.deepStrictEqual(timeseries, [{ - labelValues: [], - points: [{value: 46.5, timestamp: mockedTime}], - startTimestamp: mockedTime - }]); + assert.deepStrictEqual(timeseries, [ + { + labelValues: [], + points: [{ value: 46.5, timestamp: mockedTime }], + startTimestamp: mockedTime, + }, + ]); }); }); @@ -755,7 +788,7 @@ describe('Add multiple gauges', () => { let registry: MetricRegistry; const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; beforeEach(() => { registry = new MetricRegistry(); @@ -781,54 +814,67 @@ describe('Add multiple gauges', () => { doubleGauge.getOrCreateTimeSeries(LABEL_VALUES_200).add(5.5); const arr = new Array(5).fill('test'); - const derivedInt64Gauge = - registry.addDerivedInt64Gauge('metric-name3', METRIC_OPTIONS); + const derivedInt64Gauge = registry.addDerivedInt64Gauge( + 'metric-name3', + METRIC_OPTIONS + ); derivedInt64Gauge.createTimeSeries(LABEL_VALUES_400, { size: () => arr.length, }); - const int64Cumulative = - registry.addInt64Cumulative('metric-name4', METRIC_OPTIONS); + const int64Cumulative = registry.addInt64Cumulative( + 'metric-name4', + METRIC_OPTIONS + ); int64Cumulative.getOrCreateTimeSeries(LABEL_VALUES_200).inc(); const metrics = registry.getMetricProducer().getMetrics(); assert.strictEqual(metrics.length, 4); - const [{descriptor: descriptor1, timeseries: timeseries1}, {descriptor: descriptor2, timeseries: timeseries2}, {descriptor: descriptor3, timeseries: timeseries3}, {descriptor: descriptor4, timeseries: timeseries4}] = metrics; + const [ + { descriptor: descriptor1, timeseries: timeseries1 }, + { descriptor: descriptor2, timeseries: timeseries2 }, + { descriptor: descriptor3, timeseries: timeseries3 }, + { descriptor: descriptor4, timeseries: timeseries4 }, + ] = metrics; assert.deepStrictEqual(descriptor1, { name: 'metric-name1', description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.GAUGE_INT64 + type: MetricDescriptorType.GAUGE_INT64, }); assert.deepStrictEqual(descriptor2, { name: 'metric-name2', description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.GAUGE_DOUBLE + type: MetricDescriptorType.GAUGE_DOUBLE, }); assert.deepStrictEqual(descriptor3, { name: 'metric-name3', description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.GAUGE_INT64 + type: MetricDescriptorType.GAUGE_INT64, }); assert.deepStrictEqual(descriptor4, { name: 'metric-name4', description: METRIC_DESCRIPTION, labelKeys: LABEL_KEYS, unit: UNIT, - type: MetricDescriptorType.CUMULATIVE_INT64 + type: MetricDescriptorType.CUMULATIVE_INT64, }); assert.strictEqual(timeseries1.length, 1); assert.strictEqual(timeseries1[0].points.length, 1); assert.strictEqual(timeseries1[0].points[0].value, 100); assert.strictEqual( - timeseries1[0].points[0].timestamp.seconds, mockedTime.seconds); + timeseries1[0].points[0].timestamp.seconds, + mockedTime.seconds + ); assert.strictEqual( - timeseries1[0].points[0].timestamp.nanos, mockedTime.nanos); + timeseries1[0].points[0].timestamp.nanos, + mockedTime.nanos + ); assert.strictEqual(timeseries2.length, 1); assert.strictEqual(timeseries2[0].points.length, 1); assert.strictEqual(timeseries2[0].points[0].value, 5.5); @@ -836,9 +882,13 @@ describe('Add multiple gauges', () => { assert.strictEqual(timeseries3[0].points.length, 1); assert.strictEqual(timeseries3[0].points[0].value, 5); assert.deepStrictEqual( - timeseries1[0].points[0].timestamp, timeseries2[0].points[0].timestamp); + timeseries1[0].points[0].timestamp, + timeseries2[0].points[0].timestamp + ); assert.deepStrictEqual( - timeseries2[0].points[0].timestamp, timeseries3[0].points[0].timestamp); + timeseries2[0].points[0].timestamp, + timeseries3[0].points[0].timestamp + ); assert.strictEqual(timeseries4.length, 1); assert.strictEqual(timeseries4[0].points.length, 1); assert.strictEqual(timeseries4[0].points[0].value, 1); diff --git a/packages/opencensus-core/test/test-metric-utils.ts b/packages/opencensus-core/test/test-metric-utils.ts index 08b70c481..0cc1639a6 100644 --- a/packages/opencensus-core/test/test-metric-utils.ts +++ b/packages/opencensus-core/test/test-metric-utils.ts @@ -16,10 +16,14 @@ import * as assert from 'assert'; -import {BaseView, MetricUtils} from '../src'; -import {MetricDescriptorType} from '../src/metrics/export/types'; -import {AggregationType, Measure, MeasureType, MeasureUnit} from '../src/stats/types'; - +import { BaseView, MetricUtils } from '../src'; +import { MetricDescriptorType } from '../src/metrics/export/types'; +import { + AggregationType, + Measure, + MeasureType, + MeasureUnit, +} from '../src/stats/types'; describe('MetricUtil', () => { it('should convert view to MetricDescriptor', () => { @@ -27,36 +31,54 @@ describe('MetricUtil', () => { const measure: Measure = { name: 'Test Measure', type: MeasureType.DOUBLE, - unit: MeasureUnit.UNIT + unit: MeasureUnit.UNIT, }; - const tagKeys = [{name: 'testKey1'}, {name: 'testKey2'}]; + const tagKeys = [{ name: 'testKey1' }, { name: 'testKey2' }]; const view = new BaseView( - 'test/view/name', measure, AggregationType.LAST_VALUE, tagKeys, - VIEW_DESCRIPTION); + 'test/view/name', + measure, + AggregationType.LAST_VALUE, + tagKeys, + VIEW_DESCRIPTION + ); const metricDescriptor = MetricUtils.viewToMetricDescriptor(view); assert.ok(metricDescriptor); assert.strictEqual(metricDescriptor.name, view.name); assert.strictEqual(metricDescriptor.unit, MeasureUnit.UNIT); assert.strictEqual( - metricDescriptor.type, MetricDescriptorType.GAUGE_DOUBLE); + metricDescriptor.type, + MetricDescriptorType.GAUGE_DOUBLE + ); assert.strictEqual(metricDescriptor.description, VIEW_DESCRIPTION); assert.deepStrictEqual(metricDescriptor.labelKeys, [ - {key: 'testKey1', description: ''}, {key: 'testKey2', description: ''} + { key: 'testKey1', description: '' }, + { key: 'testKey2', description: '' }, ]); }); it('should convert tag values to label values', () => { - const tags = [{value: 'value1'}, {value: 'value2'}, {value: ''}, null]; - assert.deepStrictEqual( - MetricUtils.tagValuesToLabelValues(tags), - [{value: 'value1'}, {value: 'value2'}, {value: ''}, {value: null}]); + const tags = [ + { value: 'value1' }, + { value: 'value2' }, + { value: '' }, + null, + ]; + assert.deepStrictEqual(MetricUtils.tagValuesToLabelValues(tags), [ + { value: 'value1' }, + { value: 'value2' }, + { value: '' }, + { value: null }, + ]); }); it('should convert tag values to label values with null tag value', () => { - const tags = [{value: 'value1'}, null, null, null]; - assert.deepStrictEqual( - MetricUtils.tagValuesToLabelValues(tags), - [{value: 'value1'}, {value: null}, {value: null}, {value: null}]); + const tags = [{ value: 'value1' }, null, null, null]; + assert.deepStrictEqual(MetricUtils.tagValuesToLabelValues(tags), [ + { value: 'value1' }, + { value: null }, + { value: null }, + { value: null }, + ]); }); }); diff --git a/packages/opencensus-core/test/test-no-record-root-span.ts b/packages/opencensus-core/test/test-no-record-root-span.ts index 9928f4cb8..4f69c4c73 100644 --- a/packages/opencensus-core/test/test-no-record-root-span.ts +++ b/packages/opencensus-core/test/test-no-record-root-span.ts @@ -15,19 +15,33 @@ */ import * as assert from 'assert'; -import {CanonicalCode, CoreTracer, LinkType, MessageEventType, SpanKind} from '../src'; -import {NoRecordRootSpan} from '../src/trace/model/no-record/no-record-root-span'; +import { + CanonicalCode, + CoreTracer, + LinkType, + MessageEventType, + SpanKind, +} from '../src'; +import { NoRecordRootSpan } from '../src/trace/model/no-record/no-record-root-span'; const tracer = new CoreTracer(); describe('NoRecordRootSpan()', () => { it('do not crash', () => { - const noRecordRootSpan = - new NoRecordRootSpan(tracer, 'name', SpanKind.SERVER, 'traceid', ''); + const noRecordRootSpan = new NoRecordRootSpan( + tracer, + 'name', + SpanKind.SERVER, + 'traceid', + '' + ); noRecordRootSpan.addAnnotation('MyAnnotation'); - noRecordRootSpan.addAnnotation('MyAnnotation', {myString: 'bar'}); - noRecordRootSpan.addAnnotation( - 'MyAnnotation', {myString: 'bar', myNumber: 123, myBoolean: true}); + noRecordRootSpan.addAnnotation('MyAnnotation', { myString: 'bar' }); + noRecordRootSpan.addAnnotation('MyAnnotation', { + myString: 'bar', + myNumber: 123, + myBoolean: true, + }); noRecordRootSpan.addLink('aaaaa', 'aaa', LinkType.CHILD_LINKED_SPAN); noRecordRootSpan.addMessageEvent(MessageEventType.RECEIVED, 1, 123456789); noRecordRootSpan.addAttribute('my_first_attribute', 'foo'); diff --git a/packages/opencensus-core/test/test-no-record-span.ts b/packages/opencensus-core/test/test-no-record-span.ts index e91608e48..0e63aa480 100644 --- a/packages/opencensus-core/test/test-no-record-span.ts +++ b/packages/opencensus-core/test/test-no-record-span.ts @@ -15,16 +15,19 @@ */ import * as assert from 'assert'; -import {CanonicalCode, LinkType, MessageEventType} from '../src'; -import {NoRecordSpan} from '../src/trace/model/no-record/no-record-span'; +import { CanonicalCode, LinkType, MessageEventType } from '../src'; +import { NoRecordSpan } from '../src/trace/model/no-record/no-record-span'; describe('NoRecordSpan()', () => { it('do not crash', () => { const noRecordSpan = new NoRecordSpan(); noRecordSpan.addAnnotation('MyAnnotation'); - noRecordSpan.addAnnotation('MyAnnotation', {myString: 'bar'}); - noRecordSpan.addAnnotation( - 'MyAnnotation', {myString: 'bar', myNumber: 123, myBoolean: true}); + noRecordSpan.addAnnotation('MyAnnotation', { myString: 'bar' }); + noRecordSpan.addAnnotation('MyAnnotation', { + myString: 'bar', + myNumber: 123, + myBoolean: true, + }); noRecordSpan.addLink('aaaaa', 'aaa', LinkType.CHILD_LINKED_SPAN); noRecordSpan.addMessageEvent(MessageEventType.RECEIVED, 1, 123456789); noRecordSpan.addAttribute('my_first_attribute', 'foo'); diff --git a/packages/opencensus-core/test/test-recorder.ts b/packages/opencensus-core/test/test-recorder.ts index 22022ae56..a078c5d74 100644 --- a/packages/opencensus-core/test/test-recorder.ts +++ b/packages/opencensus-core/test/test-recorder.ts @@ -15,8 +15,18 @@ */ import * as assert from 'assert'; -import {Recorder, TagMap, TagTtl} from '../src'; -import {AggregationType, CountData, DistributionData, LastValueData, Measure, Measurement, MeasureType, MeasureUnit, SumData} from '../src/stats/types'; +import { Recorder, TagMap, TagTtl } from '../src'; +import { + AggregationType, + CountData, + DistributionData, + LastValueData, + Measure, + Measurement, + MeasureType, + MeasureUnit, + SumData, +} from '../src/stats/types'; /** The order of how close values must be to be considerated almost equal */ const EPSILON = 6; @@ -27,12 +37,17 @@ interface RecorderTestCase { } function isAlmostEqual( - actual: number, expected: number, epsilon: number): boolean { + actual: number, + expected: number, + epsilon: number +): boolean { return Math.abs(actual - expected) < Math.pow(10, -epsilon); } function assertDistributionData( - distributionData: DistributionData, values: number[]) { + distributionData: DistributionData, + values: number[] +) { const valuesSum = values.reduce((acc, cur) => acc + cur); assert.strictEqual(distributionData.count, values.length); @@ -41,143 +56,165 @@ function assertDistributionData( const expectedMean = valuesSum / values.length; assert.ok(isAlmostEqual(distributionData.mean, expectedMean, EPSILON)); - const expectedSumSquaredDeviations = - values.map(value => Math.pow(value - expectedMean, 2)) - .reduce((acc, curr) => acc + curr); - assert.ok(isAlmostEqual( - distributionData.sumOfSquaredDeviation, expectedSumSquaredDeviations, - EPSILON)); + const expectedSumSquaredDeviations = values + .map(value => Math.pow(value - expectedMean, 2)) + .reduce((acc, curr) => acc + curr); + assert.ok( + isAlmostEqual( + distributionData.sumOfSquaredDeviation, + expectedSumSquaredDeviations, + EPSILON + ) + ); - const expectedStdDeviation = - Math.sqrt(expectedSumSquaredDeviations / values.length); - assert.ok(isAlmostEqual( - distributionData.stdDeviation, expectedStdDeviation, EPSILON)); + const expectedStdDeviation = Math.sqrt( + expectedSumSquaredDeviations / values.length + ); + assert.ok( + isAlmostEqual(distributionData.stdDeviation, expectedStdDeviation, EPSILON) + ); } describe('Recorder', () => { const measures: Measure[] = [ - {name: 'Test Measure 1', type: MeasureType.DOUBLE, unit: MeasureUnit.UNIT}, - {name: 'Test Measure 2', type: MeasureType.INT64, unit: MeasureUnit.UNIT} + { + name: 'Test Measure 1', + type: MeasureType.DOUBLE, + unit: MeasureUnit.UNIT, + }, + { name: 'Test Measure 2', type: MeasureType.INT64, unit: MeasureUnit.UNIT }, ]; - const tagValues = [{value: 'testValue'}]; + const tagValues = [{ value: 'testValue' }]; const testCases: RecorderTestCase[] = [ - {values: [1.1, 2.5, 3.2, 4.7, 5.2], description: 'with positive values'}, { + { values: [1.1, 2.5, 3.2, 4.7, 5.2], description: 'with positive values' }, + { values: [-1.5, -2.3, -3.7, -4.3, -5.9], - description: 'with negative values' + description: 'with negative values', }, - {values: [0, 0, 0, 0], description: 'with zeros'}, - {values: [1.1, -2.3, 3.2, -4.3, 5.2], description: 'with mixed values'} + { values: [0, 0, 0, 0], description: 'with zeros' }, + { values: [1.1, -2.3, 3.2, -4.3, 5.2], description: 'with mixed values' }, ]; for (const measure of measures) { describe(`for count aggregation data of ${measure.type} values`, () => { for (const testCase of testCases) { - it(`should record measurements ${testCase.description} correctly`, - () => { - const countData: CountData = { - type: AggregationType.COUNT, - tagValues, - timestamp: Date.now(), - value: 0 - }; - let count = 0; - for (const value of testCase.values) { - count++; - const measurement: Measurement = {measure, value}; - const updatedAggregationData = - Recorder.addMeasurement(countData, measurement) as CountData; + it(`should record measurements ${ + testCase.description + } correctly`, () => { + const countData: CountData = { + type: AggregationType.COUNT, + tagValues, + timestamp: Date.now(), + value: 0, + }; + let count = 0; + for (const value of testCase.values) { + count++; + const measurement: Measurement = { measure, value }; + const updatedAggregationData = Recorder.addMeasurement( + countData, + measurement + ) as CountData; - assert.strictEqual(updatedAggregationData.value, count); - } - }); + assert.strictEqual(updatedAggregationData.value, count); + } + }); } }); - describe( - `for last value aggregation data of ${measure.type} values`, () => { - for (const testCase of testCases) { - it(`should record measurements ${testCase.description} correctly`, - () => { - const lastValueData: LastValueData = { - type: AggregationType.LAST_VALUE, - tagValues, - timestamp: Date.now(), - value: 0 - }; - for (const value of testCase.values) { - const measurement: Measurement = {measure, value}; - const lastValue = measure.type === MeasureType.DOUBLE ? - value : - Math.trunc(value); + describe(`for last value aggregation data of ${ + measure.type + } values`, () => { + for (const testCase of testCases) { + it(`should record measurements ${ + testCase.description + } correctly`, () => { + const lastValueData: LastValueData = { + type: AggregationType.LAST_VALUE, + tagValues, + timestamp: Date.now(), + value: 0, + }; + for (const value of testCase.values) { + const measurement: Measurement = { measure, value }; + const lastValue = + measure.type === MeasureType.DOUBLE ? value : Math.trunc(value); - const updatedAggregationData = - Recorder.addMeasurement(lastValueData, measurement) as - LastValueData; - assert.strictEqual(updatedAggregationData.value, lastValue); - } - }); + const updatedAggregationData = Recorder.addMeasurement( + lastValueData, + measurement + ) as LastValueData; + assert.strictEqual(updatedAggregationData.value, lastValue); } }); + } + }); describe(`for sum aggregation data of ${measure.type} values`, () => { for (const testCase of testCases) { - it(`should record measurements ${testCase.description} correctly`, - () => { - const sumData: SumData = { - type: AggregationType.SUM, - tagValues, - timestamp: Date.now(), - value: 0 - }; - let acc = 0; - for (const value of testCase.values) { - acc += measure.type === MeasureType.DOUBLE ? value : - Math.trunc(value); - const measurement: Measurement = {measure, value}; - const updatedAggregationData = - Recorder.addMeasurement(sumData, measurement) as SumData; + it(`should record measurements ${ + testCase.description + } correctly`, () => { + const sumData: SumData = { + type: AggregationType.SUM, + tagValues, + timestamp: Date.now(), + value: 0, + }; + let acc = 0; + for (const value of testCase.values) { + acc += + measure.type === MeasureType.DOUBLE ? value : Math.trunc(value); + const measurement: Measurement = { measure, value }; + const updatedAggregationData = Recorder.addMeasurement( + sumData, + measurement + ) as SumData; - assert.strictEqual(updatedAggregationData.value, acc); - } - }); + assert.strictEqual(updatedAggregationData.value, acc); + } + }); } }); - describe( - `for distribution aggregation data of ${measure.type} values`, () => { - for (const testCase of testCases) { - it(`should record measurements ${testCase.description} correctly`, - () => { - const distributionData: DistributionData = { - type: AggregationType.DISTRIBUTION, - tagValues, - timestamp: Date.now(), - startTime: Date.now(), - count: 0, - sum: 0, - mean: 0, - stdDeviation: 0, - sumOfSquaredDeviation: 0, - buckets: [2, 4, 6], - bucketCounts: [0, 0, 0, 0] - }; - const sentValues = []; - for (const value of testCase.values) { - sentValues.push( - measure.type === MeasureType.DOUBLE ? value : - Math.trunc(value)); - const measurement: Measurement = {measure, value}; - const updatedAggregationData = - Recorder.addMeasurement(distributionData, measurement) as - DistributionData; - assertDistributionData(updatedAggregationData, sentValues); - } - }); + describe(`for distribution aggregation data of ${ + measure.type + } values`, () => { + for (const testCase of testCases) { + it(`should record measurements ${ + testCase.description + } correctly`, () => { + const distributionData: DistributionData = { + type: AggregationType.DISTRIBUTION, + tagValues, + timestamp: Date.now(), + startTime: Date.now(), + count: 0, + sum: 0, + mean: 0, + stdDeviation: 0, + sumOfSquaredDeviation: 0, + buckets: [2, 4, 6], + bucketCounts: [0, 0, 0, 0], + }; + const sentValues = []; + for (const value of testCase.values) { + sentValues.push( + measure.type === MeasureType.DOUBLE ? value : Math.trunc(value) + ); + const measurement: Measurement = { measure, value }; + const updatedAggregationData = Recorder.addMeasurement( + distributionData, + measurement + ) as DistributionData; + assertDistributionData(updatedAggregationData, sentValues); } }); + } + }); describe('for distribution aggregation data with attachments', () => { - const attachments = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}; + const attachments = { k1: 'v1', k2: 'v2', k3: 'v3' }; it('should record measurements and attachments correctly', () => { const distributionData: DistributionData = { type: AggregationType.DISTRIBUTION, @@ -191,13 +228,15 @@ describe('Recorder', () => { sumOfSquaredDeviation: 0, buckets: [2, 4, 6], bucketCounts: [0, 0, 0, 0], - exemplars: new Array(4) + exemplars: new Array(4), }; const value = 5; - const measurement: Measurement = {measure, value}; - const aggregationData = - Recorder.addMeasurement( - distributionData, measurement, attachments) as DistributionData; + const measurement: Measurement = { measure, value }; + const aggregationData = Recorder.addMeasurement( + distributionData, + measurement, + attachments + ) as DistributionData; assert.strictEqual(aggregationData.sum, 5); assert.strictEqual(aggregationData.mean, 5); @@ -205,22 +244,24 @@ describe('Recorder', () => { assert.deepStrictEqual(aggregationData.bucketCounts, [0, 0, 1, 0]); assert.deepStrictEqual(aggregationData.exemplars![0], undefined); assert.deepStrictEqual(aggregationData.exemplars![1], undefined); - assert.deepStrictEqual( - aggregationData!.exemplars![2], - {value: 5, timestamp: aggregationData.timestamp, attachments}); + assert.deepStrictEqual(aggregationData!.exemplars![2], { + value: 5, + timestamp: aggregationData.timestamp, + attachments, + }); assert.deepStrictEqual(aggregationData.exemplars![3], undefined); }); }); describe('getTagValues()', () => { - const CALLER = {name: 'caller'}; - const METHOD = {name: 'method'}; - const ORIGINATOR = {name: 'originator'}; - const CALLER_V = {value: 'some caller'}; - const METHOD_V = {value: 'some method'}; - const ORIGINATOR_V = {value: 'some originator'}; - const NO_PROPAGATION_MD = {tagTtl: TagTtl.NO_PROPAGATION}; - const UNLIMITED_PROPAGATION_MD = {tagTtl: TagTtl.UNLIMITED_PROPAGATION}; + const CALLER = { name: 'caller' }; + const METHOD = { name: 'method' }; + const ORIGINATOR = { name: 'originator' }; + const CALLER_V = { value: 'some caller' }; + const METHOD_V = { value: 'some method' }; + const ORIGINATOR_V = { value: 'some originator' }; + const NO_PROPAGATION_MD = { tagTtl: TagTtl.NO_PROPAGATION }; + const UNLIMITED_PROPAGATION_MD = { tagTtl: TagTtl.UNLIMITED_PROPAGATION }; let tagMap: TagMap; beforeEach(() => { @@ -236,36 +277,33 @@ describe('Recorder', () => { assert.deepStrictEqual(tagValues, [CALLER_V, METHOD_V]); }); - it('should return tag values from tags and columns when using metadata', - () => { - const columns = [CALLER, METHOD]; - tagMap.set(CALLER, CALLER_V, NO_PROPAGATION_MD); - tagMap.set(METHOD, METHOD_V, UNLIMITED_PROPAGATION_MD); - const tagValues = Recorder.getTagValues(tagMap.tags, columns); - assert.strictEqual(tagValues.length, 2); - assert.deepStrictEqual(tagValues, [CALLER_V, METHOD_V]); - }); + it('should return tag values from tags and columns when using metadata', () => { + const columns = [CALLER, METHOD]; + tagMap.set(CALLER, CALLER_V, NO_PROPAGATION_MD); + tagMap.set(METHOD, METHOD_V, UNLIMITED_PROPAGATION_MD); + const tagValues = Recorder.getTagValues(tagMap.tags, columns); + assert.strictEqual(tagValues.length, 2); + assert.deepStrictEqual(tagValues, [CALLER_V, METHOD_V]); + }); - it('should return tag values from tags and columns with extra keys', - () => { - const columns = [CALLER, METHOD, ORIGINATOR]; - tagMap.set(CALLER, CALLER_V); - tagMap.set(METHOD, METHOD_V); - const tagValues = Recorder.getTagValues(tagMap.tags, columns); - assert.strictEqual(tagValues.length, 3); - assert.deepStrictEqual(tagValues, [CALLER_V, METHOD_V, null]); - }); + it('should return tag values from tags and columns with extra keys', () => { + const columns = [CALLER, METHOD, ORIGINATOR]; + tagMap.set(CALLER, CALLER_V); + tagMap.set(METHOD, METHOD_V); + const tagValues = Recorder.getTagValues(tagMap.tags, columns); + assert.strictEqual(tagValues.length, 3); + assert.deepStrictEqual(tagValues, [CALLER_V, METHOD_V, null]); + }); - it('should return tag values from tags and columns with extra tags', - () => { - const columns = [CALLER, METHOD]; - tagMap.set(CALLER, CALLER_V); - tagMap.set(METHOD, METHOD_V); - tagMap.set(ORIGINATOR, ORIGINATOR_V); - const tagValues = Recorder.getTagValues(tagMap.tags, columns); - assert.strictEqual(tagValues.length, 2); - assert.deepStrictEqual(tagValues, [CALLER_V, METHOD_V]); - }); + it('should return tag values from tags and columns with extra tags', () => { + const columns = [CALLER, METHOD]; + tagMap.set(CALLER, CALLER_V); + tagMap.set(METHOD, METHOD_V); + tagMap.set(ORIGINATOR, ORIGINATOR_V); + const tagValues = Recorder.getTagValues(tagMap.tags, columns); + assert.strictEqual(tagValues.length, 2); + assert.deepStrictEqual(tagValues, [CALLER_V, METHOD_V]); + }); }); } }); diff --git a/packages/opencensus-core/test/test-resource.ts b/packages/opencensus-core/test/test-resource.ts index 812cb99e1..86007c7df 100644 --- a/packages/opencensus-core/test/test-resource.ts +++ b/packages/opencensus-core/test/test-resource.ts @@ -16,14 +16,14 @@ import * as assert from 'assert'; -import {CoreResource} from '../src/resource/resource'; -import {Labels, Resource} from '../src/resource/types'; +import { CoreResource } from '../src/resource/resource'; +import { Labels, Resource } from '../src/resource/types'; describe('Resource()', () => { before(() => { process.env.OC_RESOURCE_TYPE = 'k8s.io/container'; process.env.OC_RESOURCE_LABELS = - 'k8s.io/pod/name="pod-xyz-123",k8s.io/container/name="c1",k8s.io/namespace/name="default"'; + 'k8s.io/pod/name="pod-xyz-123",k8s.io/container/name="c1",k8s.io/namespace/name="default"'; CoreResource.setup(); }); @@ -38,7 +38,7 @@ describe('Resource()', () => { const expectedLabels: Labels = { 'k8s.io/container/name': '"c1"', 'k8s.io/namespace/name': '"default"', - 'k8s.io/pod/name': '"pod-xyz-123"' + 'k8s.io/pod/name': '"pod-xyz-123"', }; assert.strictEqual(resource.type, 'k8s.io/container'); @@ -48,16 +48,21 @@ describe('Resource()', () => { }); describe('mergeResources()', () => { - const DEFAULT_RESOURCE: Resource = {type: null, labels: {}}; - const DEFAULT_RESOURCE_1: Resource = {type: 'default', labels: {'a': '100'}}; - const RESOURCE_1: Resource = {type: 't1', labels: {'a': '1', 'b': '2'}}; - const RESOURCE_2: - Resource = {type: 't2', labels: {'a': '1', 'b': '3', 'c': '4'}}; + const DEFAULT_RESOURCE: Resource = { type: null, labels: {} }; + const DEFAULT_RESOURCE_1: Resource = { + type: 'default', + labels: { a: '100' }, + }; + const RESOURCE_1: Resource = { type: 't1', labels: { a: '1', b: '2' } }; + const RESOURCE_2: Resource = { + type: 't2', + labels: { a: '1', b: '3', c: '4' }, + }; it('merge resources with default, resource1', () => { const resources: Resource[] = [DEFAULT_RESOURCE, RESOURCE_1]; const resource = CoreResource.mergeResources(resources); - const expectedLabels: Labels = {'a': '1', 'b': '2'}; + const expectedLabels: Labels = { a: '1', b: '2' }; assert.strictEqual(resource.type, 't1'); assert.strictEqual(Object.keys(resource.labels).length, 2); @@ -65,10 +70,13 @@ describe('mergeResources()', () => { }); it('merge resources with default, resource1, resource2 = empty', () => { - const resources: Resource[] = - [DEFAULT_RESOURCE, RESOURCE_1, {type: null, labels: {}}]; + const resources: Resource[] = [ + DEFAULT_RESOURCE, + RESOURCE_1, + { type: null, labels: {} }, + ]; const resource = CoreResource.mergeResources(resources); - const expectedLabels: Labels = {'a': '1', 'b': '2'}; + const expectedLabels: Labels = { a: '1', b: '2' }; assert.strictEqual(resource.type, 't1'); assert.strictEqual(Object.keys(resource.labels).length, 2); @@ -76,10 +84,13 @@ describe('mergeResources()', () => { }); it('merge resources with default, resource1 = empty, resource2', () => { - const resources: Resource[] = - [DEFAULT_RESOURCE, {type: null, labels: {}}, RESOURCE_2]; + const resources: Resource[] = [ + DEFAULT_RESOURCE, + { type: null, labels: {} }, + RESOURCE_2, + ]; const resource = CoreResource.mergeResources(resources); - const expectedLabels: Labels = {'a': '1', 'b': '3', 'c': '4'}; + const expectedLabels: Labels = { a: '1', b: '3', c: '4' }; assert.strictEqual(resource.type, 't2'); assert.strictEqual(Object.keys(resource.labels).length, 3); @@ -89,7 +100,7 @@ describe('mergeResources()', () => { it('merge resources with default1, resource1, resource2', () => { const resources: Resource[] = [DEFAULT_RESOURCE_1, RESOURCE_1, RESOURCE_2]; const resource = CoreResource.mergeResources(resources); - const expectedLabels: Labels = {'a': '100', 'b': '2', 'c': '4'}; + const expectedLabels: Labels = { a: '100', b: '2', c: '4' }; assert.strictEqual(resource.type, 'default'); assert.strictEqual(Object.keys(resource.labels).length, 3); diff --git a/packages/opencensus-core/test/test-root-span.ts b/packages/opencensus-core/test/test-root-span.ts index 79efae877..9ebba2c5f 100644 --- a/packages/opencensus-core/test/test-root-span.ts +++ b/packages/opencensus-core/test/test-root-span.ts @@ -15,12 +15,12 @@ */ import * as assert from 'assert'; -import {NoRecordSpan} from '../src/trace/model/no-record/no-record-span'; -import {RootSpan} from '../src/trace/model/root-span'; -import {Span} from '../src/trace/model/span'; -import {CoreTracer} from '../src/trace/model/tracer'; +import { NoRecordSpan } from '../src/trace/model/no-record/no-record-span'; +import { RootSpan } from '../src/trace/model/root-span'; +import { Span } from '../src/trace/model/span'; +import { CoreTracer } from '../src/trace/model/tracer'; import * as types from '../src/trace/model/types'; -import {Annotation, Link} from '../src/trace/model/types'; +import { Annotation, Link } from '../src/trace/model/types'; const tracer = new CoreTracer(); @@ -47,8 +47,10 @@ describe('RootSpan', () => { it('should get span list from rootspan instance', () => { const root = new RootSpan(tracer, name, kind, traceId, ''); root.start(); - const span = - root.startChildSpan({name: 'spanName', kind: types.SpanKind.CLIENT}); + const span = root.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.CLIENT, + }); assert.strictEqual(root.spans.length, 1); assert.strictEqual(span, root.spans[0]); @@ -66,12 +68,17 @@ describe('RootSpan', () => { const root = new RootSpan(tracer, name, kind, traceId, parentSpanId); root.start(); assert.strictEqual(root.numberOfChildren, 0); - root.startChildSpan({name: 'spanName', kind: types.SpanKind.UNSPECIFIED}); + root.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.UNSPECIFIED, + }); assert.strictEqual(root.numberOfChildren, 1); for (let i = 0; i < 10; i++) { - root.startChildSpan( - {name: 'spanName' + i, kind: types.SpanKind.UNSPECIFIED}); + root.startChildSpan({ + name: 'spanName' + i, + kind: types.SpanKind.UNSPECIFIED, + }); } assert.strictEqual(root.numberOfChildren, 11); }); @@ -82,12 +89,16 @@ describe('RootSpan', () => { const root = new RootSpan(tracer, name, kind, traceId, parentSpanId); root.start(); assert.strictEqual(root.numberOfChildren, 0); - const child1 = root.startChildSpan( - {name: 'child1', kind: types.SpanKind.UNSPECIFIED}); + const child1 = root.startChildSpan({ + name: 'child1', + kind: types.SpanKind.UNSPECIFIED, + }); assert.strictEqual(root.numberOfChildren, 1); assert.strictEqual(child1.numberOfChildren, 0); - const child2 = root.startChildSpan( - {name: 'child2', kind: types.SpanKind.UNSPECIFIED}); + const child2 = root.startChildSpan({ + name: 'child2', + kind: types.SpanKind.UNSPECIFIED, + }); assert.strictEqual(root.numberOfChildren, 2); const grandchild1 = child1.startChildSpan({ name: 'grandchild1', @@ -122,8 +133,10 @@ describe('RootSpan', () => { root.start(); assert.strictEqual(root.traceId, root.spanContext.traceId); - const child = root.startChildSpan( - {name: 'child', kind: types.SpanKind.UNSPECIFIED}); + const child = root.startChildSpan({ + name: 'child', + kind: types.SpanKind.UNSPECIFIED, + }); assert.strictEqual(root.traceId, child.traceId); }); }); @@ -148,8 +161,10 @@ describe('RootSpan', () => { before(() => { root = new RootSpan(tracer, name, kind, traceId, parentSpanId); root.start(); - span = root.startChildSpan( - {name: 'spanName', kind: types.SpanKind.UNSPECIFIED}); + span = root.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.UNSPECIFIED, + }); }); it('should create span instance', () => { @@ -167,8 +182,10 @@ describe('RootSpan', () => { describe('startSpan() before start rootspan', () => { it('should create NoRecordSpan', () => { const root = new RootSpan(tracer, name, kind, traceId, parentSpanId); - const span = root.startChildSpan( - {name: 'spanName', kind: types.SpanKind.UNSPECIFIED}); + const span = root.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.UNSPECIFIED, + }); assert.ok(span instanceof NoRecordSpan); }); }); @@ -181,8 +198,10 @@ describe('RootSpan', () => { const root = new RootSpan(tracer, name, kind, traceId, parentSpanId); root.start(); root.end(); - const span = root.startChildSpan( - {name: 'spanName', kind: types.SpanKind.UNSPECIFIED}); + const span = root.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.UNSPECIFIED, + }); assert.ok(span instanceof NoRecordSpan); }); }); @@ -217,10 +236,14 @@ describe('RootSpan', () => { it('should end all spans inside rootspan', () => { const root = new RootSpan(tracer, name, kind, traceId, parentSpanId); root.start(); - const child = root.startChildSpan( - {name: 'child', kind: types.SpanKind.UNSPECIFIED}); - child.startChildSpan( - {name: 'grandchild', kind: types.SpanKind.UNSPECIFIED}); + const child = root.startChildSpan({ + name: 'child', + kind: types.SpanKind.UNSPECIFIED, + }); + child.startChildSpan({ + name: 'grandchild', + kind: types.SpanKind.UNSPECIFIED, + }); root.end(); for (const span of root.allDescendants()) { @@ -229,7 +252,6 @@ describe('RootSpan', () => { }); }); - /** * Should add an attrinbutes */ @@ -241,7 +263,9 @@ describe('RootSpan', () => { ['String', 'Number', 'Boolean'].map(attType => { rootSpan.addAttribute('testKey' + attType, 'testValue' + attType); assert.strictEqual( - rootSpan.attributes['testKey' + attType], 'testValue' + attType); + rootSpan.attributes['testKey' + attType], + 'testValue' + attType + ); }); }); }); @@ -253,8 +277,11 @@ describe('RootSpan', () => { it('should add an annotation', () => { // tslint:disable:no-any function instanceOfAnnotation(object: any): object is Annotation { - return 'description' in object && 'timestamp' in object && - 'attributes' in object; + return ( + 'description' in object && + 'timestamp' in object && + 'attributes' in object + ); } const rootSpan = new RootSpan(tracer, name, kind, traceId, parentSpanId); @@ -275,7 +302,9 @@ describe('RootSpan', () => { assert.ok(rootSpan.annotations.length > 0); assert.strictEqual(rootSpan.droppedAnnotationsCount, 0); assert.strictEqual( - rootSpan.annotations[0].description, 'description test'); + rootSpan.annotations[0].description, + 'description test' + ); assert.deepStrictEqual(rootSpan.annotations[0].attributes, {}); assert.ok(rootSpan.annotations[0].timestamp > 0); }); @@ -298,7 +327,10 @@ describe('RootSpan', () => { span.start(); rootSpan.addLink( - rootSpan.traceId, span.id, types.LinkType.CHILD_LINKED_SPAN); + rootSpan.traceId, + span.id, + types.LinkType.CHILD_LINKED_SPAN + ); assert.ok(rootSpan.links.length > 0); assert.strictEqual(rootSpan.droppedLinksCount, 0); @@ -334,8 +366,14 @@ describe('RootSpan', () => { }); it('should create a RootSpan instance with traceState', () => { - const root = - new RootSpan(tracer, name, kind, traceId, parentSpanId, 'traceState'); + const root = new RootSpan( + tracer, + name, + kind, + traceId, + parentSpanId, + 'traceState' + ); assert.ok(root instanceof RootSpan); assert.strictEqual(root.traceState, 'traceState'); }); diff --git a/packages/opencensus-core/test/test-sampler.ts b/packages/opencensus-core/test/test-sampler.ts index 736596120..85d4ccdd3 100644 --- a/packages/opencensus-core/test/test-sampler.ts +++ b/packages/opencensus-core/test/test-sampler.ts @@ -15,11 +15,14 @@ */ import * as assert from 'assert'; -import {SpanKind} from '../src'; -import {TraceParams} from '../src/trace/config/types'; -import {RootSpan} from '../src/trace/model/root-span'; -import {CoreTracer} from '../src/trace/model/tracer'; -import {SamplerBuilder, TraceParamsBuilder} from '../src/trace/sampler/sampler'; +import { SpanKind } from '../src'; +import { TraceParams } from '../src/trace/config/types'; +import { RootSpan } from '../src/trace/model/root-span'; +import { CoreTracer } from '../src/trace/model/tracer'; +import { + SamplerBuilder, + TraceParamsBuilder, +} from '../src/trace/sampler/sampler'; const tracer = new CoreTracer(); @@ -27,7 +30,7 @@ const traceParameters: TraceParams = { numberOfAnnontationEventsPerSpan: 12, numberOfAttributesPerSpan: 10, numberOfLinksPerSpan: 7, - numberOfMessageEventsPerSpan: 5 + numberOfMessageEventsPerSpan: 5, }; describe('Sampler', () => { @@ -80,60 +83,66 @@ describe('Sampler', () => { const sampler = SamplerBuilder.getSampler(0.7); assert.ok(sampler.description.indexOf('probability') >= 0); }); - it('should accept and reject traces based on last 26 bytes of traceId', - () => { - const sampler = SamplerBuilder.getSampler(0.5); + it('should accept and reject traces based on last 26 bytes of traceId', () => { + const sampler = SamplerBuilder.getSampler(0.5); - const shouldSample = [ - '11111111111111111110000000000000', - '1111111111111111111000ffffffffff', - '11111111111111111117ffffffffffff', - ]; - shouldSample.forEach(traceId => { - const samplerShouldSample = sampler.shouldSample(traceId); - assert.ok( - samplerShouldSample, - `should have sampled but didn't: ${traceId}`); - }); + const shouldSample = [ + '11111111111111111110000000000000', + '1111111111111111111000ffffffffff', + '11111111111111111117ffffffffffff', + ]; + shouldSample.forEach(traceId => { + const samplerShouldSample = sampler.shouldSample(traceId); + assert.ok( + samplerShouldSample, + `should have sampled but didn't: ${traceId}` + ); + }); - const shouldNotSample = [ - '11111111111111111118000000000000', - '11111111111111111118000fffffffff', - '1111111111111111111fffffffffffff', - ]; - shouldNotSample.forEach(traceId => { - const samplerShouldSample = sampler.shouldSample(traceId); - assert.ok( - !samplerShouldSample, - `should not have sampled but did: ${traceId}`); - }); - }); + const shouldNotSample = [ + '11111111111111111118000000000000', + '11111111111111111118000fffffffff', + '1111111111111111111fffffffffffff', + ]; + shouldNotSample.forEach(traceId => { + const samplerShouldSample = sampler.shouldSample(traceId); + assert.ok( + !samplerShouldSample, + `should not have sampled but did: ${traceId}` + ); + }); + }); }); describe('getNumberOfAnnotationEventsPerSpan', () => { it('should return 12', () => { assert.strictEqual( - TraceParamsBuilder.getNumberOfAnnotationEventsPerSpan( - traceParameters), - 12); + TraceParamsBuilder.getNumberOfAnnotationEventsPerSpan(traceParameters), + 12 + ); }); }); describe('getNumberOfMessageEventsPerSpan', () => { it('should return 5', () => { assert.strictEqual( - TraceParamsBuilder.getNumberOfMessageEventsPerSpan(traceParameters), - 5); + TraceParamsBuilder.getNumberOfMessageEventsPerSpan(traceParameters), + 5 + ); }); }); describe('getNumberOfAttributesPerSpan', () => { it('should return 10', () => { assert.strictEqual( - TraceParamsBuilder.getNumberOfAttributesPerSpan(traceParameters), 10); + TraceParamsBuilder.getNumberOfAttributesPerSpan(traceParameters), + 10 + ); }); }); describe('getNumberOfLinksPerSpan', () => { it('should return 7', () => { assert.strictEqual( - TraceParamsBuilder.getNumberOfLinksPerSpan(traceParameters), 7); + TraceParamsBuilder.getNumberOfLinksPerSpan(traceParameters), + 7 + ); }); }); }); diff --git a/packages/opencensus-core/test/test-span.ts b/packages/opencensus-core/test/test-span.ts index 593b3500d..74388c2f4 100644 --- a/packages/opencensus-core/test/test-span.ts +++ b/packages/opencensus-core/test/test-span.ts @@ -15,11 +15,11 @@ */ import * as assert from 'assert'; -import {RootSpan} from '../src/trace/model/root-span'; -import {Span} from '../src/trace/model/span'; -import {CoreTracer} from '../src/trace/model/tracer'; +import { RootSpan } from '../src/trace/model/root-span'; +import { Span } from '../src/trace/model/span'; +import { CoreTracer } from '../src/trace/model/tracer'; import * as types from '../src/trace/model/types'; -import {Annotation, Link} from '../src/trace/model/types'; +import { Annotation, Link } from '../src/trace/model/types'; // TODO: we should evaluate a way to merge similar test cases between span and // rootspan @@ -29,7 +29,7 @@ tracer.activeTraceParams = { numberOfAttributesPerSpan: 32, numberOfLinksPerSpan: 32, numberOfAnnontationEventsPerSpan: 32, - numberOfMessageEventsPerSpan: 32 + numberOfMessageEventsPerSpan: 32, }; describe('Span', () => { @@ -114,33 +114,35 @@ describe('Span', () => { assert.ok(span.started); }); + it('should start a RootSpan and set CurrentRootSpan when parentSpanId is empty', () => { + const rootSpan = new RootSpan(tracer, name, kind, traceId, ''); + rootSpan.start(); + assert.strictEqual(tracer.currentRootSpan, rootSpan); - it('should start a RootSpan and set CurrentRootSpan when parentSpanId is empty', - () => { - const rootSpan = new RootSpan(tracer, name, kind, traceId, ''); - rootSpan.start(); - assert.strictEqual(tracer.currentRootSpan, rootSpan); - - const span = new Span(tracer, rootSpan); - span.start(); - assert.strictEqual(tracer.currentRootSpan, rootSpan); + const span = new Span(tracer, rootSpan); + span.start(); + assert.strictEqual(tracer.currentRootSpan, rootSpan); - assert.ok(span.started); - }); + assert.ok(span.started); + }); - it('should start a RootSpan and set CurrentRootSpan when parentSpanId is not empty', - () => { - const rootSpan = - new RootSpan(tracer, name, kind, traceId, 'd5955a12632d46a1'); - rootSpan.start(); - assert.strictEqual(tracer.currentRootSpan, rootSpan); + it('should start a RootSpan and set CurrentRootSpan when parentSpanId is not empty', () => { + const rootSpan = new RootSpan( + tracer, + name, + kind, + traceId, + 'd5955a12632d46a1' + ); + rootSpan.start(); + assert.strictEqual(tracer.currentRootSpan, rootSpan); - const span = new Span(tracer, rootSpan); - span.start(); - assert.strictEqual(tracer.currentRootSpan, rootSpan); + const span = new Span(tracer, rootSpan); + span.start(); + assert.strictEqual(tracer.currentRootSpan, rootSpan); - assert.ok(span.started); - }); + assert.ok(span.started); + }); }); /** @@ -221,9 +223,11 @@ describe('Span', () => { ['String', 'Number', 'Boolean'].map(attType => { span.addAttribute('testKey' + attType, 'testValue' + attType); assert.strictEqual( - span.attributes['testKey' + attType], 'testValue' + attType); + span.attributes['testKey' + attType], + 'testValue' + attType + ); }); - span.addAttribute('object', {foo: 'bar'}); + span.addAttribute('object', { foo: 'bar' }); assert.strictEqual(span.attributes['object'], '{"foo":"bar"}'); span.addAttribute('array', [1, 2, 3]); assert.strictEqual(span.attributes['array'], '[1,2,3]'); @@ -251,8 +255,11 @@ describe('Span', () => { it('should add an annotation', () => { // tslint:disable:no-any function instanceOfAnnotation(object: any): object is Annotation { - return 'description' in object && 'timestamp' in object && - 'attributes' in object; + return ( + 'description' in object && + 'timestamp' in object && + 'attributes' in object + ); } const rootSpan = new RootSpan(tracer, name, kind, traceId, parentSpanId); @@ -300,7 +307,10 @@ describe('Span', () => { span.start(); span.addLink( - span.traceId, rootSpan.id, types.LinkType.PARENT_LINKED_SPAN); + span.traceId, + rootSpan.id, + types.LinkType.PARENT_LINKED_SPAN + ); assert.ok(span.links.length > 0); assert.strictEqual(span.droppedLinksCount, 0); @@ -315,7 +325,10 @@ describe('Span', () => { for (let i = 0; i < 35; i++) { span.addLink( - span.traceId, rootSpan.id, types.LinkType.PARENT_LINKED_SPAN); + span.traceId, + rootSpan.id, + types.LinkType.PARENT_LINKED_SPAN + ); } assert.strictEqual(span.links.length, 32); @@ -340,18 +353,23 @@ describe('Span', () => { span.start(); span.addMessageEvent( - types.MessageEventType.UNSPECIFIED, /* id */ 1, - /* timestamp */ 1550000000000, /* uncompressedSize */ 55, - /** compressedSize */ 40); + types.MessageEventType.UNSPECIFIED, + /* id */ 1, + /* timestamp */ 1550000000000, + /* uncompressedSize */ 55, + /** compressedSize */ 40 + ); assert.ok(span.messageEvents.length > 0); - assert.deepStrictEqual(span.messageEvents, [{ - type: types.MessageEventType.UNSPECIFIED, - id: 1, - timestamp: 1550000000000, - uncompressedSize: 55, - compressedSize: 40, - }]); + assert.deepStrictEqual(span.messageEvents, [ + { + type: types.MessageEventType.UNSPECIFIED, + id: 1, + timestamp: 1550000000000, + uncompressedSize: 55, + compressedSize: 40, + }, + ]); assert.strictEqual(span.droppedMessageEventsCount, 0); assert.ok(instanceOfLink(span.messageEvents[0])); }); @@ -401,8 +419,14 @@ describe('Span', () => { describe('get traceState()', () => { it('should return the traceState', () => { - const rootSpan = - new RootSpan(tracer, name, kind, traceId, parentSpanId, 'traceState'); + const rootSpan = new RootSpan( + tracer, + name, + kind, + traceId, + parentSpanId, + 'traceState' + ); rootSpan.start(); assert.strictEqual(rootSpan.traceState, 'traceState'); diff --git a/packages/opencensus-core/test/test-stats.ts b/packages/opencensus-core/test/test-stats.ts index 4433caef2..6bc85721b 100644 --- a/packages/opencensus-core/test/test-stats.ts +++ b/packages/opencensus-core/test/test-stats.ts @@ -15,8 +15,23 @@ */ import * as assert from 'assert'; -import {BaseView, globalStats, StatsEventListener, TagKey, TagMap, TagValue} from '../src'; -import {AggregationType, LastValueData, Measure, Measurement, MeasureType, MeasureUnit, View} from '../src/stats/types'; +import { + BaseView, + globalStats, + StatsEventListener, + TagKey, + TagMap, + TagValue, +} from '../src'; +import { + AggregationType, + LastValueData, + Measure, + Measurement, + MeasureType, + MeasureUnit, + View, +} from '../src/stats/types'; import * as tagger from '../src/tags/tagger'; class TestExporter implements StatsEventListener { @@ -28,7 +43,10 @@ class TestExporter implements StatsEventListener { } onRecord( - views: View[], measurement: Measurement, tagMap: Map) { + views: View[], + measurement: Measurement, + tagMap: Map + ) { this.recordedMeasurements.push(measurement); } @@ -50,8 +68,8 @@ describe('Stats', () => { }); const viewName = 'testViewName'; - const tagKeys = [{name: 'testKey1'}, {name: 'testKey2'}]; - const tagValues = [{value: 'testValue1'}, {value: 'testValue2'}]; + const tagKeys = [{ name: 'testKey1' }, { name: 'testKey2' }]; + const tagValues = [{ value: 'testValue1' }, { value: 'testValue2' }]; const tagMap = new TagMap(); tagMap.set(tagKeys[0], tagValues[0]); tagMap.set(tagKeys[1], tagValues[1]); @@ -63,7 +81,10 @@ describe('Stats', () => { describe('createMeasureDouble()', () => { it('should create a measure of type double', () => { const measureDouble = globalStats.createMeasureDouble( - measureName, measureUnit, description); + measureName, + measureUnit, + description + ); assert.strictEqual(measureDouble.type, MeasureType.DOUBLE); assert.strictEqual(measureDouble.name, measureName); assert.strictEqual(measureDouble.unit, measureUnit); @@ -73,8 +94,11 @@ describe('Stats', () => { describe('createMeasureInt64()', () => { it('should create a measure of type int64', () => { - const measureDouble = - globalStats.createMeasureInt64(measureName, measureUnit, description); + const measureDouble = globalStats.createMeasureInt64( + measureName, + measureUnit, + description + ); assert.strictEqual(measureDouble.type, MeasureType.INT64); assert.strictEqual(measureDouble.name, measureName); assert.strictEqual(measureDouble.unit, measureUnit); @@ -84,8 +108,10 @@ describe('Stats', () => { describe('createView()', () => { const aggregationTypes = [ - AggregationType.COUNT, AggregationType.SUM, AggregationType.LAST_VALUE, - AggregationType.DISTRIBUTION + AggregationType.COUNT, + AggregationType.SUM, + AggregationType.LAST_VALUE, + AggregationType.DISTRIBUTION, ]; let measure: Measure; @@ -101,8 +127,13 @@ describe('Stats', () => { it(`should create a view with ${aggregationType} aggregation`, () => { const bucketBoundaries = AggregationType.DISTRIBUTION ? [1, 2, 3] : []; const view = globalStats.createView( - viewName, measure, aggregationType, tagKeys, description, - bucketBoundaries); + viewName, + measure, + aggregationType, + tagKeys, + description, + bucketBoundaries + ); globalStats.registerView(view); assert.strictEqual(view.name, viewName); @@ -114,10 +145,9 @@ describe('Stats', () => { }); } - it('should not create a view with distribution aggregation when no bucket boundaries were given', - () => { - assert.throws(globalStats.createView, 'No bucketBoundaries specified'); - }); + it('should not create a view with distribution aggregation when no bucket boundaries were given', () => { + assert.throws(globalStats.createView, 'No bucketBoundaries specified'); + }); }); describe('registerView()', () => { @@ -132,7 +162,12 @@ describe('Stats', () => { it('should register a view', () => { globalStats.registerExporter(testExporter); const view = new BaseView( - viewName, measure, AggregationType.LAST_VALUE, tagKeys, description); + viewName, + measure, + AggregationType.LAST_VALUE, + tagKeys, + description + ); assert.ok(!view.registered); assert.strictEqual(testExporter.registeredViews.length, 0); @@ -152,7 +187,12 @@ describe('Stats', () => { globalStats.registerExporter(testExporter); const measure = globalStats.createMeasureInt64(measureName, measureUnit); const view = new BaseView( - viewName, measure, AggregationType.LAST_VALUE, tagKeys, description); + viewName, + measure, + AggregationType.LAST_VALUE, + tagKeys, + description + ); globalStats.unregisterExporter(testExporter); globalStats.registerView(view); @@ -172,7 +212,12 @@ describe('Stats', () => { testExporter.clean(); globalStats.registerExporter(testExporter); const view = globalStats.createView( - viewName, measure, AggregationType.LAST_VALUE, tagKeys, description); + viewName, + measure, + AggregationType.LAST_VALUE, + tagKeys, + description + ); globalStats.registerView(view); }); @@ -181,86 +226,100 @@ describe('Stats', () => { }); it('should record a single measurement', () => { - const measurement = {measure, value: 1}; + const measurement = { measure, value: 1 }; assert.strictEqual(testExporter.recordedMeasurements.length, 0); globalStats.record([measurement], tagMap); assert.strictEqual(testExporter.recordedMeasurements.length, 1); assert.deepStrictEqual(testExporter.recordedMeasurements[0], measurement); aggregationData = testExporter.registeredViews[0].getSnapshot( - tagValues) as LastValueData; + tagValues + ) as LastValueData; assert.strictEqual(aggregationData.value, measurement.value); }); it('should not record a single negative measurement', () => { globalStats.registerExporter(testExporter); - const measurement = {measure, value: -1}; + const measurement = { measure, value: -1 }; globalStats.record([measurement], tagMap); assert.strictEqual(testExporter.recordedMeasurements.length, 0); }); it('should record when tagMap is not passed', () => { globalStats.registerExporter(testExporter); - const measurement = {measure, value: 10}; + const measurement = { measure, value: 10 }; globalStats.record([measurement]); assert.strictEqual(testExporter.recordedMeasurements.length, 2); }); it('should record multiple measurements', () => { - const measurement1 = {measure, value: 1}; - const measurement2 = {measure, value: 1}; + const measurement1 = { measure, value: 1 }; + const measurement2 = { measure, value: 1 }; assert.strictEqual(testExporter.recordedMeasurements.length, 0); globalStats.record([measurement1, measurement2], tagMap); assert.strictEqual(testExporter.recordedMeasurements.length, 2); assert.deepStrictEqual( - testExporter.recordedMeasurements[0], measurement1); + testExporter.recordedMeasurements[0], + measurement1 + ); assert.deepStrictEqual( - testExporter.recordedMeasurements[1], measurement2); + testExporter.recordedMeasurements[1], + measurement2 + ); aggregationData = testExporter.registeredViews[0].getSnapshot( - tagValues) as LastValueData; + tagValues + ) as LastValueData; assert.strictEqual(aggregationData.value, measurement2.value); }); - it('should skip whole multiple measurment if one of value is negative', - () => { - const measurments = - [{measure, value: 1}, {measure, value: -1}, {measure, value: 1}]; - globalStats.record(measurments, tagMap); - assert.strictEqual(testExporter.recordedMeasurements.length, 0); - }); + it('should skip whole multiple measurment if one of value is negative', () => { + const measurments = [ + { measure, value: 1 }, + { measure, value: -1 }, + { measure, value: 1 }, + ]; + globalStats.record(measurments, tagMap); + assert.strictEqual(testExporter.recordedMeasurements.length, 0); + }); it('should record against implicit context when set', () => { const tags = new TagMap(); - tags.set(tagKeys[0], {value: 'value1'}); - tags.set(tagKeys[1], {value: 'value2'}); - const measurement = {measure, value: 1}; + tags.set(tagKeys[0], { value: 'value1' }); + tags.set(tagKeys[1], { value: 'value2' }); + const measurement = { measure, value: 1 }; globalStats.withTagContext(tags, () => { globalStats.record([measurement]); }); assert.strictEqual(testExporter.recordedMeasurements.length, 1); assert.deepStrictEqual(testExporter.recordedMeasurements[0], measurement); - aggregationData = - testExporter.registeredViews[0].getSnapshot( - [{value: 'value1'}, {value: 'value2'}]) as LastValueData; + aggregationData = testExporter.registeredViews[0].getSnapshot([ + { value: 'value1' }, + { value: 'value2' }, + ]) as LastValueData; assert.strictEqual(aggregationData.value, measurement.value); - assert.deepStrictEqual( - aggregationData.tagValues, [{value: 'value1'}, {value: 'value2'}]); + assert.deepStrictEqual(aggregationData.tagValues, [ + { value: 'value1' }, + { value: 'value2' }, + ]); }); it('should record against implicit context when not set or empty', () => { - const UNKNOWN_TAG_VALUE: TagValue|null = null; + const UNKNOWN_TAG_VALUE: TagValue | null = null; globalStats.registerExporter(testExporter); - const measurement = {measure, value: 2211}; + const measurement = { measure, value: 2211 }; globalStats.withTagContext(tagger.EMPTY_TAG_MAP, () => { globalStats.record([measurement]); }); - aggregationData = - testExporter.registeredViews[0].getSnapshot( - [UNKNOWN_TAG_VALUE, UNKNOWN_TAG_VALUE]) as LastValueData; + aggregationData = testExporter.registeredViews[0].getSnapshot([ + UNKNOWN_TAG_VALUE, + UNKNOWN_TAG_VALUE, + ]) as LastValueData; assert.strictEqual(aggregationData.value, measurement.value); - assert.deepStrictEqual( - aggregationData.tagValues, [UNKNOWN_TAG_VALUE, UNKNOWN_TAG_VALUE]); + assert.deepStrictEqual(aggregationData.tagValues, [ + UNKNOWN_TAG_VALUE, + UNKNOWN_TAG_VALUE, + ]); }); }); }); diff --git a/packages/opencensus-core/test/test-string-utils.ts b/packages/opencensus-core/test/test-string-utils.ts index fed4ff924..94048ba94 100644 --- a/packages/opencensus-core/test/test-string-utils.ts +++ b/packages/opencensus-core/test/test-string-utils.ts @@ -15,7 +15,7 @@ */ import * as assert from 'assert'; -import {StringUtils} from '../src/internal/string-utils'; +import { StringUtils } from '../src/internal/string-utils'; describe('StringUtils', () => { it('should return true when string is printable', () => { diff --git a/packages/opencensus-core/test/test-tag-map.ts b/packages/opencensus-core/test/test-tag-map.ts index ba2a990c4..b9f44e75e 100644 --- a/packages/opencensus-core/test/test-tag-map.ts +++ b/packages/opencensus-core/test/test-tag-map.ts @@ -15,28 +15,28 @@ */ import * as assert from 'assert'; -import {TagMap} from '../src/tags/tag-map'; -import {TagTtl} from '../src/tags/types'; +import { TagMap } from '../src/tags/tag-map'; +import { TagTtl } from '../src/tags/types'; describe('TagMap()', () => { let tagMap: TagMap; - const key1 = {name: 'key1'}; - const key2 = {name: 'key2'}; - const invalidKey1 = {name: 'a'.repeat(256)}; - const value1 = {value: 'value1'}; - const value2 = {value: 'value2'}; - const invalidValue1 = {value: 'a'.repeat(256)}; - const NO_PROPAGATION_MD = {tagTtl: TagTtl.NO_PROPAGATION}; - const UNLIMITED_PROPAGATION_MD = {tagTtl: TagTtl.UNLIMITED_PROPAGATION}; + const key1 = { name: 'key1' }; + const key2 = { name: 'key2' }; + const invalidKey1 = { name: 'a'.repeat(256) }; + const value1 = { value: 'value1' }; + const value2 = { value: 'value2' }; + const invalidValue1 = { value: 'a'.repeat(256) }; + const NO_PROPAGATION_MD = { tagTtl: TagTtl.NO_PROPAGATION }; + const UNLIMITED_PROPAGATION_MD = { tagTtl: TagTtl.UNLIMITED_PROPAGATION }; const expectedTagValueWithMetadata1 = { - tagValue: {value: 'value1'}, - tagMetadata: {tagTtl: -1} + tagValue: { value: 'value1' }, + tagMetadata: { tagTtl: -1 }, }; const expectedTagValueWithMetadata2 = { - tagValue: {value: 'value2'}, - tagMetadata: {tagTtl: -1} + tagValue: { value: 'value2' }, + tagMetadata: { tagTtl: -1 }, }; beforeEach(() => { @@ -53,8 +53,8 @@ describe('TagMap()', () => { it('should set tagkey and tagvalue with NO_PROPAGATION TagTtl', () => { const expectedTagValueWithMetadata = { - tagValue: {value: 'value1'}, - tagMetadata: {tagTtl: 0} + tagValue: { value: 'value1' }, + tagMetadata: { tagTtl: 0 }, }; tagMap.set(key1, value1, NO_PROPAGATION_MD); @@ -63,18 +63,17 @@ describe('TagMap()', () => { assert.deepStrictEqual(tags.get(key1), expectedTagValueWithMetadata); }); - it('should set tagkey and tagvalue with UNLIMITED_PROPAGATION TagTtl', - () => { - const expectedTagValueWithMetadata = { - tagValue: {value: 'value1'}, - tagMetadata: {tagTtl: -1} - }; + it('should set tagkey and tagvalue with UNLIMITED_PROPAGATION TagTtl', () => { + const expectedTagValueWithMetadata = { + tagValue: { value: 'value1' }, + tagMetadata: { tagTtl: -1 }, + }; - tagMap.set(key1, value1, UNLIMITED_PROPAGATION_MD); - const tags = tagMap.tagsWithMetadata; - assert.strictEqual(tags.size, 1); - assert.deepStrictEqual(tags.get(key1), expectedTagValueWithMetadata); - }); + tagMap.set(key1, value1, UNLIMITED_PROPAGATION_MD); + const tags = tagMap.tagsWithMetadata; + assert.strictEqual(tags.size, 1); + assert.deepStrictEqual(tags.get(key1), expectedTagValueWithMetadata); + }); it('should throw an error when invalid tagKey', () => { assert.throws(() => { diff --git a/packages/opencensus-core/test/test-tagger.ts b/packages/opencensus-core/test/test-tagger.ts index ebcd756dc..235104fd3 100644 --- a/packages/opencensus-core/test/test-tagger.ts +++ b/packages/opencensus-core/test/test-tagger.ts @@ -15,7 +15,7 @@ */ import * as assert from 'assert'; -import {TagMap} from '../src'; +import { TagMap } from '../src'; import * as cls from '../src/internal/cls'; import * as tagger from '../src/tags/tagger'; @@ -23,102 +23,131 @@ const contextManager = cls.getNamespace(); describe('tagger()', () => { const tags1 = new TagMap(); - tags1.set({name: 'key1'}, {value: 'value1'}); - tags1.set({name: 'key2'}, {value: 'value2'}); + tags1.set({ name: 'key1' }, { value: 'value1' }); + tags1.set({ name: 'key2' }, { value: 'value2' }); const tags2 = new TagMap(); - tags2.set({name: 'key3'}, {value: 'value3'}); - tags2.set({name: 'key4'}, {value: 'value4'}); + tags2.set({ name: 'key3' }, { value: 'value3' }); + tags2.set({ name: 'key4' }, { value: 'value4' }); const tags3 = new TagMap(); - tags3.set({name: 'key2'}, {value: 'value3'}); - tags3.set({name: 'key4'}, {value: 'value4'}); + tags3.set({ name: 'key2' }, { value: 'value3' }); + tags3.set({ name: 'key4' }, { value: 'value4' }); const tags4 = new TagMap(); - tags4.set({name: 'key1'}, {value: 'value4'}); - tags4.set({name: 'key4'}, {value: 'value5'}); - tags4.set({name: 'key6'}, {value: 'value6'}); + tags4.set({ name: 'key1' }, { value: 'value4' }); + tags4.set({ name: 'key4' }, { value: 'value5' }); + tags4.set({ name: 'key6' }, { value: 'value6' }); const expectedMergedTags = new TagMap(); - expectedMergedTags.set({name: 'key1'}, {value: 'value1'}); - expectedMergedTags.set({name: 'key2'}, {value: 'value2'}); - expectedMergedTags.set({name: 'key3'}, {value: 'value3'}); - expectedMergedTags.set({name: 'key4'}, {value: 'value4'}); + expectedMergedTags.set({ name: 'key1' }, { value: 'value1' }); + expectedMergedTags.set({ name: 'key2' }, { value: 'value2' }); + expectedMergedTags.set({ name: 'key3' }, { value: 'value3' }); + expectedMergedTags.set({ name: 'key4' }, { value: 'value4' }); const expectedTagsFrom1n3 = new TagMap(); - expectedTagsFrom1n3.set({name: 'key1'}, {value: 'value1'}); - expectedTagsFrom1n3.set({name: 'key2'}, {value: 'value3'}); - expectedTagsFrom1n3.set({name: 'key4'}, {value: 'value4'}); + expectedTagsFrom1n3.set({ name: 'key1' }, { value: 'value1' }); + expectedTagsFrom1n3.set({ name: 'key2' }, { value: 'value3' }); + expectedTagsFrom1n3.set({ name: 'key4' }, { value: 'value4' }); const expectedTagsFrom1n3n4 = new TagMap(); - expectedTagsFrom1n3n4.set({name: 'key1'}, {value: 'value4'}); - expectedTagsFrom1n3n4.set({name: 'key2'}, {value: 'value3'}); - expectedTagsFrom1n3n4.set({name: 'key4'}, {value: 'value5'}); - expectedTagsFrom1n3n4.set({name: 'key6'}, {value: 'value6'}); + expectedTagsFrom1n3n4.set({ name: 'key1' }, { value: 'value4' }); + expectedTagsFrom1n3n4.set({ name: 'key2' }, { value: 'value3' }); + expectedTagsFrom1n3n4.set({ name: 'key4' }, { value: 'value5' }); + expectedTagsFrom1n3n4.set({ name: 'key6' }, { value: 'value6' }); it('should return empty current tag context', () => { tagger.withTagContext(contextManager, tagger.EMPTY_TAG_MAP, () => { assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tagger.EMPTY_TAG_MAP); + tagger.getCurrentTagContext(contextManager), + tagger.EMPTY_TAG_MAP + ); }); }); it('should set current tag context', () => { tagger.withTagContext(contextManager, tags1, () => { assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tags1); + tagger.getCurrentTagContext(contextManager), + tags1 + ); }); assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tagger.EMPTY_TAG_MAP); + tagger.getCurrentTagContext(contextManager), + tagger.EMPTY_TAG_MAP + ); }); it('should set nested current tag context', () => { tagger.withTagContext(contextManager, tags1, () => { assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tags1); + tagger.getCurrentTagContext(contextManager), + tags1 + ); tagger.withTagContext(contextManager, tags2, () => { assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), expectedMergedTags); + tagger.getCurrentTagContext(contextManager), + expectedMergedTags + ); }); assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tags1); + tagger.getCurrentTagContext(contextManager), + tags1 + ); }); assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tagger.EMPTY_TAG_MAP); + tagger.getCurrentTagContext(contextManager), + tagger.EMPTY_TAG_MAP + ); }); it('should resolve tag conflicts', () => { tagger.withTagContext(contextManager, tags1, () => { assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tags1); + tagger.getCurrentTagContext(contextManager), + tags1 + ); tagger.withTagContext(contextManager, tags3, () => { assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), expectedTagsFrom1n3); + tagger.getCurrentTagContext(contextManager), + expectedTagsFrom1n3 + ); tagger.withTagContext(contextManager, tags4, () => { assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), - expectedTagsFrom1n3n4); + tagger.getCurrentTagContext(contextManager), + expectedTagsFrom1n3n4 + ); }); }); assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tags1); + tagger.getCurrentTagContext(contextManager), + tags1 + ); }); assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tagger.EMPTY_TAG_MAP); + tagger.getCurrentTagContext(contextManager), + tagger.EMPTY_TAG_MAP + ); }); it('should clear current tag context', () => { tagger.withTagContext(contextManager, tags1, () => { assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tags1); + tagger.getCurrentTagContext(contextManager), + tags1 + ); tagger.clear(contextManager); assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tagger.EMPTY_TAG_MAP); + tagger.getCurrentTagContext(contextManager), + tagger.EMPTY_TAG_MAP + ); }); assert.deepStrictEqual( - tagger.getCurrentTagContext(contextManager), tagger.EMPTY_TAG_MAP); + tagger.getCurrentTagContext(contextManager), + tagger.EMPTY_TAG_MAP + ); }); }); diff --git a/packages/opencensus-core/test/test-text-format.ts b/packages/opencensus-core/test/test-text-format.ts index 4dfd194a8..4414eff1c 100644 --- a/packages/opencensus-core/test/test-text-format.ts +++ b/packages/opencensus-core/test/test-text-format.ts @@ -15,21 +15,25 @@ */ import * as assert from 'assert'; -import {TagMap, TagTtl} from '../src'; -import {deserializeTextFormat, MAX_NUMBER_OF_TAGS, serializeTextFormat} from '../src/tags/propagation/text-format'; +import { TagMap, TagTtl } from '../src'; +import { + deserializeTextFormat, + MAX_NUMBER_OF_TAGS, + serializeTextFormat, +} from '../src/tags/propagation/text-format'; const K1 = { - name: 'k1' + name: 'k1', }; const K2 = { - name: 'k2' + name: 'k2', }; const V1 = { - value: 'v1' + value: 'v1', }; const V2 = { - value: 'v2' + value: 'v2', }; describe('Text Format Serializer', () => { @@ -42,7 +46,7 @@ describe('Text Format Serializer', () => { multipleTagMap.set(K1, V1); multipleTagMap.set(K2, V2); - const NO_PROPAGATION_MD = {tagTtl: TagTtl.NO_PROPAGATION}; + const NO_PROPAGATION_MD = { tagTtl: TagTtl.NO_PROPAGATION }; const nonPropagatingTagMap = new TagMap(); nonPropagatingTagMap.set(K1, V1, NO_PROPAGATION_MD); @@ -70,7 +74,7 @@ describe('Text Format Serializer', () => { it('should throw an error when exceeds the max number of tags', () => { const tags = new TagMap(); for (let i = 0; i < MAX_NUMBER_OF_TAGS + 1; i++) { - tags.set({name: `name-${i}`}, {value: `value-${i}`}); + tags.set({ name: `name-${i}` }, { value: `value-${i}` }); } assert.throws(() => { @@ -99,8 +103,8 @@ describe('Text Format Serializer', () => { it('should deserialize with white spaces tag', () => { const expectedTagMap = new TagMap(); - expectedTagMap.set(K1, {value: ' v1'}); - expectedTagMap.set({name: ' k2'}, {value: 'v 2'}); + expectedTagMap.set(K1, { value: ' v1' }); + expectedTagMap.set({ name: ' k2' }, { value: 'v 2' }); const deserializedTagMap = deserializeTextFormat('k1= v1, k2=v 2'); assert.deepStrictEqual(deserializedTagMap.tags.size, 2); diff --git a/packages/opencensus-core/test/test-time-util.ts b/packages/opencensus-core/test/test-time-util.ts index 94f67351a..9f47b802b 100644 --- a/packages/opencensus-core/test/test-time-util.ts +++ b/packages/opencensus-core/test/test-time-util.ts @@ -15,7 +15,10 @@ */ import * as assert from 'assert'; -import {getTimestampWithProcessHRTime, TEST_ONLY} from '../src/common/time-util'; +import { + getTimestampWithProcessHRTime, + TEST_ONLY, +} from '../src/common/time-util'; describe('getTimestampWithProcessHRTime()', () => { const realHrtimeFn = process.hrtime; @@ -36,7 +39,7 @@ describe('getTimestampWithProcessHRTime()', () => { const currentTime = getTimestampWithProcessHRTime(); - assert.deepStrictEqual(currentTime, {seconds: 1450000100, nanos: 1e7}); + assert.deepStrictEqual(currentTime, { seconds: 1450000100, nanos: 1e7 }); }); it('should handle excess of nanos', () => { @@ -47,6 +50,6 @@ describe('getTimestampWithProcessHRTime()', () => { const currentTime = getTimestampWithProcessHRTime(); - assert.deepStrictEqual(currentTime, {seconds: 1450000101, nanos: 12}); + assert.deepStrictEqual(currentTime, { seconds: 1450000101, nanos: 12 }); }); }); diff --git a/packages/opencensus-core/test/test-tracer-base.ts b/packages/opencensus-core/test/test-tracer-base.ts index ce63c03ec..021cbf2bb 100644 --- a/packages/opencensus-core/test/test-tracer-base.ts +++ b/packages/opencensus-core/test/test-tracer-base.ts @@ -17,15 +17,15 @@ import * as assert from 'assert'; import * as uuid from 'uuid'; -import {randomSpanId} from '../src/internal/util'; -import {TracerConfig} from '../src/trace/config/types'; -import {TraceParams} from '../src/trace/config/types'; -import {NoRecordRootSpan} from '../src/trace/model/no-record/no-record-root-span'; -import {NoRecordSpan} from '../src/trace/model/no-record/no-record-span'; -import {Span} from '../src/trace/model/span'; -import {CoreTracerBase} from '../src/trace/model/tracer-base'; +import { randomSpanId } from '../src/internal/util'; +import { TracerConfig } from '../src/trace/config/types'; +import { TraceParams } from '../src/trace/config/types'; +import { NoRecordRootSpan } from '../src/trace/model/no-record/no-record-root-span'; +import { NoRecordSpan } from '../src/trace/model/no-record/no-record-span'; +import { Span } from '../src/trace/model/span'; +import { CoreTracerBase } from '../src/trace/model/tracer-base'; import * as types from '../src/trace/model/types'; -import {SpanEventListener} from '../src/trace/model/types'; +import { SpanEventListener } from '../src/trace/model/types'; class OnEndSpanClass implements SpanEventListener { /** Counter for test use */ @@ -38,11 +38,11 @@ class OnEndSpanClass implements SpanEventListener { } const defaultConfig: TracerConfig = { - samplingRate: 1.0 // always sampler + samplingRate: 1.0, // always sampler }; describe('Tracer Base', () => { - const options = {name: 'test'}; + const options = { name: 'test' }; /** Should create a Tracer instance */ describe('new Tracer()', () => { @@ -127,7 +127,7 @@ describe('Tracer Base', () => { before(() => { const tracer = new CoreTracerBase(); tracer.start(defaultConfig); - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { rootSpanLocal = rootSpan; }); }); @@ -141,65 +141,62 @@ describe('Tracer Base', () => { describe('startRootSpan() with sampler never', () => { const tracer = new CoreTracerBase(); - const config: TracerConfig = {samplingRate: 0}; + const config: TracerConfig = { samplingRate: 0 }; it('should start the new NoRecordRootSpan instance', () => { tracer.start(config); - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { assert.ok(rootSpan instanceof NoRecordRootSpan); }); }); - it('should start the new RootSpan instance when always sampling provided at span level', - () => { - tracer.start(config); - tracer.startRootSpan({name: 'test', samplingRate: 1}, (rootSpan) => { - assert.ok(rootSpan); - }); - }); + it('should start the new RootSpan instance when always sampling provided at span level', () => { + tracer.start(config); + tracer.startRootSpan({ name: 'test', samplingRate: 1 }, rootSpan => { + assert.ok(rootSpan); + }); + }); }); describe('startRootSpan() with sampler always', () => { const tracer = new CoreTracerBase(); - const config: TracerConfig = {samplingRate: 1}; + const config: TracerConfig = { samplingRate: 1 }; it('should start the new RootSpan instance', () => { tracer.start(config); - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { assert.ok(rootSpan); }); }); - it('should start the new NoRecordRootSpan instance when never sampling provided at span level', - () => { - tracer.start(config); - tracer.startRootSpan({name: 'test', samplingRate: 0}, (rootSpan) => { - assert.ok(rootSpan instanceof NoRecordRootSpan); - }); - }); + it('should start the new NoRecordRootSpan instance when never sampling provided at span level', () => { + tracer.start(config); + tracer.startRootSpan({ name: 'test', samplingRate: 0 }, rootSpan => { + assert.ok(rootSpan instanceof NoRecordRootSpan); + }); + }); }); describe('startRootSpan() before start()', () => { - it('should start the new NoRecordRootSpan instance, tracer not started', - () => { - const tracer = new CoreTracerBase(); - assert.strictEqual(tracer.active, false); - tracer.startRootSpan(options, (rootSpan) => { - assert.ok(rootSpan instanceof NoRecordRootSpan); - }); - }); + it('should start the new NoRecordRootSpan instance, tracer not started', () => { + const tracer = new CoreTracerBase(); + assert.strictEqual(tracer.active, false); + tracer.startRootSpan(options, rootSpan => { + assert.ok(rootSpan instanceof NoRecordRootSpan); + }); + }); }); describe('startRootSpan() with context propagation', () => { const traceOptions: types.TraceOptions = { name: 'rootName', - kind: types.SpanKind.UNSPECIFIED + kind: types.SpanKind.UNSPECIFIED, }; it('should create new RootSpan instance, no propagation', () => { const tracer = new CoreTracerBase(); tracer.start(defaultConfig); - tracer.startRootSpan(traceOptions, (rootSpan) => { + tracer.startRootSpan(traceOptions, rootSpan => { assert.ok(rootSpan); assert.strictEqual(rootSpan.name, traceOptions.name); assert.strictEqual(rootSpan.kind, traceOptions.kind); @@ -207,17 +204,19 @@ describe('Tracer Base', () => { }); const spanContextPropagated: types.SpanContext = { - traceId: uuid.v4().split('-').join(''), + traceId: uuid + .v4() + .split('-') + .join(''), spanId: randomSpanId(), - options: 0x1 + options: 0x1, }; - it('should create the new RootSpan with propagation', () => { const tracer = new CoreTracerBase(); tracer.start(defaultConfig); traceOptions.spanContext = spanContextPropagated; - tracer.startRootSpan(traceOptions, (rootSpan) => { + tracer.startRootSpan(traceOptions, rootSpan => { assert.ok(rootSpan); assert.strictEqual(rootSpan.name, traceOptions.name); assert.strictEqual(rootSpan.kind, traceOptions.kind); @@ -226,55 +225,64 @@ describe('Tracer Base', () => { }); }); - it('should create the new RootSpan with no propagation (options bit is not set)', - () => { - const tracer = new CoreTracerBase(); - tracer.start(defaultConfig); - traceOptions.spanContext!.options = 0x0; - tracer.startRootSpan(traceOptions, (rootSpan) => { - assert.ok(rootSpan); - assert.strictEqual(rootSpan.name, traceOptions.name); - assert.strictEqual(rootSpan.kind, traceOptions.kind); - assert.strictEqual(rootSpan.traceId, spanContextPropagated.traceId); - assert.strictEqual( - rootSpan.parentSpanId, spanContextPropagated.spanId); - }); - }); - - it('should create a tracer with default TraceParams when no parameters are specified upon initialisation', - () => { - const tracer = new CoreTracerBase(); - tracer.start(defaultConfig); - assert.strictEqual( - tracer.activeTraceParams.numberOfAnnontationEventsPerSpan, - undefined); - assert.strictEqual( - tracer.activeTraceParams.numberOfAttributesPerSpan, undefined); - assert.strictEqual( - tracer.activeTraceParams.numberOfLinksPerSpan, undefined); - assert.strictEqual( - tracer.activeTraceParams.numberOfMessageEventsPerSpan, undefined); - }); - - it('should create a tracer with default TraceParams when parameters with values higher than maximum limit are specified upon initialisation', - () => { - const traceParametersWithHigherThanMaximumValues: TraceParams = { - numberOfAnnontationEventsPerSpan: 50, - numberOfMessageEventsPerSpan: 200, - numberOfAttributesPerSpan: 37, - numberOfLinksPerSpan: 45 - }; - defaultConfig.traceParams = traceParametersWithHigherThanMaximumValues; - const tracer = new CoreTracerBase(); - tracer.start(defaultConfig); - assert.strictEqual( - tracer.activeTraceParams.numberOfAnnontationEventsPerSpan, 32); - assert.strictEqual( - tracer.activeTraceParams.numberOfAttributesPerSpan, 32); - assert.strictEqual(tracer.activeTraceParams.numberOfLinksPerSpan, 32); - assert.strictEqual( - tracer.activeTraceParams.numberOfMessageEventsPerSpan, 128); - }); + it('should create the new RootSpan with no propagation (options bit is not set)', () => { + const tracer = new CoreTracerBase(); + tracer.start(defaultConfig); + traceOptions.spanContext!.options = 0x0; + tracer.startRootSpan(traceOptions, rootSpan => { + assert.ok(rootSpan); + assert.strictEqual(rootSpan.name, traceOptions.name); + assert.strictEqual(rootSpan.kind, traceOptions.kind); + assert.strictEqual(rootSpan.traceId, spanContextPropagated.traceId); + assert.strictEqual(rootSpan.parentSpanId, spanContextPropagated.spanId); + }); + }); + + it('should create a tracer with default TraceParams when no parameters are specified upon initialisation', () => { + const tracer = new CoreTracerBase(); + tracer.start(defaultConfig); + assert.strictEqual( + tracer.activeTraceParams.numberOfAnnontationEventsPerSpan, + undefined + ); + assert.strictEqual( + tracer.activeTraceParams.numberOfAttributesPerSpan, + undefined + ); + assert.strictEqual( + tracer.activeTraceParams.numberOfLinksPerSpan, + undefined + ); + assert.strictEqual( + tracer.activeTraceParams.numberOfMessageEventsPerSpan, + undefined + ); + }); + + it('should create a tracer with default TraceParams when parameters with values higher than maximum limit are specified upon initialisation', () => { + const traceParametersWithHigherThanMaximumValues: TraceParams = { + numberOfAnnontationEventsPerSpan: 50, + numberOfMessageEventsPerSpan: 200, + numberOfAttributesPerSpan: 37, + numberOfLinksPerSpan: 45, + }; + defaultConfig.traceParams = traceParametersWithHigherThanMaximumValues; + const tracer = new CoreTracerBase(); + tracer.start(defaultConfig); + assert.strictEqual( + tracer.activeTraceParams.numberOfAnnontationEventsPerSpan, + 32 + ); + assert.strictEqual( + tracer.activeTraceParams.numberOfAttributesPerSpan, + 32 + ); + assert.strictEqual(tracer.activeTraceParams.numberOfLinksPerSpan, 32); + assert.strictEqual( + tracer.activeTraceParams.numberOfMessageEventsPerSpan, + 128 + ); + }); }); /** Should create and start a Span instance into a rootSpan */ @@ -284,9 +292,12 @@ describe('Tracer Base', () => { before(() => { tracer = new CoreTracerBase(); tracer.start(defaultConfig); - tracer.startRootSpan(options, (rootSpan) => { - span = tracer.startChildSpan( - {name: 'spanName', kind: types.SpanKind.CLIENT, childOf: rootSpan}); + tracer.startRootSpan(options, rootSpan => { + span = tracer.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.CLIENT, + childOf: rootSpan, + }); }); }); it('should create a Span instance', () => { @@ -299,9 +310,12 @@ describe('Tracer Base', () => { }); it('should start a span with SpanObject', () => { - tracer.startRootSpan(options, (rootSpan) => { - const spanWithObject = tracer.startChildSpan( - {name: 'my-span', kind: types.SpanKind.SERVER, childOf: rootSpan}); + tracer.startRootSpan(options, rootSpan => { + const spanWithObject = tracer.startChildSpan({ + name: 'my-span', + kind: types.SpanKind.SERVER, + childOf: rootSpan, + }); assert.ok(spanWithObject.started); assert.strictEqual(spanWithObject.name, 'my-span'); assert.strictEqual(spanWithObject.kind, types.SpanKind.SERVER); @@ -309,9 +323,11 @@ describe('Tracer Base', () => { }); it('should start a span with SpanObject-name', () => { - tracer.startRootSpan(options, (rootSpan) => { - const spanWithObject = - tracer.startChildSpan({name: 'my-span1', childOf: rootSpan}); + tracer.startRootSpan(options, rootSpan => { + const spanWithObject = tracer.startChildSpan({ + name: 'my-span1', + childOf: rootSpan, + }); assert.ok(spanWithObject.started); assert.strictEqual(spanWithObject.name, 'my-span1'); assert.strictEqual(spanWithObject.kind, types.SpanKind.UNSPECIFIED); @@ -319,7 +335,7 @@ describe('Tracer Base', () => { }); it('should start a no-record span without params', () => { - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { const spanWithObject = tracer.startChildSpan(); assert.strictEqual(spanWithObject.name, 'no-record'); assert.strictEqual(spanWithObject.kind, types.SpanKind.UNSPECIFIED); @@ -327,25 +343,25 @@ describe('Tracer Base', () => { }); it('should support nested children', () => { - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { assert.strictEqual(rootSpan.numberOfChildren, 0); const child1 = tracer.startChildSpan({ name: 'child1', kind: types.SpanKind.UNSPECIFIED, - childOf: rootSpan + childOf: rootSpan, }); assert.strictEqual(rootSpan.numberOfChildren, 1); assert.strictEqual(child1.numberOfChildren, 0); const child2 = tracer.startChildSpan({ name: 'child2', kind: types.SpanKind.UNSPECIFIED, - childOf: rootSpan + childOf: rootSpan, }); assert.strictEqual(rootSpan.numberOfChildren, 2); const grandchild1 = tracer.startChildSpan({ name: 'grandchild1', kind: types.SpanKind.UNSPECIFIED, - childOf: child1 + childOf: child1, }); assert.strictEqual(rootSpan.numberOfChildren, 2); assert.strictEqual(child1.numberOfChildren, 1); @@ -373,8 +389,10 @@ describe('Tracer Base', () => { it('should create a NoRecordSpan instance, without a rootspan', () => { const tracer = new CoreTracerBase(); tracer.start(defaultConfig); - const span = tracer.startChildSpan( - {name: 'spanName', kind: types.SpanKind.UNSPECIFIED}); + const span = tracer.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.UNSPECIFIED, + }); assert.ok(span instanceof NoRecordSpan); }); }); @@ -389,19 +407,26 @@ describe('Tracer Base', () => { tracer = new CoreTracerBase(); tracerConfig = { ...defaultConfig, - defaultAttributes: - {cluster_name: 'test-cluster', asg_name: 'test-asg'} + defaultAttributes: { + cluster_name: 'test-cluster', + asg_name: 'test-asg', + }, }; tracer.start(tracerConfig); - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { rootSpanLocal = rootSpan; - span = tracer.startChildSpan( - {name: 'spanName', kind: types.SpanKind.CLIENT, childOf: rootSpan}); + span = tracer.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.CLIENT, + childOf: rootSpan, + }); }); }); it('should add add attributes to spans', () => { assert.deepStrictEqual( - rootSpanLocal.attributes, tracerConfig.defaultAttributes); + rootSpanLocal.attributes, + tracerConfig.defaultAttributes + ); assert.deepStrictEqual(span.attributes, tracerConfig.defaultAttributes); }); }); @@ -414,10 +439,12 @@ describe('Tracer Base', () => { tracer.registerSpanEventListener(eventListener); tracer.start(defaultConfig); - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { rootSpan.end(); assert.strictEqual( - eventListener.testCount, tracer.eventListeners.length); + eventListener.testCount, + tracer.eventListeners.length + ); }); }); }); diff --git a/packages/opencensus-core/test/test-tracer.ts b/packages/opencensus-core/test/test-tracer.ts index 403998c8d..79964e0f8 100644 --- a/packages/opencensus-core/test/test-tracer.ts +++ b/packages/opencensus-core/test/test-tracer.ts @@ -16,18 +16,18 @@ import * as assert from 'assert'; -import {TracerConfig} from '../src/trace/config/types'; -import {NoRecordSpan} from '../src/trace/model/no-record/no-record-span'; -import {Span} from '../src/trace/model/span'; -import {CoreTracer} from '../src/trace/model/tracer'; +import { TracerConfig } from '../src/trace/config/types'; +import { NoRecordSpan } from '../src/trace/model/no-record/no-record-span'; +import { Span } from '../src/trace/model/span'; +import { CoreTracer } from '../src/trace/model/tracer'; import * as types from '../src/trace/model/types'; const defaultConfig: TracerConfig = { - samplingRate: 1.0 // always sampler + samplingRate: 1.0, // always sampler }; describe('Tracer', () => { - const options = {name: 'test'}; + const options = { name: 'test' }; /** Should create a Tracer instance */ describe('new Tracer()', () => { @@ -41,7 +41,7 @@ describe('Tracer', () => { describe('get/set currentRootSpan()', () => { const tracer = new CoreTracer().start(defaultConfig); it('should get the current RootSpan from tracer instance', () => { - tracer.startRootSpan(options, (root) => { + tracer.startRootSpan(options, root => { assert.ok(root); assert.ok(tracer.currentRootSpan instanceof Span); assert.strictEqual(tracer.currentRootSpan, root); @@ -56,7 +56,7 @@ describe('Tracer', () => { before(() => { tracer = new CoreTracer(); tracer.start(defaultConfig); - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { rootSpanLocal = rootSpan; }); }); @@ -64,7 +64,7 @@ describe('Tracer', () => { assert.ok(rootSpanLocal instanceof Span); }); it('should set current root span', () => { - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { assert.ok(tracer.currentRootSpan instanceof Span); assert.strictEqual(tracer.currentRootSpan, rootSpan); }); @@ -76,7 +76,7 @@ describe('Tracer', () => { it('should set the current root span to null', () => { const tracer = new CoreTracer(); tracer.start(defaultConfig); - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { assert.ok(tracer.currentRootSpan instanceof Span); assert.strictEqual(tracer.currentRootSpan, rootSpan); tracer.clearCurrentTrace(); @@ -93,10 +93,12 @@ describe('Tracer', () => { before(() => { tracer = new CoreTracer(); tracer.start(defaultConfig); - tracer.startRootSpan(options, (rootSpan) => { + tracer.startRootSpan(options, rootSpan => { rootSpanLocal = rootSpan; - span = tracer.startChildSpan( - {name: 'spanName', kind: types.SpanKind.CLIENT}); + span = tracer.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.CLIENT, + }); }); }); it('should create a Span instance', () => { @@ -115,8 +117,10 @@ describe('Tracer', () => { it('should create a NoRecordSpan instance, without a rootspan', () => { const tracer = new CoreTracer(); tracer.start(defaultConfig); - const span = tracer.startChildSpan( - {name: 'spanName', kind: types.SpanKind.UNSPECIFIED}); + const span = tracer.startChildSpan({ + name: 'spanName', + kind: types.SpanKind.UNSPECIFIED, + }); assert.ok(span instanceof NoRecordSpan); }); }); diff --git a/packages/opencensus-core/test/test-utils.ts b/packages/opencensus-core/test/test-utils.ts index 9abfd1fcc..72fc99829 100644 --- a/packages/opencensus-core/test/test-utils.ts +++ b/packages/opencensus-core/test/test-utils.ts @@ -14,14 +14,17 @@ * limitations under the License. */ import * as assert from 'assert'; -import {LabelValue} from '../src/metrics/export/types'; -import {hashLabelValues, initializeDefaultLabels} from '../src/metrics/utils'; +import { LabelValue } from '../src/metrics/export/types'; +import { hashLabelValues, initializeDefaultLabels } from '../src/metrics/utils'; describe('hashLabelValues', () => { - const LABEL_VALUES: LabelValue[] = [{value: '200'}]; - const LABEL_VALUES_WITH_NULL: LabelValue[] = [{value: '200'}, {value: null}]; - const LABEL_VALUES_1: LabelValue[] = [{value: '200'}, {value: '400'}]; - const LABEL_VALUES_2: LabelValue[] = [{value: '400'}, {value: '200'}]; + const LABEL_VALUES: LabelValue[] = [{ value: '200' }]; + const LABEL_VALUES_WITH_NULL: LabelValue[] = [ + { value: '200' }, + { value: null }, + ]; + const LABEL_VALUES_1: LabelValue[] = [{ value: '200' }, { value: '400' }]; + const LABEL_VALUES_2: LabelValue[] = [{ value: '400' }, { value: '200' }]; it('should return hash for single Value', () => { const hash = hashLabelValues(LABEL_VALUES); assert.deepStrictEqual(hash, '200'); @@ -32,21 +35,26 @@ describe('hashLabelValues', () => { }); it('should return same hash for interchanged labels', () => { assert.deepStrictEqual( - hashLabelValues(LABEL_VALUES_1), hashLabelValues(LABEL_VALUES_2)); + hashLabelValues(LABEL_VALUES_1), + hashLabelValues(LABEL_VALUES_2) + ); }); it('should return empty string for empty array', () => { assert.deepStrictEqual(hashLabelValues([]), ''); }); }); describe('initializeDefaultLabels', () => { - const UNSET_VALUE: LabelValue = {value: null}; + const UNSET_VALUE: LabelValue = { value: null }; it('should return single default labels', () => { const labelValues = initializeDefaultLabels(1); assert.deepStrictEqual(labelValues, [UNSET_VALUE]); }); it('should return multiple default labels', () => { const labelValues = initializeDefaultLabels(3); - assert.deepStrictEqual( - labelValues, [UNSET_VALUE, UNSET_VALUE, UNSET_VALUE]); + assert.deepStrictEqual(labelValues, [ + UNSET_VALUE, + UNSET_VALUE, + UNSET_VALUE, + ]); }); }); diff --git a/packages/opencensus-core/test/test-validation.ts b/packages/opencensus-core/test/test-validation.ts index b669b691b..0371db171 100644 --- a/packages/opencensus-core/test/test-validation.ts +++ b/packages/opencensus-core/test/test-validation.ts @@ -15,40 +15,38 @@ */ import * as assert from 'assert'; -import {isValidTagKey, isValidTagValue} from '../src/tags/validation'; +import { isValidTagKey, isValidTagValue } from '../src/tags/validation'; describe('isValidTagKey()', () => { it('should return true when tag key is valid', () => { - const tagKey = {name: 'key1'}; + const tagKey = { name: 'key1' }; assert.ok(isValidTagKey(tagKey)); }); it('should return false when tag key is 0 character long', () => { - const tagKey = {name: ''}; + const tagKey = { name: '' }; assert.strictEqual(isValidTagKey(tagKey), false); }); - it('should return false when the tag key length is longer than 255 characters ', - () => { - const tagKey = {name: 'a'.repeat(256)}; - assert.strictEqual(isValidTagKey(tagKey), false); - }); + it('should return false when the tag key length is longer than 255 characters ', () => { + const tagKey = { name: 'a'.repeat(256) }; + assert.strictEqual(isValidTagKey(tagKey), false); + }); }); describe('isValidTagValue()', () => { it('should return true when tag value is valid', () => { - const tagValue = {value: 'value1'}; + const tagValue = { value: 'value1' }; assert.ok(isValidTagValue(tagValue)); }); it('should not throw an error when tag value is 0 character long', () => { - const tagValue = {value: ''}; + const tagValue = { value: '' }; assert.ok(isValidTagValue(tagValue)); }); - it('should return false when the tag value length is longer than 255 characters ', - () => { - const tagValue = {value: 'a'.repeat(256)}; - assert.strictEqual(isValidTagValue(tagValue), false); - }); + it('should return false when the tag value length is longer than 255 characters ', () => { + const tagValue = { value: 'a'.repeat(256) }; + assert.strictEqual(isValidTagValue(tagValue), false); + }); }); diff --git a/packages/opencensus-core/test/test-variant-encoding.ts b/packages/opencensus-core/test/test-variant-encoding.ts index 88fd233d0..039391dc3 100644 --- a/packages/opencensus-core/test/test-variant-encoding.ts +++ b/packages/opencensus-core/test/test-variant-encoding.ts @@ -15,10 +15,23 @@ */ import * as assert from 'assert'; -import {DecodeVarint, EncodeVarint} from '../src/tags/propagation/variant-encoding'; +import { + DecodeVarint, + EncodeVarint, +} from '../src/tags/propagation/variant-encoding'; -const testCases = - [0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000]; +const testCases = [ + 0, + 1, + 10, + 100, + 1000, + 10000, + 100000, + 1000000, + 10000000, + 100000000, +]; function randint(range: number) { return Math.floor(Math.random() * range); @@ -32,7 +45,7 @@ describe('variant encoding', () => { it('should encode/decode multiple bytes', () => { const num = 300; - const expectedBytes = [0xAC, 0x02]; // [172, 2] + const expectedBytes = [0xac, 0x02]; // [172, 2] const variant = EncodeVarint(num); assert.deepStrictEqual(variant, expectedBytes); diff --git a/packages/opencensus-core/test/test-view.ts b/packages/opencensus-core/test/test-view.ts index 7125adb2b..36c2cbfed 100644 --- a/packages/opencensus-core/test/test-view.ts +++ b/packages/opencensus-core/test/test-view.ts @@ -16,10 +16,21 @@ import * as assert from 'assert'; -import {BaseView, TagMap, TagValue} from '../src'; -import {TEST_ONLY} from '../src/common/time-util'; -import {DistributionValue, MetricDescriptorType, Timestamp} from '../src/metrics/export/types'; -import {AggregationType, DistributionData, Measure, MeasureType, MeasureUnit, View} from '../src/stats/types'; +import { BaseView, TagMap, TagValue } from '../src'; +import { TEST_ONLY } from '../src/common/time-util'; +import { + DistributionValue, + MetricDescriptorType, + Timestamp, +} from '../src/metrics/export/types'; +import { + AggregationType, + DistributionData, + Measure, + MeasureType, + MeasureUnit, + View, +} from '../src/stats/types'; /** The order of how close values must be to be considerated almost equal */ const EPSILON = 6; @@ -31,12 +42,17 @@ interface AggregationTestCase { } function isAlmostEqual( - actual: number, expected: number, epsilon: number): boolean { + actual: number, + expected: number, + epsilon: number +): boolean { return Math.abs(actual - expected) < Math.pow(10, -epsilon); } function assertDistributionData( - distributionData: DistributionData, values: number[]) { + distributionData: DistributionData, + values: number[] +) { const valuesSum = values.reduce((acc, cur) => acc + cur); assert.strictEqual(distributionData.count, values.length); @@ -45,22 +61,31 @@ function assertDistributionData( const expectedMean = valuesSum / values.length; assert.ok(isAlmostEqual(distributionData.mean, expectedMean, EPSILON)); - const expectedSumSquaredDeviations = - values.map(value => Math.pow(value - expectedMean, 2)) - .reduce((acc, curr) => acc + curr); - assert.ok(isAlmostEqual( - distributionData.sumOfSquaredDeviation, expectedSumSquaredDeviations, - EPSILON)); - - const expectedStdDeviation = - Math.sqrt(expectedSumSquaredDeviations / values.length); - assert.ok(isAlmostEqual( - distributionData.stdDeviation, expectedStdDeviation, EPSILON)); + const expectedSumSquaredDeviations = values + .map(value => Math.pow(value - expectedMean, 2)) + .reduce((acc, curr) => acc + curr); + assert.ok( + isAlmostEqual( + distributionData.sumOfSquaredDeviation, + expectedSumSquaredDeviations, + EPSILON + ) + ); + + const expectedStdDeviation = Math.sqrt( + expectedSumSquaredDeviations / values.length + ); + assert.ok( + isAlmostEqual(distributionData.stdDeviation, expectedStdDeviation, EPSILON) + ); } function assertView( - view: View, recordedValues: number[], aggregationType: AggregationType, - tagValues: TagValue[]) { + view: View, + recordedValues: number[], + aggregationType: AggregationType, + tagValues: TagValue[] +) { assert.strictEqual(view.aggregation, aggregationType); const aggregationData = view.getSnapshot(tagValues); switch (aggregationData.type) { @@ -76,7 +101,9 @@ function assertView( break; default: assert.strictEqual( - aggregationData.value, recordedValues[recordedValues.length - 1]); + aggregationData.value, + recordedValues[recordedValues.length - 1] + ); break; } } @@ -85,38 +112,42 @@ describe('BaseView', () => { const measure: Measure = { name: 'Test Measure', type: MeasureType.DOUBLE, - unit: MeasureUnit.UNIT + unit: MeasureUnit.UNIT, }; const aggregationTestCases: AggregationTestCase[] = [ { aggregationType: AggregationType.SUM, description: 'Sum', - metricDescriptorType: MetricDescriptorType.CUMULATIVE_DOUBLE + metricDescriptorType: MetricDescriptorType.CUMULATIVE_DOUBLE, }, { aggregationType: AggregationType.COUNT, description: 'Count', - metricDescriptorType: MetricDescriptorType.CUMULATIVE_INT64 + metricDescriptorType: MetricDescriptorType.CUMULATIVE_INT64, }, { aggregationType: AggregationType.LAST_VALUE, description: 'Last Value', - metricDescriptorType: MetricDescriptorType.GAUGE_DOUBLE + metricDescriptorType: MetricDescriptorType.GAUGE_DOUBLE, }, { aggregationType: AggregationType.DISTRIBUTION, description: 'Distribution', - metricDescriptorType: MetricDescriptorType.CUMULATIVE_DISTRIBUTION - } + metricDescriptorType: MetricDescriptorType.CUMULATIVE_DISTRIBUTION, + }, ]; describe('getColumns()', () => { it('should access the given tag keys', () => { - const tagKeys = [{name: 'testKey1'}, {name: 'testKey2'}]; + const tagKeys = [{ name: 'testKey1' }, { name: 'testKey2' }]; const view = new BaseView( - 'test/view/name', measure, AggregationType.LAST_VALUE, tagKeys, - 'description test'); + 'test/view/name', + measure, + AggregationType.LAST_VALUE, + tagKeys, + 'description test' + ); assert.deepStrictEqual(view.getColumns(), tagKeys); }); @@ -124,12 +155,19 @@ describe('BaseView', () => { describe('createView()', () => { it('should throw error when keys are duplicate', () => { - const tagKeys = - [{name: 'testKey1'}, {name: 'testKey1'}, {name: 'testKey2'}]; + const tagKeys = [ + { name: 'testKey1' }, + { name: 'testKey1' }, + { name: 'testKey2' }, + ]; assert.throws(() => { const view = new BaseView( - 'test/view/name', measure, AggregationType.LAST_VALUE, tagKeys, - 'description test'); + 'test/view/name', + measure, + AggregationType.LAST_VALUE, + tagKeys, + 'description test' + ); assert.deepStrictEqual(view.getColumns(), tagKeys); }, /^Error: Columns have duplicate$/); }); @@ -138,13 +176,13 @@ describe('BaseView', () => { describe('recordMeasurement()', () => { const measurementValues = [1.1, 2.3, 3.2, 4.3, 5.2]; const bucketBoundaries = [2, 4, 6]; - const tagKey1 = {name: 'testKey1'}; - const tagKey2 = {name: 'testKey2'}; + const tagKey1 = { name: 'testKey1' }; + const tagKey2 = { name: 'testKey2' }; const tagKeys = [tagKey1, tagKey2]; - const tagKey3 = {name: 'testKey3'}; - const tagValue1 = {value: 'testValue1'}; - const tagValue2 = {value: 'testValue2'}; - const tagValue3 = {value: 'testValue3'}; + const tagKey3 = { name: 'testKey3' }; + const tagValue1 = { value: 'testValue1' }; + const tagValue2 = { value: 'testValue2' }; + const tagValue3 = { value: 'testValue3' }; const tags = new TagMap(); tags.set(tagKey1, tagValue1); @@ -152,32 +190,45 @@ describe('BaseView', () => { for (const aggregationTestCase of aggregationTestCases) { it(`should record measurements on a View with ${ - aggregationTestCase.description} Aggregation Data type`, - () => { - const view = new BaseView( - 'test/view/name', measure, aggregationTestCase.aggregationType, - tagKeys, 'description test', bucketBoundaries); - const recordedValues = []; - for (const value of measurementValues) { - recordedValues.push(value); - const measurement = {measure, value}; - view.recordMeasurement(measurement, tags); - assertView( - view, recordedValues, aggregationTestCase.aggregationType, - [tagValue1, tagValue2]); - } - }); + aggregationTestCase.description + } Aggregation Data type`, () => { + const view = new BaseView( + 'test/view/name', + measure, + aggregationTestCase.aggregationType, + tagKeys, + 'description test', + bucketBoundaries + ); + const recordedValues = []; + for (const value of measurementValues) { + recordedValues.push(value); + const measurement = { measure, value }; + view.recordMeasurement(measurement, tags); + assertView( + view, + recordedValues, + aggregationTestCase.aggregationType, + [tagValue1, tagValue2] + ); + } + }); } it('should ignore negative bucket bounds', () => { const negativeBucketBoundaries = [-Infinity, -4, -2, 0, 2, 4, 6]; const view = new BaseView( - 'test/view/name', measure, AggregationType.DISTRIBUTION, tagKeys, - 'description test', negativeBucketBoundaries); + 'test/view/name', + measure, + AggregationType.DISTRIBUTION, + tagKeys, + 'description test', + negativeBucketBoundaries + ); const recordedValues = []; for (const value of measurementValues) { recordedValues.push(value); - const measurement = {measure, value}; + const measurement = { measure, value }; view.recordMeasurement(measurement, tags); } const data = view.getSnapshot([tagValue1, tagValue2]) as DistributionData; @@ -186,13 +237,17 @@ describe('BaseView', () => { }); const view = new BaseView( - 'test/view/name', measure, AggregationType.LAST_VALUE, tagKeys, - 'description test'); + 'test/view/name', + measure, + AggregationType.LAST_VALUE, + tagKeys, + 'description test' + ); it('should not record a measurement when it have wrong tag keys', () => { const tagMap = new TagMap(); tagMap.set(tagKey3, tagValue3); - const measurement = {measure, value: 10}; + const measurement = { measure, value: 10 }; view.recordMeasurement(measurement, tagMap); assert.ok(!view.getSnapshot([tagValue3])); }); @@ -201,18 +256,18 @@ describe('BaseView', () => { describe('getMetric()', () => { const realHrtimeFn = process.hrtime; const realNowFn = Date.now; - const mockedTime: Timestamp = {seconds: 1450000100, nanos: 1e7}; + const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 }; const mockStartTime = 1546540757282; - const mockStartTimestamp: Timestamp = {seconds: 1546540757, nanos: 282e6}; + const mockStartTimestamp: Timestamp = { seconds: 1546540757, nanos: 282e6 }; const measurementValues = [1.1, 2.3, 3.2, 4.3, 5.2]; const buckets = [2, 4, 6]; - const tagKey1 = {name: 'testKey1'}; - const tagKey2 = {name: 'testKey2'}; + const tagKey1 = { name: 'testKey1' }; + const tagKey2 = { name: 'testKey2' }; const tagKeys = [tagKey1, tagKey2]; - const tagValue1 = {value: 'testValue1'}; - const tagValue2 = {value: 'testValue2'}; - const tagValue3 = {value: 'testValue3'}; - const tagValue4 = {value: 'testValue4'}; + const tagValue1 = { value: 'testValue1' }; + const tagValue2 = { value: 'testValue2' }; + const tagValue3 = { value: 'testValue3' }; + const tagValue4 = { value: 'testValue4' }; const tags = new TagMap(); tags.set(tagKey1, tagValue1); @@ -224,10 +279,15 @@ describe('BaseView', () => { for (const aggregationTestCase of aggregationTestCases) { const view: View = new BaseView( - 'test/view/name', measure, aggregationTestCase.aggregationType, - tagKeys, 'description test', buckets); + 'test/view/name', + measure, + aggregationTestCase.aggregationType, + tagKeys, + 'description test', + buckets + ); for (const value of measurementValues) { - const measurement = {measure, value}; + const measurement = { measure, value }; view.recordMeasurement(measurement, tags); } @@ -245,83 +305,94 @@ describe('BaseView', () => { TEST_ONLY.resetHrtimeFunctionCache(); }); - const {descriptor, timeseries} = view.getMetric(mockStartTime); - - describe( - `Aggregation type: ${aggregationTestCase.aggregationType}`, () => { - it('should have descriptor', () => { - assert.ok(descriptor); - assert.deepStrictEqual(descriptor, { - description: 'description test', - labelKeys: [ - {key: 'testKey1', description: ''}, - {key: 'testKey2', description: ''} - ], - name: 'test/view/name', - type: aggregationTestCase.metricDescriptorType, - unit: '1', - }); - }); - - const [{startTimestamp, labelValues}] = timeseries; - - if (aggregationTestCase.metricDescriptorType === - MetricDescriptorType.GAUGE_INT64) { - it('GAUGE_INT64 shouldnt have timeseries startTimestamp', () => { - assert.strictEqual(startTimestamp, undefined); - }); - } else if ( - aggregationTestCase.metricDescriptorType === - MetricDescriptorType.GAUGE_DOUBLE) { - it('GAUGE_DOUBLE shouldnt have timeseries startTimestamp', () => { - assert.strictEqual(startTimestamp, undefined); - }); - } else { - it('should have timeseries startTimestamp', () => { - assert.ok(startTimestamp); - assert.strictEqual(typeof startTimestamp!.nanos, 'number'); - assert.strictEqual(typeof startTimestamp!.seconds, 'number'); - assert.deepStrictEqual(startTimestamp, mockStartTimestamp); - }); - } - - it('should have labelValues', () => { - assert.ok(labelValues); - assert.deepStrictEqual( - labelValues, [{value: 'testValue1'}, {value: 'testValue2'}]); - }); + const { descriptor, timeseries } = view.getMetric(mockStartTime); + + describe(`Aggregation type: ${ + aggregationTestCase.aggregationType + }`, () => { + it('should have descriptor', () => { + assert.ok(descriptor); + assert.deepStrictEqual(descriptor, { + description: 'description test', + labelKeys: [ + { key: 'testKey1', description: '' }, + { key: 'testKey2', description: '' }, + ], + name: 'test/view/name', + type: aggregationTestCase.metricDescriptorType, + unit: '1', + }); + }); + + const [{ startTimestamp, labelValues }] = timeseries; + + if ( + aggregationTestCase.metricDescriptorType === + MetricDescriptorType.GAUGE_INT64 + ) { + it('GAUGE_INT64 shouldnt have timeseries startTimestamp', () => { + assert.strictEqual(startTimestamp, undefined); + }); + } else if ( + aggregationTestCase.metricDescriptorType === + MetricDescriptorType.GAUGE_DOUBLE + ) { + it('GAUGE_DOUBLE shouldnt have timeseries startTimestamp', () => { + assert.strictEqual(startTimestamp, undefined); + }); + } else { + it('should have timeseries startTimestamp', () => { + assert.ok(startTimestamp); + assert.strictEqual(typeof startTimestamp!.nanos, 'number'); + assert.strictEqual(typeof startTimestamp!.seconds, 'number'); + assert.deepStrictEqual(startTimestamp, mockStartTimestamp); }); + } + + it('should have labelValues', () => { + assert.ok(labelValues); + assert.deepStrictEqual(labelValues, [ + { value: 'testValue1' }, + { value: 'testValue2' }, + ]); + }); + }); } describe('DISTRIBUTION aggregation type', () => { const view: View = new BaseView( - 'test/view/name', measure, AggregationType.DISTRIBUTION, tagKeys, - 'description test', buckets); + 'test/view/name', + measure, + AggregationType.DISTRIBUTION, + tagKeys, + 'description test', + buckets + ); let total = 0; for (const value of measurementValues) { total += value; - const measurement = {measure, value}; + const measurement = { measure, value }; view.recordMeasurement(measurement, tags); } it('should have point', () => { - const {timeseries} = view.getMetric(mockStartTime); - const [{points, startTimestamp}] = timeseries; + const { timeseries } = view.getMetric(mockStartTime); + const [{ points, startTimestamp }] = timeseries; assert.ok(points); const [point] = points; - const {timestamp, value} = point; + const { timestamp, value } = point; assert.ok(timestamp); assert.strictEqual(typeof timestamp.nanos, 'number'); assert.strictEqual(typeof timestamp.seconds, 'number'); assert.strictEqual(timestamp.seconds, mockedTime.seconds); assert.strictEqual(timestamp.nanos, mockedTime.nanos); assert.notStrictEqual(typeof value, 'number'); - assert.deepStrictEqual((value as DistributionValue), { - bucketOptions: {explicit: {bounds: buckets}}, - buckets: [{count: 1}, {count: 2}, {count: 2}, {count: 0}], + assert.deepStrictEqual(value as DistributionValue, { + bucketOptions: { explicit: { bounds: buckets } }, + buckets: [{ count: 1 }, { count: 2 }, { count: 2 }, { count: 0 }], count: 5, sum: total, - sumOfSquaredDeviation: 10.427999999999997 + sumOfSquaredDeviation: 10.427999999999997, }); assert.deepStrictEqual(startTimestamp, mockStartTimestamp); @@ -339,191 +410,211 @@ describe('BaseView', () => { it('should have point with attachments', () => { const view: View = new BaseView( - 'test/view/name', measure, AggregationType.DISTRIBUTION, tagKeys, - 'description test', buckets); + 'test/view/name', + measure, + AggregationType.DISTRIBUTION, + tagKeys, + 'description test', + buckets + ); let total = 0; - const attachments = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}; + const attachments = { k1: 'v1', k2: 'v2', k3: 'v3' }; for (const value of measurementValues) { total += value; - const measurement = {measure, value}; + const measurement = { measure, value }; view.recordMeasurement(measurement, tags, attachments); } - const {timeseries} = view.getMetric(mockStartTime); - const [{points, startTimestamp}] = timeseries; + const { timeseries } = view.getMetric(mockStartTime); + const [{ points, startTimestamp }] = timeseries; assert.ok(points); const [point] = points; - const {timestamp, value} = point; + const { timestamp, value } = point; assert.ok(timestamp); - assert.deepStrictEqual((value as DistributionValue), { - bucketOptions: {explicit: {bounds: buckets}}, + assert.deepStrictEqual(value as DistributionValue, { + bucketOptions: { explicit: { bounds: buckets } }, buckets: [ { count: 1, exemplar: { value: 1.1, - timestamp: {seconds: 1450000000, nanos: 0}, - attachments - } + timestamp: { seconds: 1450000000, nanos: 0 }, + attachments, + }, }, { count: 2, exemplar: { value: 3.2, - timestamp: {seconds: 1450000000, nanos: 0}, - attachments - } + timestamp: { seconds: 1450000000, nanos: 0 }, + attachments, + }, }, { count: 2, exemplar: { value: 5.2, - timestamp: {seconds: 1450000000, nanos: 0}, - attachments - } + timestamp: { seconds: 1450000000, nanos: 0 }, + attachments, + }, }, - {count: 0} + { count: 0 }, ], count: 5, sum: total, - sumOfSquaredDeviation: 10.427999999999997 + sumOfSquaredDeviation: 10.427999999999997, }); assert.deepStrictEqual(startTimestamp, mockStartTimestamp); }); it('should have point with empty attachments', () => { const view: View = new BaseView( - 'test/view/name', measure, AggregationType.DISTRIBUTION, tagKeys, - 'description test', buckets); + 'test/view/name', + measure, + AggregationType.DISTRIBUTION, + tagKeys, + 'description test', + buckets + ); let total = 0; for (const value of measurementValues) { total += value; - const measurement = {measure, value}; + const measurement = { measure, value }; view.recordMeasurement(measurement, tags, {}); } - const {timeseries} = view.getMetric(mockStartTime); - const [{points, startTimestamp}] = timeseries; + const { timeseries } = view.getMetric(mockStartTime); + const [{ points, startTimestamp }] = timeseries; assert.ok(points); const [point] = points; - const {timestamp, value} = point; + const { timestamp, value } = point; assert.ok(timestamp); - assert.deepStrictEqual((value as DistributionValue), { - bucketOptions: {explicit: {bounds: buckets}}, + assert.deepStrictEqual(value as DistributionValue, { + bucketOptions: { explicit: { bounds: buckets } }, buckets: [ { count: 1, exemplar: { value: 1.1, - timestamp: {seconds: 1450000000, nanos: 0}, - attachments: {} - } + timestamp: { seconds: 1450000000, nanos: 0 }, + attachments: {}, + }, }, { count: 2, exemplar: { value: 3.2, - timestamp: {seconds: 1450000000, nanos: 0}, - attachments: {} - } + timestamp: { seconds: 1450000000, nanos: 0 }, + attachments: {}, + }, }, { count: 2, exemplar: { value: 5.2, - timestamp: {seconds: 1450000000, nanos: 0}, - attachments: {} - } + timestamp: { seconds: 1450000000, nanos: 0 }, + attachments: {}, + }, }, - {count: 0} + { count: 0 }, ], count: 5, sum: total, - sumOfSquaredDeviation: 10.427999999999997 + sumOfSquaredDeviation: 10.427999999999997, }); assert.deepStrictEqual(startTimestamp, mockStartTimestamp); }); }); - describe( - 'DISTRIBUTION aggregation type: record with measurements in succession from a single view and single measure', - () => { - const view: View = new BaseView( - 'test/view/name', measure, AggregationType.DISTRIBUTION, tagKeys, - 'description test', buckets); - let total = 0; - for (const value of measurementValues) { - total += value; - const measurement = {measure, value}; - const measurement1 = {measure, value}; - view.recordMeasurement(measurement, tags); - view.recordMeasurement(measurement1, tagMap); - } - - it('should have points', () => { - const {timeseries} = view.getMetric(mockStartTime); - assert.strictEqual(timeseries.length, 2); - const [{labelValues: labelValues1, points: points1}, { - labelValues: labelValues2, - points: points2 - }] = timeseries; - assert.ok(points1); - - let [point] = points1; - let {timestamp, value} = point; - assert.ok(timestamp); - assert.strictEqual(typeof timestamp.nanos, 'number'); - assert.strictEqual(typeof timestamp.seconds, 'number'); - assert.strictEqual(timestamp.seconds, mockedTime.seconds); - assert.strictEqual(timestamp.nanos, mockedTime.nanos); - assert.notStrictEqual(typeof value, 'number'); - assert.deepStrictEqual((value as DistributionValue), { - bucketOptions: {explicit: {bounds: buckets}}, - buckets: [{count: 1}, {count: 2}, {count: 2}, {count: 0}], - count: 5, - sum: total, - sumOfSquaredDeviation: 10.427999999999997 - }); - assert.deepStrictEqual( - labelValues1, - [{'value': 'testValue1'}, {'value': 'testValue2'}]); - assert.ok(points2); - [point] = points2; - ({timestamp, value} = point); - assert.ok(timestamp); - assert.strictEqual(typeof timestamp.nanos, 'number'); - assert.strictEqual(typeof timestamp.seconds, 'number'); - assert.strictEqual(timestamp.seconds, mockedTime.seconds); - assert.strictEqual(timestamp.nanos, mockedTime.nanos); - assert.notStrictEqual(typeof value, 'number'); - assert.deepStrictEqual((value as DistributionValue), { - bucketOptions: {explicit: {bounds: buckets}}, - buckets: [{count: 1}, {count: 2}, {count: 2}, {count: 0}], - count: 5, - sum: total, - sumOfSquaredDeviation: 10.427999999999997 - }); - assert.deepStrictEqual( - labelValues2, - [{'value': 'testValue3'}, {'value': 'testValue4'}]); - }); + describe('DISTRIBUTION aggregation type: record with measurements in succession from a single view and single measure', () => { + const view: View = new BaseView( + 'test/view/name', + measure, + AggregationType.DISTRIBUTION, + tagKeys, + 'description test', + buckets + ); + let total = 0; + for (const value of measurementValues) { + total += value; + const measurement = { measure, value }; + const measurement1 = { measure, value }; + view.recordMeasurement(measurement, tags); + view.recordMeasurement(measurement1, tagMap); + } + + it('should have points', () => { + const { timeseries } = view.getMetric(mockStartTime); + assert.strictEqual(timeseries.length, 2); + const [ + { labelValues: labelValues1, points: points1 }, + { labelValues: labelValues2, points: points2 }, + ] = timeseries; + assert.ok(points1); + + let [point] = points1; + let { timestamp, value } = point; + assert.ok(timestamp); + assert.strictEqual(typeof timestamp.nanos, 'number'); + assert.strictEqual(typeof timestamp.seconds, 'number'); + assert.strictEqual(timestamp.seconds, mockedTime.seconds); + assert.strictEqual(timestamp.nanos, mockedTime.nanos); + assert.notStrictEqual(typeof value, 'number'); + assert.deepStrictEqual(value as DistributionValue, { + bucketOptions: { explicit: { bounds: buckets } }, + buckets: [{ count: 1 }, { count: 2 }, { count: 2 }, { count: 0 }], + count: 5, + sum: total, + sumOfSquaredDeviation: 10.427999999999997, + }); + assert.deepStrictEqual(labelValues1, [ + { value: 'testValue1' }, + { value: 'testValue2' }, + ]); + assert.ok(points2); + [point] = points2; + ({ timestamp, value } = point); + assert.ok(timestamp); + assert.strictEqual(typeof timestamp.nanos, 'number'); + assert.strictEqual(typeof timestamp.seconds, 'number'); + assert.strictEqual(timestamp.seconds, mockedTime.seconds); + assert.strictEqual(timestamp.nanos, mockedTime.nanos); + assert.notStrictEqual(typeof value, 'number'); + assert.deepStrictEqual(value as DistributionValue, { + bucketOptions: { explicit: { bounds: buckets } }, + buckets: [{ count: 1 }, { count: 2 }, { count: 2 }, { count: 0 }], + count: 5, + sum: total, + sumOfSquaredDeviation: 10.427999999999997, }); + assert.deepStrictEqual(labelValues2, [ + { value: 'testValue3' }, + { value: 'testValue4' }, + ]); + }); + }); describe('COUNT aggregation type', () => { const view: View = new BaseView( - 'test/view/name', measure, AggregationType.COUNT, tagKeys, - 'description test', buckets); + 'test/view/name', + measure, + AggregationType.COUNT, + tagKeys, + 'description test', + buckets + ); for (const value of measurementValues) { - const measurement = {measure, value}; + const measurement = { measure, value }; view.recordMeasurement(measurement, tags); } it('should have point', () => { - const {timeseries} = view.getMetric(mockStartTime); - const [{points, startTimestamp}] = timeseries; + const { timeseries } = view.getMetric(mockStartTime); + const [{ points, startTimestamp }] = timeseries; assert.ok(points); const [point] = points; - const {timestamp, value} = point; + const { timestamp, value } = point; assert.ok(timestamp); assert.strictEqual(typeof timestamp.nanos, 'number'); assert.strictEqual(typeof timestamp.seconds, 'number'); @@ -537,21 +628,26 @@ describe('BaseView', () => { describe('SUM aggregation type', () => { const view: View = new BaseView( - 'test/view/name', measure, AggregationType.SUM, tagKeys, - 'description test', buckets); + 'test/view/name', + measure, + AggregationType.SUM, + tagKeys, + 'description test', + buckets + ); let total = 0; for (const value of measurementValues) { total += value; - const measurement = {measure, value}; + const measurement = { measure, value }; view.recordMeasurement(measurement, tags); } it('should have point', () => { - const {timeseries} = view.getMetric(mockStartTime); - const [{points, startTimestamp}] = timeseries; + const { timeseries } = view.getMetric(mockStartTime); + const [{ points, startTimestamp }] = timeseries; assert.ok(points); const [point] = points; - const {timestamp, value} = point; + const { timestamp, value } = point; assert.ok(timestamp); assert.strictEqual(typeof timestamp.nanos, 'number'); assert.strictEqual(typeof timestamp.seconds, 'number'); @@ -565,24 +661,31 @@ describe('BaseView', () => { describe('LAST_VALUE aggregation type', () => { const view: View = new BaseView( - 'test/view/name', measure, AggregationType.LAST_VALUE, tagKeys, - 'description test', buckets); + 'test/view/name', + measure, + AggregationType.LAST_VALUE, + tagKeys, + 'description test', + buckets + ); for (const value of measurementValues) { - const measurement = {measure, value}; + const measurement = { measure, value }; view.recordMeasurement(measurement, tags); } it('should have point', () => { - const {timeseries} = view.getMetric(mockStartTime); - const [{points, startTimestamp}] = timeseries; + const { timeseries } = view.getMetric(mockStartTime); + const [{ points, startTimestamp }] = timeseries; assert.ok(points); const [point] = points; - const {timestamp, value} = point; + const { timestamp, value } = point; assert.strictEqual(timestamp.seconds, mockedTime.seconds); assert.strictEqual(timestamp.nanos, mockedTime.nanos); assert.strictEqual(typeof value, 'number'); assert.strictEqual( - value, measurementValues[measurementValues.length - 1]); + value, + measurementValues[measurementValues.length - 1] + ); assert.strictEqual(startTimestamp, undefined); }); }); @@ -590,11 +693,11 @@ describe('BaseView', () => { describe('getSnapshots()', () => { let view: View; - const tagKey1 = {name: 'testKey1'}; - const tagKey2 = {name: 'testKey2'}; + const tagKey1 = { name: 'testKey1' }; + const tagKey2 = { name: 'testKey2' }; const tagKeys = [tagKey1, tagKey2]; - const tagValue1 = {value: 'testValue1'}; - const tagValue2 = {value: 'testValue2'}; + const tagValue1 = { value: 'testValue1' }; + const tagValue2 = { value: 'testValue2' }; const tags = new TagMap(); tags.set(tagKey1, tagValue1); @@ -602,18 +705,25 @@ describe('BaseView', () => { before(() => { view = new BaseView( - 'test/view/name', measure, AggregationType.LAST_VALUE, tagKeys, - 'description test'); - - const measurement = {measure, value: 10}; + 'test/view/name', + measure, + AggregationType.LAST_VALUE, + tagKeys, + 'description test' + ); + + const measurement = { measure, value: 10 }; view.recordMeasurement(measurement, tags); }); - it('should not get aggregation data when wrong tags values are given', - () => { - assert.ok(!view.getSnapshot( - [{value: 'wrongTagValue'}, {value: 'wrongTagValue'}])); - }); + it('should not get aggregation data when wrong tags values are given', () => { + assert.ok( + !view.getSnapshot([ + { value: 'wrongTagValue' }, + { value: 'wrongTagValue' }, + ]) + ); + }); it('should not get aggregation data when not enough tags are given', () => { assert.ok(!view.getSnapshot([tagValue1])); diff --git a/packages/opencensus-exporter-instana/package-lock.json b/packages/opencensus-exporter-instana/package-lock.json index a73798f7e..d8a346605 100644 --- a/packages/opencensus-exporter-instana/package-lock.json +++ b/packages/opencensus-exporter-instana/package-lock.json @@ -169,9 +169,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -232,58 +232,6 @@ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -437,16 +385,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -527,9 +465,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "commander": { - "version": "2.15.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz", - "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==" + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -964,32 +902,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } + }, + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" } } }, @@ -1012,21 +955,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1115,29 +1043,34 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } } } }, @@ -1393,15 +1326,10 @@ "handlebars": "^4.1.2" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2246,6 +2174,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "propagate": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/propagate/-/propagate-1.0.0.tgz", @@ -2322,9 +2255,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2357,11 +2290,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2395,9 +2328,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2528,17 +2461,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2563,9 +2496,9 @@ "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=" }, "supports-color": { - "version": "5.4.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", - "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "requires": { "has-flag": "^3.0.0" } @@ -2769,22 +2702,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2962,9 +2896,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-exporter-instana/package.json b/packages/opencensus-exporter-instana/package.json index 5569630cb..27340affe 100644 --- a/packages/opencensus-exporter-instana/package.json +++ b/packages/opencensus-exporter-instana/package.json @@ -54,7 +54,7 @@ "@types/nock": "^10.0.0", "@types/node": "^10.12.12", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nock": "^10.0.0", "nyc": "14.1.1", diff --git a/packages/opencensus-exporter-instana/src/instana.ts b/packages/opencensus-exporter-instana/src/instana.ts index d1bcdff1f..4f551c1b5 100644 --- a/packages/opencensus-exporter-instana/src/instana.ts +++ b/packages/opencensus-exporter-instana/src/instana.ts @@ -14,27 +14,32 @@ * limitations under the License. */ -import {Exporter, ExporterBuffer, ExporterConfig, Span} from '@opencensus/core'; -import {logger, Logger} from '@opencensus/core'; -import {request} from 'http'; - -const spanKindTranslation: {[k: string]: string} = { +import { + Exporter, + ExporterBuffer, + ExporterConfig, + Span, +} from '@opencensus/core'; +import { logger, Logger } from '@opencensus/core'; +import { request } from 'http'; + +const spanKindTranslation: { [k: string]: string } = { CLIENT: 'EXIT', SERVER: 'ENTRY', UNSPECIFIED: 'INTERMEDIATE', }; -type InstanaSpan = { - spanId: string, - parentId: string|undefined, - traceId: string, - timestamp: number, - duration: number, - name: string, - type: string, - error: boolean, - data: {[s: string]: string;} -}; +interface InstanaSpan { + spanId: string; + parentId: string | undefined; + traceId: string; + timestamp: number; + duration: number; + name: string; + type: string; + error: boolean; + data: { [s: string]: string }; +} export interface InstanaExporterOptions extends ExporterConfig { agentHost?: string; @@ -52,9 +57,9 @@ export class InstanaTraceExporter implements Exporter { constructor(options: InstanaExporterOptions = {}) { this.agentHost = - options.agentHost || process.env.INSTANA_AGENT_HOST || '127.0.0.1'; + options.agentHost || process.env.INSTANA_AGENT_HOST || '127.0.0.1'; this.agentPort = - options.agentPort || Number(process.env.INSTANA_AGENT_PORT) || 42699; + options.agentPort || Number(process.env.INSTANA_AGENT_PORT) || 42699; this.transmissionTimeout = options.transmissionTimeout || 10000; this.logger = options.logger || logger.logger(); this.exporterBuffer = new ExporterBuffer(this, options); @@ -84,13 +89,12 @@ export class InstanaTraceExporter implements Exporter { */ publish(spans: Span[]): Promise { try { - return this - .transmit(this.translateRootSpans(spans)) - - .catch(e => e); + return this.transmit(this.translateRootSpans(spans)).catch(e => e); } catch (e) { this.logger.error( - 'Unexpected error in Instana exporter during publish attempt', e); + 'Unexpected error in Instana exporter during publish attempt', + e + ); return Promise.resolve(e); } } @@ -114,13 +118,13 @@ export class InstanaTraceExporter implements Exporter { name: span.name, type: spanKindTranslation[span.kind], error: span.status != null && span.status.code !== 0, - data: Object.keys(span.attributes) - .reduce( - (agg: {[k: string]: string}, key) => { - agg[String(key)] = String(span.attributes[key]); - return agg; - }, - {}) + data: Object.keys(span.attributes).reduce( + (agg: { [k: string]: string }, key) => { + agg[String(key)] = String(span.attributes[key]); + return agg; + }, + {} + ), }; } @@ -128,8 +132,10 @@ export class InstanaTraceExporter implements Exporter { return new Promise((resolve, reject) => { const json = JSON.stringify(spans); this.logger.debug( - 'Transmitting the following spans (%s) to Instana agent', - spans.length, json); + 'Transmitting the following spans (%s) to Instana agent', + spans.length, + json + ); const payload = Buffer.from(json, 'utf8'); const options = { hostname: this.agentHost, @@ -138,27 +144,35 @@ export class InstanaTraceExporter implements Exporter { method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', - 'Content-Length': payload.length - } + 'Content-Length': payload.length, + }, }; - const req = request(options, (res) => { + const req = request(options, res => { res.setEncoding('utf8'); let responseBody = ''; - res.on('data', (chunk) => { + res.on('data', chunk => { responseBody += chunk; }); res.on('end', () => { - if (res.statusCode != null && 200 <= res.statusCode && - res.statusCode <= 299) { + if ( + res.statusCode != null && + 200 <= res.statusCode && + res.statusCode <= 299 + ) { this.logger.debug( - 'Successfully delivered %s spans to Instana agent', - spans.length); + 'Successfully delivered %s spans to Instana agent', + spans.length + ); resolve(); } else { this.logger.error( - 'Delivery of %s spans to Instana agent failed. %s %s: %s', - spans.length, res.statusCode, res.statusMessage, responseBody); + 'Delivery of %s spans to Instana agent failed. %s %s: %s', + spans.length, + res.statusCode, + res.statusMessage, + responseBody + ); reject(); } }); @@ -166,9 +180,12 @@ export class InstanaTraceExporter implements Exporter { req.setTimeout(this.transmissionTimeout, () => req.abort()); - req.on('error', (e) => { + req.on('error', e => { this.logger.error( - 'Failed to deliver %s spans to Instana agent', spans.length, e); + 'Failed to deliver %s spans to Instana agent', + spans.length, + e + ); reject(); }); diff --git a/packages/opencensus-exporter-instana/test/test-instana.ts b/packages/opencensus-exporter-instana/test/test-instana.ts index 490fc2381..2290ac1ae 100644 --- a/packages/opencensus-exporter-instana/test/test-instana.ts +++ b/packages/opencensus-exporter-instana/test/test-instana.ts @@ -14,22 +14,22 @@ * limitations under the License. */ -import {CoreTracer, Span, SpanKind, TracerConfig} from '@opencensus/core'; +import { CoreTracer, Span, SpanKind, TracerConfig } from '@opencensus/core'; import * as assert from 'assert'; import * as nock from 'nock'; -import {InstanaTraceExporter} from '../src/instana'; +import { InstanaTraceExporter } from '../src/instana'; /** Default config for traces tests */ const defaultConfig: TracerConfig = { - samplingRate: 1 + samplingRate: 1, }; /** Run a nock server to replace the Instana agent */ const runNockServer = () => { nock('http://127.0.0.1:42699') - .persist() - .post('/com.instana.plugin.generic.trace') - .reply(200); + .persist() + .post('/com.instana.plugin.generic.trace') + .reply(200); }; /** Checking if tests will use a real network, otherwise run a nock server */ @@ -48,16 +48,16 @@ describe('Instana Exporter', function() { tracer.start(defaultConfig); return tracer - .startRootSpan( - {name: 'root-test'}, - async (rootSpan: Span) => { - const span = rootSpan.startChildSpan( - {name: 'spanTest', kind: SpanKind.CLIENT}); - span.end(); - rootSpan.end(); - return exporter.publish([rootSpan, rootSpan]); - }) - .then(error => assert.ifError(error)); + .startRootSpan({ name: 'root-test' }, async (rootSpan: Span) => { + const span = rootSpan.startChildSpan({ + name: 'spanTest', + kind: SpanKind.CLIENT, + }); + span.end(); + rootSpan.end(); + return exporter.publish([rootSpan, rootSpan]); + }) + .then(error => assert.ifError(error)); }); }); }); diff --git a/packages/opencensus-exporter-jaeger/package-lock.json b/packages/opencensus-exporter-jaeger/package-lock.json index e7a7c9537..b9b3c28f2 100644 --- a/packages/opencensus-exporter-jaeger/package-lock.json +++ b/packages/opencensus-exporter-jaeger/package-lock.json @@ -191,9 +191,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -254,58 +254,6 @@ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==" }, - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -454,16 +402,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -544,9 +482,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -990,32 +928,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } + }, + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" } } }, @@ -1038,21 +981,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1141,23 +1069,40 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "lodash": { + "version": "4.17.11", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", + "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + } } }, "invert-kv": { @@ -1403,15 +1348,10 @@ "xorshift": "^0.2.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2318,6 +2258,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "propagate": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/propagate/-/propagate-1.0.0.tgz", @@ -2387,9 +2332,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2422,11 +2367,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2460,9 +2405,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2598,17 +2543,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2841,22 +2786,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" } }, "tsutils": { @@ -3034,9 +2980,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-exporter-jaeger/package.json b/packages/opencensus-exporter-jaeger/package.json index ecf330573..292855b35 100644 --- a/packages/opencensus-exporter-jaeger/package.json +++ b/packages/opencensus-exporter-jaeger/package.json @@ -53,7 +53,7 @@ "@types/nock": "^10.0.0", "@types/node": "^10.12.12", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nock": "^10.0.0", "nyc": "^14.0.0", diff --git a/packages/opencensus-exporter-jaeger/src/jaeger-driver/index.ts b/packages/opencensus-exporter-jaeger/src/jaeger-driver/index.ts index 3cef08028..fbc26a04a 100644 --- a/packages/opencensus-exporter-jaeger/src/jaeger-driver/index.ts +++ b/packages/opencensus-exporter-jaeger/src/jaeger-driver/index.ts @@ -14,73 +14,73 @@ * limitations under the License. */ -import {Link, LinkType, Span} from '@opencensus/core'; +import { Link, LinkType, Span } from '@opencensus/core'; // tslint:disable-next-line:variable-name -export const UDPSender = - require('jaeger-client/dist/src/reporters/udp_sender').default; +export const UDPSender = require('jaeger-client/dist/src/reporters/udp_sender') + .default; // tslint:disable-next-line:variable-name export const Utils = require('jaeger-client/dist/src/util').default; // tslint:disable-next-line:variable-name export const ThriftUtils = require('jaeger-client/dist/src/thrift').default; -export type TagValue = string|number|boolean; +export type TagValue = string | number | boolean; -export type Tag = { - key: string, - value: TagValue -}; +export interface Tag { + key: string; + value: TagValue; +} -export type Log = { - timestamp: number, - fields: Tag[] -}; +export interface Log { + timestamp: number; + fields: Tag[]; +} export type SenderCallback = (numSpans: number, err?: string) => void; -export type ThriftProcess = { - serviceName: string, - tags: ThriftTag[] -}; +export interface ThriftProcess { + serviceName: string; + tags: ThriftTag[]; +} -export type ThriftTag = { - key: string, - vType: string, - vStr: string, - vDouble: number, - vBool: boolean -}; +export interface ThriftTag { + key: string; + vType: string; + vStr: string; + vDouble: number; + vBool: boolean; +} -export type ThriftLog = { - timestamp: number, - fields: ThriftTag[] -}; +export interface ThriftLog { + timestamp: number; + fields: ThriftTag[]; +} export enum ThriftReferenceType { CHILD_OF = 'CHILD_OF', - FOLLOWS_FROM = 'FOLLOWS_FROM' + FOLLOWS_FROM = 'FOLLOWS_FROM', +} + +export interface ThriftReference { + traceIdLow: Buffer; + traceIdHigh: Buffer; + spanId: Buffer; + refType: ThriftReferenceType; } -export type ThriftReference = { - traceIdLow: Buffer, - traceIdHigh: Buffer, - spanId: Buffer, - refType: ThriftReferenceType -}; - -export type ThriftSpan = { - traceIdLow: Buffer, - traceIdHigh: Buffer, - spanId: Buffer, - parentSpanId: string|Buffer, - operationName: string, - references: ThriftReference[], - flags: number, - startTime: number, // milliseconds - duration: number, // milliseconds - tags: ThriftTag[], - logs: ThriftLog[], -}; +export interface ThriftSpan { + traceIdLow: Buffer; + traceIdHigh: Buffer; + spanId: Buffer; + parentSpanId: string | Buffer; + operationName: string; + references: ThriftReference[]; + flags: number; + startTime: number; // milliseconds + duration: number; // milliseconds + tags: ThriftTag[]; + logs: ThriftLog[]; +} /** * Translate opencensus Span to Jaeger Thrift Span @@ -90,7 +90,7 @@ export function spanToThrift(span: Span): ThriftSpan { const tags: Tag[] = []; if (span.attributes) { Object.keys(span.attributes).forEach(key => { - tags.push({'key': key, 'value': span.attributes[key]}); + tags.push({ key, value: span.attributes[key] }); }); } @@ -100,8 +100,8 @@ export function spanToThrift(span: Span): ThriftSpan { logs.push({ timestamp: msg.timestamp, fields: [ - {'key': 'message.id', 'value': msg.id}, - {'key': 'message.type', 'value': msg.type} + { key: 'message.id', value: msg.id }, + { key: 'message.type', value: msg.type }, ], }); }); @@ -111,9 +111,9 @@ export function spanToThrift(span: Span): ThriftSpan { span.annotations.forEach(ann => { const tags: Tag[] = []; Object.keys(ann.attributes).forEach(key => { - tags.push({'key': key, 'value': ann.attributes[key]}); + tags.push({ key, value: ann.attributes[key] }); }); - tags.push({'key': 'description', 'value': ann.description}); + tags.push({ key: 'description', value: ann.description }); logs.push({ timestamp: ann.timestamp, fields: tags, @@ -121,12 +121,13 @@ export function spanToThrift(span: Span): ThriftSpan { }); } - const parentSpan: string|Buffer = span.parentSpanId ? - Utils.encodeInt64(span.parentSpanId) : - ThriftUtils.emptyBuffer; + const parentSpan: string | Buffer = span.parentSpanId + ? Utils.encodeInt64(span.parentSpanId) + : ThriftUtils.emptyBuffer; - const traceId = - `00000000000000000000000000000000${span.spanContext.traceId}`.slice(-32); + const traceId = `00000000000000000000000000000000${ + span.spanContext.traceId + }`.slice(-32); const high = traceId.slice(0, 16); const low = traceId.slice(16); @@ -141,9 +142,8 @@ export function spanToThrift(span: Span): ThriftSpan { operationName: span.name, references: getThriftReference(span.links), flags: span.spanContext.options || 0x1, - startTime: - Utils.encodeInt64(span.startTime.getTime() * 1000), // to microseconds - duration: Utils.encodeInt64(span.duration * 1000), // to microseconds + startTime: Utils.encodeInt64(span.startTime.getTime() * 1000), // to microseconds + duration: Utils.encodeInt64(span.duration * 1000), // to microseconds tags: spanTags, logs: spanLogs, }; @@ -151,25 +151,24 @@ export function spanToThrift(span: Span): ThriftSpan { function getThriftReference(links: Link[]): ThriftReference[] { return links - .map( - (link): - ThriftReference| - null => { - const refType = getThriftType(link.type); - if (!refType) return null; - - const traceId = - `00000000000000000000000000000000${link.traceId}`.slice( - -32); - const traceIdHigh = Utils.encodeInt64(traceId.slice(0, 16)); - const traceIdLow = Utils.encodeInt64(traceId.slice(16)); - const spanId = Utils.encodeInt64(link.spanId); - return {traceIdLow, traceIdHigh, spanId, refType}; - }) - .filter(ref => !!ref) as ThriftReference[]; + .map( + (link): ThriftReference | null => { + const refType = getThriftType(link.type); + if (!refType) return null; + + const traceId = `00000000000000000000000000000000${link.traceId}`.slice( + -32 + ); + const traceIdHigh = Utils.encodeInt64(traceId.slice(0, 16)); + const traceIdLow = Utils.encodeInt64(traceId.slice(16)); + const spanId = Utils.encodeInt64(link.spanId); + return { traceIdLow, traceIdHigh, spanId, refType }; + } + ) + .filter(ref => !!ref) as ThriftReference[]; } -function getThriftType(type: number): ThriftReferenceType|null { +function getThriftType(type: number): ThriftReferenceType | null { if (type === LinkType.CHILD_LINKED_SPAN) { return ThriftReferenceType.CHILD_OF; } diff --git a/packages/opencensus-exporter-jaeger/src/jaeger.ts b/packages/opencensus-exporter-jaeger/src/jaeger.ts index 1a4aeaa18..1c90aaeb0 100644 --- a/packages/opencensus-exporter-jaeger/src/jaeger.ts +++ b/packages/opencensus-exporter-jaeger/src/jaeger.ts @@ -14,10 +14,18 @@ * limitations under the License. */ -import {Exporter, ExporterConfig, Span} from '@opencensus/core'; -import {logger, Logger} from '@opencensus/core'; +import { Exporter, ExporterConfig, Span } from '@opencensus/core'; +import { logger, Logger } from '@opencensus/core'; import * as os from 'os'; -import {spanToThrift, Tag, TagValue, ThriftProcess, ThriftUtils, UDPSender, Utils} from './jaeger-driver'; +import { + spanToThrift, + Tag, + TagValue, + ThriftProcess, + ThriftUtils, + UDPSender, + Utils, +} from './jaeger-driver'; const DEFAULT_BUFFER_FLUSH_INTERVAL_MILLIS = 1000; const DEFAULT_BUFFER_SIZE = 1000; @@ -49,10 +57,10 @@ try { export class JaegerTraceExporter implements Exporter { // Name of the tag used to report client version. static readonly JAEGER_OPENCENSUS_EXPORTER_VERSION_TAG_KEY = - 'opencensus.exporter.jaeger.version'; + 'opencensus.exporter.jaeger.version'; // host name of the process. static readonly TRACER_HOSTNAME_TAG_KEY = - 'opencensus.exporter.jaeger.hostname'; + 'opencensus.exporter.jaeger.hostname'; // ip of the process. static readonly PROCESS_IP = 'ip'; @@ -72,15 +80,15 @@ export class JaegerTraceExporter implements Exporter { constructor(options: JaegerTraceExporterOptions) { this.logger = options.logger || logger.logger(); this.bufferTimeout = - options.bufferTimeout || DEFAULT_BUFFER_FLUSH_INTERVAL_MILLIS; + options.bufferTimeout || DEFAULT_BUFFER_FLUSH_INTERVAL_MILLIS; this.bufferSize = options.bufferSize || DEFAULT_BUFFER_SIZE; this.sender = new UDPSender(options); const tags: Tag[] = options.tags || []; const defaultTags: Record = {}; - defaultTags[JaegerTraceExporter - .JAEGER_OPENCENSUS_EXPORTER_VERSION_TAG_KEY] = - `opencensus-exporter-jaeger-${pjsonVersion}`; + defaultTags[ + JaegerTraceExporter.JAEGER_OPENCENSUS_EXPORTER_VERSION_TAG_KEY + ] = `opencensus-exporter-jaeger-${pjsonVersion}`; defaultTags[JaegerTraceExporter.TRACER_HOSTNAME_TAG_KEY] = os.hostname(); defaultTags[JaegerTraceExporter.PROCESS_IP] = Utils.myIp(); @@ -93,7 +101,6 @@ export class JaegerTraceExporter implements Exporter { this.sender.setProcess(this.process); } - // TODO: should be evaluated if onEndSpan should also return a Promise. /** @@ -108,21 +115,21 @@ export class JaegerTraceExporter implements Exporter { // UDPSender buffer is limited by maxPacketSize this.addSpanToSenderBuffer(span) - .then(result => { - this.addToBuffer(span, result as number); - for (const localSpan of span.spans) { - this.addSpanToSenderBuffer(localSpan) - .then(result => { - this.addToBuffer(localSpan, result as number); - }) - .catch(err => { - return; - }); - } - }) - .catch(err => { - return; - }); + .then(result => { + this.addToBuffer(span, result as number); + for (const localSpan of span.spans) { + this.addSpanToSenderBuffer(localSpan) + .then(result => { + this.addToBuffer(localSpan, result as number); + }) + .catch(err => { + return; + }); + } + }) + .catch(err => { + return; + }); // Set a buffer timeout this.setBufferTimeout(); diff --git a/packages/opencensus-exporter-jaeger/test/test-jaeger.ts b/packages/opencensus-exporter-jaeger/test/test-jaeger.ts index cbacd9a6a..a2ed879a0 100644 --- a/packages/opencensus-exporter-jaeger/test/test-jaeger.ts +++ b/packages/opencensus-exporter-jaeger/test/test-jaeger.ts @@ -14,15 +14,20 @@ * limitations under the License. */ -import {CoreTracer, LinkType, logger} from '@opencensus/core'; +import { CoreTracer, LinkType, logger } from '@opencensus/core'; import * as assert from 'assert'; -import {JaegerTraceExporter, JaegerTraceExporterOptions,} from '../src/'; -import {spanToThrift, ThriftReferenceType, ThriftUtils, UDPSender} from '../src/jaeger-driver'; -import {ThriftProcess} from '../src/jaeger-driver'; -import {SenderCallback} from '../src/jaeger-driver'; +import { JaegerTraceExporter, JaegerTraceExporterOptions } from '../src/'; +import { + spanToThrift, + ThriftReferenceType, + ThriftUtils, + UDPSender, +} from '../src/jaeger-driver'; +import { ThriftProcess } from '../src/jaeger-driver'; +import { SenderCallback } from '../src/jaeger-driver'; -const DEFAULT_BUFFER_TIMEOUT = 10; // time in milliseconds +const DEFAULT_BUFFER_TIMEOUT = 10; // time in milliseconds /** * Controls if the tests will use a real network or not @@ -38,17 +43,16 @@ describe('Jaeger Exporter', () => { let exporter: JaegerTraceExporter; let tracer: CoreTracer; - before(() => { testLogger.debug('dryrun=%s', dryrun); exporterOptions = { serviceName: 'opencensus-exporter-jaeger', host: 'localhost', port: 6832, - tags: [{key: 'opencensus-exporter-jaeger', value: '0.0.1'}], + tags: [{ key: 'opencensus-exporter-jaeger', value: '0.0.1' }], bufferTimeout: DEFAULT_BUFFER_TIMEOUT, logger: testLogger, - maxPacketSize: 1000 + maxPacketSize: 1000, }; }); @@ -58,7 +62,7 @@ describe('Jaeger Exporter', () => { mockUDPSender(exporter); } tracer = new CoreTracer(); - tracer.start({samplingRate: 1}); + tracer.start({ samplingRate: 1 }); tracer.registerSpanEventListener(exporter); }); @@ -78,14 +82,19 @@ describe('Jaeger Exporter', () => { let testExporterVersionSeen = false; let testHostnameSeen = false; let testProcessIpSeen = false; - process.tags.forEach((tag) => { - if (tag.key === 'opencensus-exporter-jaeger' && - tag.vType === 'STRING' && tag.vStr === '0.0.1') { + process.tags.forEach(tag => { + if ( + tag.key === 'opencensus-exporter-jaeger' && + tag.vType === 'STRING' && + tag.vStr === '0.0.1' + ) { testVersionSeen = true; return; } - if (tag.key === - JaegerTraceExporter.JAEGER_OPENCENSUS_EXPORTER_VERSION_TAG_KEY) { + if ( + tag.key === + JaegerTraceExporter.JAEGER_OPENCENSUS_EXPORTER_VERSION_TAG_KEY + ) { testExporterVersionSeen = true; return; } @@ -93,28 +102,33 @@ describe('Jaeger Exporter', () => { testHostnameSeen = true; return; } - if (tag.key === JaegerTraceExporter.PROCESS_IP && - tag.vType === 'STRING') { + if ( + tag.key === JaegerTraceExporter.PROCESS_IP && + tag.vType === 'STRING' + ) { testProcessIpSeen = true; return; } }); assert.ok( - testVersionSeen && testExporterVersionSeen && testHostnameSeen && - testProcessIpSeen); + testVersionSeen && + testExporterVersionSeen && + testHostnameSeen && + testProcessIpSeen + ); }); }); /* Should export spans to Jaeger */ describe('test spans are valid', () => { it('should encode as thrift', () => { - return tracer.startRootSpan({name: 'root-s01'}, (rootSpan) => { - const span = tracer.startChildSpan({name: 'child-s01'}); + return tracer.startRootSpan({ name: 'root-s01' }, rootSpan => { + const span = tracer.startChildSpan({ name: 'child-s01' }); span.addAttribute('testBool', true); span.addAttribute('testString', 'here'); span.addAttribute('testNum', 3.142); span.addAnnotation('something happened', { - 'error': true, + error: true, }); const traceIdHigh = '6e0c63257de34c92'; const traceIdLow = 'bf9efcd03927272e'; @@ -133,19 +147,28 @@ describe('Jaeger Exporter', () => { let testBoolSeen = false; let testStringSeen = false; let testNumSeen = false; - thriftSpan.tags.forEach((tag) => { - if (tag.key === 'testBool' && tag.vType === 'BOOL' && - tag.vBool === true) { + thriftSpan.tags.forEach(tag => { + if ( + tag.key === 'testBool' && + tag.vType === 'BOOL' && + tag.vBool === true + ) { testBoolSeen = true; return; } - if (tag.key === 'testString' && tag.vType === 'STRING' && - tag.vStr === 'here') { + if ( + tag.key === 'testString' && + tag.vType === 'STRING' && + tag.vStr === 'here' + ) { testStringSeen = true; return; } - if (tag.key === 'testNum' && tag.vType === 'DOUBLE' && - tag.vDouble === 3.142) { + if ( + tag.key === 'testNum' && + tag.vType === 'DOUBLE' && + tag.vDouble === 3.142 + ) { testNumSeen = true; return; } @@ -159,28 +182,34 @@ describe('Jaeger Exporter', () => { refType: ThriftReferenceType.CHILD_OF, traceIdHigh: Buffer.from([110, 12, 99, 37, 125, 227, 76, 146]), traceIdLow: Buffer.from([191, 158, 252, 208, 57, 39, 39, 46]), - spanId: Buffer.from([110, 12, 99, 37, 125, 227, 76, 146]) + spanId: Buffer.from([110, 12, 99, 37, 125, 227, 76, 146]), }, { refType: ThriftReferenceType.FOLLOWS_FROM, traceIdHigh: Buffer.from([110, 12, 99, 37, 125, 227, 76, 146]), traceIdLow: Buffer.from([191, 158, 252, 208, 57, 39, 39, 46]), - spanId: Buffer.from([110, 12, 99, 37, 125, 227, 76, 146]) - } + spanId: Buffer.from([110, 12, 99, 37, 125, 227, 76, 146]), + }, ]); assert.strictEqual(thriftSpan.logs.length, 1); - thriftSpan.logs.forEach((log) => { + thriftSpan.logs.forEach(log => { let descriptionSeen = false; let errorSeen = false; - log.fields.forEach((field) => { - if (field.key === 'description' && field.vType === 'STRING' && - field.vStr === 'something happened') { + log.fields.forEach(field => { + if ( + field.key === 'description' && + field.vType === 'STRING' && + field.vStr === 'something happened' + ) { descriptionSeen = true; return; } - if (field.key === 'error' && field.vType === 'BOOL' && - field.vBool === true) { + if ( + field.key === 'error' && + field.vType === 'BOOL' && + field.vBool === true + ) { errorSeen = true; return; } @@ -194,24 +223,23 @@ describe('Jaeger Exporter', () => { /* Should export spans to Jaeger */ describe('publish()', () => { it('should export spans to Jaeger', () => { - return tracer.startRootSpan({name: 'root-s01'}, (rootSpan) => { - const span = tracer.startChildSpan({name: 'child-s01'}); + return tracer.startRootSpan({ name: 'root-s01' }, rootSpan => { + const span = tracer.startChildSpan({ name: 'child-s01' }); span.end(); rootSpan.end(); - return exporter.publish([rootSpan]).then((result) => { + return exporter.publish([rootSpan]).then(result => { assert.strictEqual(result, 2); }); }); }); }); - describe('addToBuffer force flush by timeout ', () => { - it('should flush by timeout', (done) => { + it('should flush by timeout', done => { assert.strictEqual(exporter.queue.length, 0); - tracer.startRootSpan({name: 'root-s02'}, (rootSpan) => { - const span = tracer.startChildSpan({name: 'child-s02'}); + tracer.startRootSpan({ name: 'root-s02' }, rootSpan => { + const span = tracer.startChildSpan({ name: 'child-s02' }); span.end(); rootSpan.end(); @@ -225,7 +253,6 @@ describe('Jaeger Exporter', () => { }); }); - function mockUDPSender(exporter: JaegerTraceExporter) { // Get the process of the current sender and pass to the mock sender. The // process is constructed and attached to the sender at exporter construction @@ -236,15 +263,16 @@ function mockUDPSender(exporter: JaegerTraceExporter) { exporter.sender.setProcess(process); } - class MockedUDPSender extends UDPSender { // tslint:disable-next-line:no-any queue: any = []; // Holds the initialized process information. Name matches the associated // UDPSender property. - _process: - ThriftProcess = {serviceName: 'opencensus-exporter-jaeger', tags: []}; + _process: ThriftProcess = { + serviceName: 'opencensus-exporter-jaeger', + tags: [], + }; setProcess(process: ThriftProcess): void { this._process = process; diff --git a/packages/opencensus-exporter-ocagent/package-lock.json b/packages/opencensus-exporter-ocagent/package-lock.json index 551ac8f0a..1752bd1e4 100644 --- a/packages/opencensus-exporter-ocagent/package-lock.json +++ b/packages/opencensus-exporter-ocagent/package-lock.json @@ -263,9 +263,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "2.1.1", @@ -364,11 +364,6 @@ "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=" }, - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, "async-each": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.1.tgz", @@ -379,40 +374,6 @@ "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==" }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "http://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -712,16 +673,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.5.1.tgz", "integrity": "sha512-fKFIKXaYiL1exImwJ0AhR/6jxFPSKQBk2ayV5NiNoruUs2+rxC2kNw0EG+1Z9dugZRdCrppskQ8DN2cyaUM1Hw==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "class-utils": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", @@ -827,9 +778,9 @@ "integrity": "sha1-nLFpkX7F0SwHNtPoaFdG3xyt93g=" }, "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -1413,8 +1364,7 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true, - "optional": true + "bundled": true }, "aproba": { "version": "1.2.0", @@ -1432,13 +1382,11 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true, - "optional": true + "bundled": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, - "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -1451,18 +1399,15 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "concat-map": { "version": "0.0.1", - "bundled": true, - "optional": true + "bundled": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "core-util-is": { "version": "1.0.2", @@ -1565,8 +1510,7 @@ }, "inherits": { "version": "2.0.3", - "bundled": true, - "optional": true + "bundled": true }, "ini": { "version": "1.3.5", @@ -1576,7 +1520,6 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, - "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -1589,20 +1532,17 @@ "minimatch": { "version": "3.0.4", "bundled": true, - "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true, - "optional": true + "bundled": true }, "minipass": { "version": "2.2.4", "bundled": true, - "optional": true, "requires": { "safe-buffer": "^5.1.1", "yallist": "^3.0.0" @@ -1619,7 +1559,6 @@ "mkdirp": { "version": "0.5.1", "bundled": true, - "optional": true, "requires": { "minimist": "0.0.8" } @@ -1692,8 +1631,7 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true, - "optional": true + "bundled": true }, "object-assign": { "version": "4.1.1", @@ -1703,7 +1641,6 @@ "once": { "version": "1.4.0", "bundled": true, - "optional": true, "requires": { "wrappy": "1" } @@ -1779,8 +1716,7 @@ }, "safe-buffer": { "version": "5.1.1", - "bundled": true, - "optional": true + "bundled": true }, "safer-buffer": { "version": "2.1.2", @@ -1810,7 +1746,6 @@ "string-width": { "version": "1.0.2", "bundled": true, - "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -1828,7 +1763,6 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, - "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -1867,13 +1801,11 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true, - "optional": true + "bundled": true }, "yallist": { "version": "3.0.2", - "bundled": true, - "optional": true + "bundled": true } } }, @@ -2417,23 +2349,28 @@ } }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" + }, "pify": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", @@ -2467,14 +2404,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -2597,22 +2526,22 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { @@ -2621,6 +2550,16 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, "is-fullwidth-code-point": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", @@ -2646,17 +2585,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } } @@ -3036,15 +2975,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -4285,6 +4219,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "process-nextick-args": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", @@ -4464,11 +4403,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -4512,9 +4451,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -5044,22 +4983,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" } }, "tsutils": { diff --git a/packages/opencensus-exporter-ocagent/package.json b/packages/opencensus-exporter-ocagent/package.json index 0fd720523..9c6b0aefe 100644 --- a/packages/opencensus-exporter-ocagent/package.json +++ b/packages/opencensus-exporter-ocagent/package.json @@ -54,7 +54,7 @@ "@types/uuid": "^3.4.3", "codecov": "^3.4.0", "google-proto-files": "^1.0.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nodemon": "^1.18.7", "nyc": "^14.0.0", diff --git a/packages/opencensus-exporter-ocagent/src/adapters.ts b/packages/opencensus-exporter-ocagent/src/adapters.ts index 3cd5a0b29..e11df6253 100644 --- a/packages/opencensus-exporter-ocagent/src/adapters.ts +++ b/packages/opencensus-exporter-ocagent/src/adapters.ts @@ -14,25 +14,37 @@ * limitations under the License. */ -import {Annotation, Attributes, Link, LinkType, MessageEvent, MessageEventType, Span, SpanKind} from '@opencensus/core'; -import {google, opencensus} from './types'; +import { + Annotation, + Attributes, + Link, + LinkType, + MessageEvent, + MessageEventType, + Span, + SpanKind, +} from '@opencensus/core'; +import { google, opencensus } from './types'; /** * Adapts a string to a `opencensus.proto.trace.v1.TruncatableString` type. * @param value string * @returns opencensus.proto.trace.v1.TruncatableString */ -const stringToTruncatableString = - (value: string): opencensus.proto.trace.v1.TruncatableString => { - return {value, truncatedByteCount: null}; - }; +const stringToTruncatableString = ( + value: string +): opencensus.proto.trace.v1.TruncatableString => { + return { value, truncatedByteCount: null }; +}; /** * Adapts a millis number or Date object to a `google.protobuf.Timestamp` type. * @param millis Date | number * @returns google.protobuf.Timestamp */ -const millisToTimestamp = (millis: Date|number): google.protobuf.Timestamp => { +const millisToTimestamp = ( + millis: Date | number +): google.protobuf.Timestamp => { let milliseconds = 0; if (typeof millis === 'number') { milliseconds = millis; @@ -43,7 +55,7 @@ const millisToTimestamp = (millis: Date|number): google.protobuf.Timestamp => { const seconds = Math.floor(milliseconds / 1000); const nanos = (milliseconds % 1000) * 1000000; - return {seconds, nanos}; + return { seconds, nanos }; }; /** @@ -52,7 +64,7 @@ const millisToTimestamp = (millis: Date|number): google.protobuf.Timestamp => { * @param hex string * @returns Uint8Array */ -const hexStringToUint8Array = (hex: string): Uint8Array|null => { +const hexStringToUint8Array = (hex: string): Uint8Array | null => { if (!hex) return null; const match = hex.match(/.{1,2}/g); if (!match) return null; @@ -64,42 +76,46 @@ const hexStringToUint8Array = (hex: string): Uint8Array|null => { * Adapts a string spanKind value to a `opencensus.proto.trace.v1.Span.SpanKind` * enum type. */ -const spanKindToEnum = - (kind: SpanKind): opencensus.proto.trace.v1.Span.SpanKind => { - switch (kind) { - case SpanKind.SERVER: { - return opencensus.proto.trace.v1.Span.SpanKind.SERVER; - } - case SpanKind.CLIENT: { - return opencensus.proto.trace.v1.Span.SpanKind.CLIENT; - } - default: { - return opencensus.proto.trace.v1.Span.SpanKind.SPAN_KIND_UNSPECIFIED; - } - } - }; +const spanKindToEnum = ( + kind: SpanKind +): opencensus.proto.trace.v1.Span.SpanKind => { + switch (kind) { + case SpanKind.SERVER: { + return opencensus.proto.trace.v1.Span.SpanKind.SERVER; + } + case SpanKind.CLIENT: { + return opencensus.proto.trace.v1.Span.SpanKind.CLIENT; + } + default: { + return opencensus.proto.trace.v1.Span.SpanKind.SPAN_KIND_UNSPECIFIED; + } + } +}; /** * Adapts Attributes to a `opencensus.proto.trace.v1.Span.Attributes` type. * @param attributes Attributes * @returns opencensus.proto.trace.v1.Span.Attributes */ -const adaptAttributes = (attributes: Attributes, - droppedAttributesCount: number): - opencensus.proto.trace.v1.Span.Attributes|null => { +const adaptAttributes = ( + attributes: Attributes, + droppedAttributesCount: number +): opencensus.proto.trace.v1.Span.Attributes | null => { if (!attributes) { return null; } - const attributeMap: - Record = {}; + const attributeMap: Record< + string, + opencensus.proto.trace.v1.AttributeValue + > = {}; - Object.getOwnPropertyNames(attributes).forEach((name) => { + Object.getOwnPropertyNames(attributes).forEach(name => { const value = attributes[name]; - let stringValue: opencensus.proto.trace.v1.TruncatableString|null = null; - let intValue: number|null = null; - let boolValue: boolean|null = null; + let stringValue: opencensus.proto.trace.v1.TruncatableString | null = null; + let intValue: number | null = null; + let boolValue: boolean | null = null; switch (typeof value) { case 'number': { @@ -111,7 +127,7 @@ const adaptAttributes = (attributes: Attributes, break; } case 'string': { - stringValue = {value: value as string, truncatedByteCount: null}; + stringValue = { value: value as string, truncatedByteCount: null }; break; } default: { @@ -119,10 +135,10 @@ const adaptAttributes = (attributes: Attributes, } } - attributeMap[name] = {stringValue, intValue, boolValue}; + attributeMap[name] = { stringValue, intValue, boolValue }; }); - return {attributeMap, droppedAttributesCount}; + return { attributeMap, droppedAttributesCount }; }; /** @@ -131,19 +147,20 @@ const adaptAttributes = (attributes: Attributes, * @param value * @return opencensus.proto.trace.v1.Span.TimeEvent.MessageEvent.Type */ -const adaptMessageEventType = (type: MessageEventType): opencensus.proto.trace - .v1.Span.TimeEvent.MessageEvent.Type => { +const adaptMessageEventType = ( + type: MessageEventType +): opencensus.proto.trace.v1.Span.TimeEvent.MessageEvent.Type => { switch (type) { case MessageEventType.SENT: { return opencensus.proto.trace.v1.Span.TimeEvent.MessageEvent.Type.SENT; } case MessageEventType.RECEIVED: { return opencensus.proto.trace.v1.Span.TimeEvent.MessageEvent.Type - .RECEIVED; + .RECEIVED; } default: { return opencensus.proto.trace.v1.Span.TimeEvent.MessageEvent.Type - .TYPE_UNSPECIFIED; + .TYPE_UNSPECIFIED; } } }; @@ -156,44 +173,46 @@ const adaptMessageEventType = (type: MessageEventType): opencensus.proto.trace * @param messageEvents MessageEvent[] * @returns opencensus.proto.trace.v1.Span.TimeEvents */ -const adaptTimeEvents = - (annotations: Annotation[], messageEvents: MessageEvent[], - droppedAnnotationsCount: number, droppedMessageEventsCount: number): - opencensus.proto.trace.v1.Span.TimeEvents => { - const timeEvents: opencensus.proto.trace.v1.Span.TimeEvent[] = []; +const adaptTimeEvents = ( + annotations: Annotation[], + messageEvents: MessageEvent[], + droppedAnnotationsCount: number, + droppedMessageEventsCount: number +): opencensus.proto.trace.v1.Span.TimeEvents => { + const timeEvents: opencensus.proto.trace.v1.Span.TimeEvent[] = []; - if (annotations) { - annotations.forEach(annotation => { - timeEvents.push({ - time: null, - annotation: { - description: stringToTruncatableString(annotation.description), - attributes: adaptAttributes(annotation.attributes, 0) - } - }); - }); - } + if (annotations) { + annotations.forEach(annotation => { + timeEvents.push({ + time: null, + annotation: { + description: stringToTruncatableString(annotation.description), + attributes: adaptAttributes(annotation.attributes, 0), + }, + }); + }); + } - if (messageEvents) { - messageEvents.forEach(messageEvent => { - timeEvents.push({ - time: millisToTimestamp(messageEvent.timestamp), - messageEvent: { - id: messageEvent.id, - type: adaptMessageEventType(messageEvent.type), - uncompressedSize: messageEvent.uncompressedSize || 0, - compressedSize: messageEvent.compressedSize || 0 - } - }); - }); - } + if (messageEvents) { + messageEvents.forEach(messageEvent => { + timeEvents.push({ + time: millisToTimestamp(messageEvent.timestamp), + messageEvent: { + id: messageEvent.id, + type: adaptMessageEventType(messageEvent.type), + uncompressedSize: messageEvent.uncompressedSize || 0, + compressedSize: messageEvent.compressedSize || 0, + }, + }); + }); + } - return { - timeEvent: timeEvents, - droppedAnnotationsCount, - droppedMessageEventsCount - }; - }; + return { + timeEvent: timeEvents, + droppedAnnotationsCount, + droppedMessageEventsCount, + }; +}; /** * Adapts a traceState string to a `opencensus.proto.trace.v1.Span.Tracestate` @@ -202,16 +221,20 @@ const adaptTimeEvents = * @param traceState string * @returns opencensus.proto.trace.v1.Span.Tracestate */ -const adaptTraceState = - (traceState?: string): opencensus.proto.trace.v1.Span.Tracestate => { - const entries: opencensus.proto.trace.v1.Span.Tracestate.Entry[]|null = - !traceState ? null : traceState.split(',').map(state => { - const [key, value] = state.split('='); - return {key, value}; - }); +const adaptTraceState = ( + traceState?: string +): opencensus.proto.trace.v1.Span.Tracestate => { + const entries: + | opencensus.proto.trace.v1.Span.Tracestate.Entry[] + | null = !traceState + ? null + : traceState.split(',').map(state => { + const [key, value] = state.split('='); + return { key, value }; + }); - return {entries}; - }; + return { entries }; +}; /** * Adapts a link to a `opencensus.proto.trace.v1.Span.Link` type. @@ -239,7 +262,7 @@ const adaptLink = (link: Link): opencensus.proto.trace.v1.Span.Link => { const attributes = adaptAttributes(link.attributes, 0); - return {traceId, spanId, type, attributes}; + return { traceId, spanId, type, attributes }; }; /** @@ -247,9 +270,11 @@ const adaptLink = (link: Link): opencensus.proto.trace.v1.Span.Link => { * @param links Link[] * @returns opencensus.proto.trace.v1.Span.Links */ -const adaptLinks = (links: Link[] = [], droppedLinksCount: number): - opencensus.proto.trace.v1.Span.Links => { - return {link: links.map(adaptLink), droppedLinksCount}; +const adaptLinks = ( + links: Link[] = [], + droppedLinksCount: number +): opencensus.proto.trace.v1.Span.Links => { + return { link: links.map(adaptLink), droppedLinksCount }; }; /** @@ -257,7 +282,7 @@ const adaptLinks = (links: Link[] = [], droppedLinksCount: number): * @param value boolean * @returns google.protobuf.BoolValue */ -const adaptBoolean = (value: boolean): google.protobuf.BoolValue => ({value}); +const adaptBoolean = (value: boolean): google.protobuf.BoolValue => ({ value }); /** * Adapts a span to a `opencensus.proto.trace.v1.Span` type. @@ -275,10 +300,13 @@ export const adaptSpan = (span: Span): opencensus.proto.trace.v1.Span => { startTime: millisToTimestamp(span.startTime), endTime: millisToTimestamp(span.endTime), attributes: adaptAttributes(span.attributes, span.droppedAttributesCount), - stackTrace: null, // Unsupported by nodejs + stackTrace: null, // Unsupported by nodejs timeEvents: adaptTimeEvents( - span.annotations, span.messageEvents, span.droppedAnnotationsCount, - span.droppedMessageEventsCount), + span.annotations, + span.messageEvents, + span.droppedAnnotationsCount, + span.droppedMessageEventsCount + ), links: adaptLinks(span.links, span.droppedLinksCount), status: span.status, sameProcessAsParentSpan: adaptBoolean(!span.remoteParent), @@ -305,7 +333,7 @@ export interface CreateNodeOptions { coreVersion: string; hostName: string; processStartTimeMillis: number; - attributes: Record|undefined; + attributes: Record | undefined; } /** @@ -314,20 +342,21 @@ export interface CreateNodeOptions { * @param options CreateNodeOptions * @returns opencensus.proto.agent.common.v1.Node */ -export const createNode = (options: CreateNodeOptions): - opencensus.proto.agent.common.v1.Node => { +export const createNode = ( + options: CreateNodeOptions +): opencensus.proto.agent.common.v1.Node => { return { identifier: { hostName: options.hostName, pid: process.pid, - startTimestamp: millisToTimestamp(options.processStartTimeMillis) + startTimestamp: millisToTimestamp(options.processStartTimeMillis), }, libraryInfo: { language: opencensus.proto.agent.common.v1.LibraryInfo.Language.NODE_JS, exporterVersion: options.exporterVersion, - coreLibraryVersion: options.coreVersion + coreLibraryVersion: options.coreVersion, }, - serviceInfo: {name: options.serviceName}, - attributes: options.attributes + serviceInfo: { name: options.serviceName }, + attributes: options.attributes, }; }; diff --git a/packages/opencensus-exporter-ocagent/src/ocagent.ts b/packages/opencensus-exporter-ocagent/src/ocagent.ts index eb6dfd8ad..dc446951f 100644 --- a/packages/opencensus-exporter-ocagent/src/ocagent.ts +++ b/packages/opencensus-exporter-ocagent/src/ocagent.ts @@ -15,11 +15,23 @@ */ import * as protoLoader from '@grpc/proto-loader'; -import {Exporter, ExporterBuffer, ExporterConfig, logger, Logger, Span, version as coreVersion} from '@opencensus/core'; +import { + Exporter, + ExporterBuffer, + ExporterConfig, + logger, + Logger, + Span, + version as coreVersion, +} from '@opencensus/core'; import * as grpc from 'grpc'; import * as os from 'os'; -import {adaptRootSpan, createNode} from './adapters'; -import {opencensus, TraceServiceClient, TraceServiceExportStream} from './types'; +import { adaptRootSpan, createNode } from './adapters'; +import { + opencensus, + TraceServiceClient, + TraceServiceExportStream, +} from './types'; /** * Options for OpenCensus Agent Exporter configuration. @@ -37,7 +49,7 @@ const DEFAULT_OPTIONS: OCAgentExporterOptions = { host: 'localhost', port: 55678, credentials: grpc.credentials.createInsecure(), - logger: logger.logger() + logger: logger.logger(), }; /** @@ -47,7 +59,7 @@ enum StreamEvent { Data = 'data', Status = 'status', Error = 'error', - Metadata = 'metadata' + Metadata = 'metadata', } /** @@ -63,7 +75,7 @@ export class OCAgentExporter implements Exporter { // Connection objects private traceServiceClient: TraceServiceClient; - private exportStream: TraceServiceExportStream|undefined; + private exportStream: TraceServiceExportStream | undefined; // Resolved configuration options private config: OCAgentExporterOptions; @@ -90,35 +102,35 @@ export class OCAgentExporter implements Exporter { this.exporterVersion = require('../../package.json').version; this.coreVersion = coreVersion; this.hostName = os.hostname(); - this.processStartTimeMillis = Date.now() - (process.uptime() * 1000); + this.processStartTimeMillis = Date.now() - process.uptime() * 1000; /** * Generate grpc services from the proto files. */ const traceServiceProtoPath = - 'opencensus/proto/agent/trace/v1/trace_service.proto'; - const includeDirs = [ - __dirname + '/protos', - ]; + 'opencensus/proto/agent/trace/v1/trace_service.proto'; + const includeDirs = [__dirname + '/protos']; // tslint:disable-next-line:no-any - const proto: any = - grpc.loadPackageDefinition(protoLoader.loadSync(traceServiceProtoPath, { - keepCase: false, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs - })); + const proto: any = grpc.loadPackageDefinition( + protoLoader.loadSync(traceServiceProtoPath, { + keepCase: false, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs, + }) + ); /** * Connect to the trace service and connect to the config and export * streams. */ const serverAddress = `${this.config.host}:${this.config.port}`; - this.traceServiceClient = - new proto.opencensus.proto.agent.trace.v1.TraceService( - serverAddress, this.config.credentials); + this.traceServiceClient = new proto.opencensus.proto.agent.trace.v1.TraceService( + serverAddress, + this.config.credentials + ); this.start(); } @@ -167,22 +179,23 @@ export class OCAgentExporter implements Exporter { this.logger.info('OCAgent: export stream connected'); }); this.exportStream.on( - StreamEvent.Data, - (message: - opencensus.proto.agent.trace.v1.ExportTraceServiceResponse) => { - // no-op: We must listen on the "data" event otherwise we won't - // receive status events. - }); + StreamEvent.Data, + (message: opencensus.proto.agent.trace.v1.ExportTraceServiceResponse) => { + // no-op: We must listen on the "data" event otherwise we won't + // receive status events. + } + ); this.exportStream.on(StreamEvent.Status, (status: grpc.StatusObject) => { // Attempt reconnect if appropriate. The grpc client will perform a // backoff internally. if (this.shouldAttemptReconnect(status)) { this.logger.error( - `OCAgent: export stream disconnected; attempting reconnect`); + `OCAgent: export stream disconnected; attempting reconnect` + ); setTimeout(() => this.connectToExportStream(), 250); } }); - this.exportStream.on(StreamEvent.Error, (err) => { + this.exportStream.on(StreamEvent.Error, err => { // no-op: Swallow errors to keep the process alive. Not listening // to this event will exit the process on an error. this.logger.error('OCAgent: export stream error', err); @@ -196,8 +209,8 @@ export class OCAgentExporter implements Exporter { */ private shouldAttemptReconnect(status: grpc.StatusObject): boolean { switch (status.code) { - case grpc.status.UNKNOWN: // stream disconnected - case grpc.status.UNAVAILABLE: // stream could not be established + case grpc.status.UNKNOWN: // stream disconnected + case grpc.status.UNAVAILABLE: // stream could not be established return true; default: return false; @@ -213,13 +226,14 @@ export class OCAgentExporter implements Exporter { this.buffer.addToBuffer(span); } - publish(spans: Span[]): Promise { + publish(spans: Span[]): Promise { return new Promise((resolve, reject) => { this.logger.info(`OCAgent: publish spans=${spans.length}`); if (!this.exportStream) { this.logger.warn( - 'OCAgent: Export stream not connected. Could not publish spans.'); + 'OCAgent: Export stream not connected. Could not publish spans.' + ); return reject(); } @@ -230,7 +244,7 @@ export class OCAgentExporter implements Exporter { coreVersion: this.coreVersion, hostName: this.hostName, processStartTimeMillis: this.processStartTimeMillis, - attributes: this.config.attributes + attributes: this.config.attributes, }); // Adapt and write each Span to the agent through the export stream. @@ -238,7 +252,7 @@ export class OCAgentExporter implements Exporter { // will be lost. spans.forEach(span => { if (this.exportStream) { - this.exportStream.write({node, spans: adaptRootSpan(span)}); + this.exportStream.write({ node, spans: adaptRootSpan(span) }); } }); diff --git a/packages/opencensus-exporter-ocagent/src/types/google.ts b/packages/opencensus-exporter-ocagent/src/types/google.ts index 8113e2d6e..f51a14f1a 100644 --- a/packages/opencensus-exporter-ocagent/src/types/google.ts +++ b/packages/opencensus-exporter-ocagent/src/types/google.ts @@ -18,42 +18,42 @@ export namespace google.protobuf { export interface Timestamp { - seconds?: number|Long|null; - nanos?: number|null; + seconds?: number | Long | null; + nanos?: number | null; } export interface DoubleValue { - value?: number|null; + value?: number | null; } export interface FloatValue { - value?: number|null; + value?: number | null; } export interface Int64Value { - value?: number|Long|null; + value?: number | Long | null; } export interface UInt64Value { - value?: number|Long|null; + value?: number | Long | null; } export interface Int32Value { - value?: number|null; + value?: number | null; } export interface UInt32Value { - value?: number|null; + value?: number | null; } export interface BoolValue { - value?: boolean|null; + value?: boolean | null; } export interface StringValue { - value?: string|null; + value?: string | null; } export interface BytesValue { - value?: Uint8Array|null; + value?: Uint8Array | null; } } diff --git a/packages/opencensus-exporter-ocagent/src/types/index.ts b/packages/opencensus-exporter-ocagent/src/types/index.ts index add4ac3c5..50b673628 100644 --- a/packages/opencensus-exporter-ocagent/src/types/index.ts +++ b/packages/opencensus-exporter-ocagent/src/types/index.ts @@ -16,4 +16,4 @@ export * from './google'; export * from './opencensus'; -export * from './trace-service'; \ No newline at end of file +export * from './trace-service'; diff --git a/packages/opencensus-exporter-ocagent/src/types/opencensus.ts b/packages/opencensus-exporter-ocagent/src/types/opencensus.ts index 66c0a51ce..f9c7ee710 100644 --- a/packages/opencensus-exporter-ocagent/src/types/opencensus.ts +++ b/packages/opencensus-exporter-ocagent/src/types/opencensus.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {google} from './google'; +import { google } from './google'; // tslint:disable:no-namespace @@ -22,22 +22,22 @@ export namespace opencensus.proto { export namespace agent { export namespace common.v1 { export interface Node { - identifier?: opencensus.proto.agent.common.v1.ProcessIdentifier|null; - libraryInfo?: opencensus.proto.agent.common.v1.LibraryInfo|null; - serviceInfo?: opencensus.proto.agent.common.v1.ServiceInfo|null; - attributes?: {[k: string]: string}|null; + identifier?: opencensus.proto.agent.common.v1.ProcessIdentifier | null; + libraryInfo?: opencensus.proto.agent.common.v1.LibraryInfo | null; + serviceInfo?: opencensus.proto.agent.common.v1.ServiceInfo | null; + attributes?: { [k: string]: string } | null; } export interface ProcessIdentifier { - hostName?: string|null; - pid?: number|null; - startTimestamp?: google.protobuf.Timestamp|null; + hostName?: string | null; + pid?: number | null; + startTimestamp?: google.protobuf.Timestamp | null; } export interface LibraryInfo { - language?: opencensus.proto.agent.common.v1.LibraryInfo.Language|null; - exporterVersion?: string|null; - coreLibraryVersion?: string|null; + language?: opencensus.proto.agent.common.v1.LibraryInfo.Language | null; + exporterVersion?: string | null; + coreLibraryVersion?: string | null; } export namespace LibraryInfo { @@ -51,12 +51,12 @@ export namespace opencensus.proto { NODE_JS = 6, PHP = 7, PYTHON = 8, - RUBY = 9 + RUBY = 9, } } export interface ServiceInfo { - name?: string|null; + name?: string | null; } } export namespace trace.v1 { @@ -77,158 +77,165 @@ export namespace opencensus.proto { export interface ExportTraceServiceResponse {} export interface ProbabilitySampler { - samplingProbability?: number|null; + samplingProbability?: number | null; } export interface ConstantSampler { - decision?: boolean|null; + decision?: boolean | null; } export interface RateLimitingSampler { - qps?: number|Long|null; + qps?: number | Long | null; } export interface TraceConfig { - probabilitySampler?: ProbabilitySampler|null; - constantSampler?: ConstantSampler|null; - rateLimitingSampler?: RateLimitingSampler|null; + probabilitySampler?: ProbabilitySampler | null; + constantSampler?: ConstantSampler | null; + rateLimitingSampler?: RateLimitingSampler | null; } } } export namespace trace.v1 { export interface Span { - traceId?: Uint8Array|null; - spanId?: Uint8Array|null; - tracestate?: opencensus.proto.trace.v1.Span.Tracestate|null; - parentSpanId?: Uint8Array|null; - name?: opencensus.proto.trace.v1.TruncatableString|null; - kind?: opencensus.proto.trace.v1.Span.SpanKind|null; - startTime?: google.protobuf.Timestamp|null; - endTime?: google.protobuf.Timestamp|null; - attributes?: opencensus.proto.trace.v1.Span.Attributes|null; - stackTrace?: opencensus.proto.trace.v1.StackTrace|null; - timeEvents?: opencensus.proto.trace.v1.Span.TimeEvents|null; - links?: opencensus.proto.trace.v1.Span.Links|null; - status?: opencensus.proto.trace.v1.Status|null; - sameProcessAsParentSpan?: google.protobuf.BoolValue|null; - childSpanCount?: google.protobuf.UInt32Value|null; + traceId?: Uint8Array | null; + spanId?: Uint8Array | null; + tracestate?: opencensus.proto.trace.v1.Span.Tracestate | null; + parentSpanId?: Uint8Array | null; + name?: opencensus.proto.trace.v1.TruncatableString | null; + kind?: opencensus.proto.trace.v1.Span.SpanKind | null; + startTime?: google.protobuf.Timestamp | null; + endTime?: google.protobuf.Timestamp | null; + attributes?: opencensus.proto.trace.v1.Span.Attributes | null; + stackTrace?: opencensus.proto.trace.v1.StackTrace | null; + timeEvents?: opencensus.proto.trace.v1.Span.TimeEvents | null; + links?: opencensus.proto.trace.v1.Span.Links | null; + status?: opencensus.proto.trace.v1.Status | null; + sameProcessAsParentSpan?: google.protobuf.BoolValue | null; + childSpanCount?: google.protobuf.UInt32Value | null; } export namespace Span { export interface Tracestate { - entries?: opencensus.proto.trace.v1.Span.Tracestate.Entry[]|null; + entries?: opencensus.proto.trace.v1.Span.Tracestate.Entry[] | null; } export namespace Tracestate { export interface Entry { - key?: string|null; - value?: string|null; + key?: string | null; + value?: string | null; } } - export enum SpanKind {SPAN_KIND_UNSPECIFIED = 0, SERVER = 1, CLIENT = 2} + export enum SpanKind { + SPAN_KIND_UNSPECIFIED = 0, + SERVER = 1, + CLIENT = 2, + } export interface Attributes { - attributeMap?: {[k: string]: opencensus.proto.trace.v1.AttributeValue}| - null; - droppedAttributesCount?: number|null; + attributeMap?: { + [k: string]: opencensus.proto.trace.v1.AttributeValue; + } | null; + droppedAttributesCount?: number | null; } export interface TimeEvent { - time?: google.protobuf.Timestamp|null; - annotation?: opencensus.proto.trace.v1.Span.TimeEvent.Annotation|null; - messageEvent?: opencensus.proto.trace.v1.Span.TimeEvent.MessageEvent| - null; + time?: google.protobuf.Timestamp | null; + annotation?: opencensus.proto.trace.v1.Span.TimeEvent.Annotation | null; + messageEvent?: opencensus.proto.trace.v1.Span.TimeEvent.MessageEvent | null; } export namespace TimeEvent { export interface Annotation { - description?: opencensus.proto.trace.v1.TruncatableString|null; - attributes?: opencensus.proto.trace.v1.Span.Attributes|null; + description?: opencensus.proto.trace.v1.TruncatableString | null; + attributes?: opencensus.proto.trace.v1.Span.Attributes | null; } export interface MessageEvent { - type?: opencensus.proto.trace.v1.Span.TimeEvent.MessageEvent.Type| - null; - id?: number|Long|null; - uncompressedSize?: number|Long|null; - compressedSize?: number|Long|null; + type?: opencensus.proto.trace.v1.Span.TimeEvent.MessageEvent.Type | null; + id?: number | Long | null; + uncompressedSize?: number | Long | null; + compressedSize?: number | Long | null; } export namespace MessageEvent { - export enum Type {TYPE_UNSPECIFIED = 0, SENT = 1, RECEIVED = 2} + export enum Type { + TYPE_UNSPECIFIED = 0, + SENT = 1, + RECEIVED = 2, + } } } export interface TimeEvents { - timeEvent?: opencensus.proto.trace.v1.Span.TimeEvent[]|null; - droppedAnnotationsCount?: number|null; - droppedMessageEventsCount?: number|null; + timeEvent?: opencensus.proto.trace.v1.Span.TimeEvent[] | null; + droppedAnnotationsCount?: number | null; + droppedMessageEventsCount?: number | null; } export interface Link { - traceId?: Uint8Array|null; + traceId?: Uint8Array | null; - spanId?: Uint8Array|null; + spanId?: Uint8Array | null; - type?: opencensus.proto.trace.v1.Span.Link.Type|null; + type?: opencensus.proto.trace.v1.Span.Link.Type | null; - attributes?: opencensus.proto.trace.v1.Span.Attributes|null; + attributes?: opencensus.proto.trace.v1.Span.Attributes | null; } export namespace Link { export enum Type { TYPE_UNSPECIFIED = 0, CHILD_LINKED_SPAN = 1, - PARENT_LINKED_SPAN = 2 + PARENT_LINKED_SPAN = 2, } } export interface Links { - link?: opencensus.proto.trace.v1.Span.Link[]|null; - droppedLinksCount?: number|null; + link?: opencensus.proto.trace.v1.Span.Link[] | null; + droppedLinksCount?: number | null; } } export interface Status { - code?: number|null; - message?: string|null; + code?: number | null; + message?: string | null; } export interface AttributeValue { - stringValue?: opencensus.proto.trace.v1.TruncatableString|null; - intValue?: number|Long|null; - boolValue?: boolean|null; + stringValue?: opencensus.proto.trace.v1.TruncatableString | null; + intValue?: number | Long | null; + boolValue?: boolean | null; } export interface StackTrace { - stackFrames?: opencensus.proto.trace.v1.StackTrace.StackFrames|null; - stackTraceHashId?: number|Long|null; + stackFrames?: opencensus.proto.trace.v1.StackTrace.StackFrames | null; + stackTraceHashId?: number | Long | null; } export namespace StackTrace { export interface StackFrame { - functionName?: opencensus.proto.trace.v1.TruncatableString|null; - originalFunctionName?: opencensus.proto.trace.v1.TruncatableString|null; - fileName?: opencensus.proto.trace.v1.TruncatableString|null; - lineNumber?: number|Long|null; - columnNumber?: number|Long|null; - loadModule?: opencensus.proto.trace.v1.Module|null; - sourceVersion?: opencensus.proto.trace.v1.TruncatableString|null; + functionName?: opencensus.proto.trace.v1.TruncatableString | null; + originalFunctionName?: opencensus.proto.trace.v1.TruncatableString | null; + fileName?: opencensus.proto.trace.v1.TruncatableString | null; + lineNumber?: number | Long | null; + columnNumber?: number | Long | null; + loadModule?: opencensus.proto.trace.v1.Module | null; + sourceVersion?: opencensus.proto.trace.v1.TruncatableString | null; } export interface StackFrames { - frame?: opencensus.proto.trace.v1.StackTrace.StackFrame[]|null; - droppedFramesCount?: number|null; + frame?: opencensus.proto.trace.v1.StackTrace.StackFrame[] | null; + droppedFramesCount?: number | null; } } export interface Module { - module?: opencensus.proto.trace.v1.TruncatableString|null; - buildId?: opencensus.proto.trace.v1.TruncatableString|null; + module?: opencensus.proto.trace.v1.TruncatableString | null; + buildId?: opencensus.proto.trace.v1.TruncatableString | null; } export interface TruncatableString { - value?: string|null; - truncatedByteCount?: number|null; + value?: string | null; + truncatedByteCount?: number | null; } } } diff --git a/packages/opencensus-exporter-ocagent/src/types/trace-service.ts b/packages/opencensus-exporter-ocagent/src/types/trace-service.ts index 62efffcde..315af0fec 100644 --- a/packages/opencensus-exporter-ocagent/src/types/trace-service.ts +++ b/packages/opencensus-exporter-ocagent/src/types/trace-service.ts @@ -15,18 +15,20 @@ */ import * as grpc from 'grpc'; -import {opencensus} from './opencensus'; +import { opencensus } from './opencensus'; /** * Trace Service types */ export type TraceServiceConfigStream = grpc.ClientDuplexStream< - opencensus.proto.agent.trace.v1.CurrentLibraryConfig, - opencensus.proto.agent.trace.v1.UpdatedLibraryConfig>; + opencensus.proto.agent.trace.v1.CurrentLibraryConfig, + opencensus.proto.agent.trace.v1.UpdatedLibraryConfig +>; export type TraceServiceExportStream = grpc.ClientDuplexStream< - opencensus.proto.agent.trace.v1.ExportTraceServiceRequest, - opencensus.proto.agent.trace.v1.ExportTraceServiceRequest>; + opencensus.proto.agent.trace.v1.ExportTraceServiceRequest, + opencensus.proto.agent.trace.v1.ExportTraceServiceRequest +>; export interface TraceServiceClient extends grpc.Client { config: () => TraceServiceConfigStream; diff --git a/packages/opencensus-exporter-ocagent/test/test-ocagent.ts b/packages/opencensus-exporter-ocagent/test/test-ocagent.ts index de3fb87dd..81cdb8ee7 100644 --- a/packages/opencensus-exporter-ocagent/test/test-ocagent.ts +++ b/packages/opencensus-exporter-ocagent/test/test-ocagent.ts @@ -15,14 +15,22 @@ */ import * as protoLoader from '@grpc/proto-loader'; -import {CanonicalCode, LinkType, MessageEventType, Span, SpanKind, TraceOptions, Tracing} from '@opencensus/core'; +import { + CanonicalCode, + LinkType, + MessageEventType, + Span, + SpanKind, + TraceOptions, + Tracing, +} from '@opencensus/core'; import * as nodeTracing from '@opencensus/nodejs'; import * as assert from 'assert'; -import {EventEmitter} from 'events'; +import { EventEmitter } from 'events'; import * as grpc from 'grpc'; import * as uuid from 'uuid'; -import {OCAgentExporter} from '../src'; -import {opencensus} from '../src/types'; +import { OCAgentExporter } from '../src'; +import { opencensus } from '../src/types'; // Mock Agent @@ -30,11 +38,13 @@ import {opencensus} from '../src/types'; * Agent stream types. */ type TraceServiceConfigStream = grpc.ServerDuplexStream< - opencensus.proto.agent.trace.v1.CurrentLibraryConfig, - opencensus.proto.agent.trace.v1.UpdatedLibraryConfig>; + opencensus.proto.agent.trace.v1.CurrentLibraryConfig, + opencensus.proto.agent.trace.v1.UpdatedLibraryConfig +>; type TraceServiceExportStream = grpc.ServerDuplexStream< - opencensus.proto.agent.trace.v1.ExportTraceServiceRequest, - opencensus.proto.agent.trace.v1.ExportTraceServiceRequest>; + opencensus.proto.agent.trace.v1.ExportTraceServiceRequest, + opencensus.proto.agent.trace.v1.ExportTraceServiceRequest +>; /** * Events emitted by the MockAgent. @@ -51,50 +61,56 @@ enum MockAgentEvent { */ class MockAgent extends EventEmitter { private server: grpc.Server; - private configStream: TraceServiceConfigStream|undefined; + private configStream: TraceServiceConfigStream | undefined; constructor(host: string, port: number) { super(); this.server = new grpc.Server(); const traceServiceProtoPath = - 'opencensus/proto/agent/trace/v1/trace_service.proto'; + 'opencensus/proto/agent/trace/v1/trace_service.proto'; const includeDirs = [ __dirname + '../../../src/protos', - __dirname + '../../../node_modules/google-proto-files' + __dirname + '../../../node_modules/google-proto-files', ]; // tslint:disable-next-line:no-any - const proto: any = - grpc.loadPackageDefinition(protoLoader.loadSync(traceServiceProtoPath, { - keepCase: false, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs - })); + const proto: any = grpc.loadPackageDefinition( + protoLoader.loadSync(traceServiceProtoPath, { + keepCase: false, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs, + }) + ); this.server.addService( - proto.opencensus.proto.agent.trace.v1.TraceService.service, { - config: (stream: TraceServiceConfigStream) => { - this.configStream = stream; - this.emit(MockAgentEvent.ConfigStreamConnected); - }, - export: (stream: TraceServiceExportStream) => { - this.emit(MockAgentEvent.ExportStreamConnected); - stream.on( - 'data', - (message: opencensus.proto.agent.trace.v1 - .ExportTraceServiceRequest) => { - this.emit( - MockAgentEvent.ExportStreamMessageReceived, message); - }); - } - }); + proto.opencensus.proto.agent.trace.v1.TraceService.service, + { + config: (stream: TraceServiceConfigStream) => { + this.configStream = stream; + this.emit(MockAgentEvent.ConfigStreamConnected); + }, + export: (stream: TraceServiceExportStream) => { + this.emit(MockAgentEvent.ExportStreamConnected); + stream.on( + 'data', + ( + message: opencensus.proto.agent.trace.v1.ExportTraceServiceRequest + ) => { + this.emit(MockAgentEvent.ExportStreamMessageReceived, message); + } + ); + }, + } + ); this.server.bind( - `${host}:${port}`, grpc.ServerCredentials.createInsecure()); + `${host}:${port}`, + grpc.ServerCredentials.createInsecure() + ); this.server.start(); } @@ -104,8 +120,9 @@ class MockAgent extends EventEmitter { */ sendConfigurationChangeProbability(probablity: number) { if (this.configStream) { - this.configStream.write( - {config: {probabilitySampler: {samplingProbability: probablity}}}); + this.configStream.write({ + config: { probabilitySampler: { samplingProbability: probablity } }, + }); } } @@ -114,7 +131,7 @@ class MockAgent extends EventEmitter { */ sendConfigurationChangeConstant(decision: boolean) { if (this.configStream) { - this.configStream.write({config: {constantSampler: {decision}}}); + this.configStream.write({ config: { constantSampler: { decision } } }); } } @@ -123,7 +140,7 @@ class MockAgent extends EventEmitter { */ sendConfigurationChangeRateLimited(qps: number) { if (this.configStream) { - this.configStream.write({config: {rateLimitingSampler: {qps}}}); + this.configStream.write({ config: { rateLimitingSampler: { qps } } }); } } @@ -139,7 +156,10 @@ class MockAgent extends EventEmitter { * Generate a hex id. */ const hexId = (): string => { - return uuid.v4().split('-').join(''); + return uuid + .v4() + .split('-') + .join(''); }; describe('OpenCensus Agent Exporter', () => { @@ -160,7 +180,7 @@ describe('OpenCensus Agent Exporter', () => { host: SERVER_HOST, port: SERVER_PORT, bufferSize: 1, - bufferTimeout: 0 + bufferTimeout: 0, }); tracing = nodeTracing.start({ exporter: ocAgentExporter, @@ -169,8 +189,8 @@ describe('OpenCensus Agent Exporter', () => { numberOfAttributesPerSpan: 4, numberOfLinksPerSpan: 3, numberOfAnnontationEventsPerSpan: 2, - numberOfMessageEventsPerSpan: 3 - } + numberOfMessageEventsPerSpan: 3, + }, }); }); @@ -180,60 +200,66 @@ describe('OpenCensus Agent Exporter', () => { server.stop(); }); - it('should publish spans to agent', (done) => { + it('should publish spans to agent', done => { const ROOT_SPAN_NAME = 'root-span'; const CHILD_SPAN_NAME = 'child-span'; // Create a rootSpan and one childSpan, then validate that those spans // arrived at the server through the grpc stream. tracing.tracer.startRootSpan( - { - name: ROOT_SPAN_NAME, - spanContext: {traceId: hexId(), spanId: hexId(), options: 0x1} - }, - (rootSpan: Span) => { - const childSpan = rootSpan.startChildSpan( - {name: CHILD_SPAN_NAME, kind: SpanKind.UNSPECIFIED}); - - // When the stream is connected, we end both spans, which should - // trigger the spans to be sent to the agent. - server.once(MockAgentEvent.ExportStreamConnected, () => { - childSpan.end(); - rootSpan.end(); - }); + { + name: ROOT_SPAN_NAME, + spanContext: { traceId: hexId(), spanId: hexId(), options: 0x1 }, + }, + (rootSpan: Span) => { + const childSpan = rootSpan.startChildSpan({ + name: CHILD_SPAN_NAME, + kind: SpanKind.UNSPECIFIED, + }); - // When the stream receives data, validate that the two spans we just - // ended are present. - server.once( - MockAgentEvent.ExportStreamMessageReceived, - (message: opencensus.proto.agent.trace.v1 - .ExportTraceServiceRequest) => { - let foundRootSpan = false; - let foundChildSpan = false; - message.spans.forEach(span => { - if (!span || !span.name) return; - - switch (span.name.value) { - case ROOT_SPAN_NAME: { - foundRootSpan = true; - break; - } - case CHILD_SPAN_NAME: { - foundChildSpan = true; - break; - } - default: { break; } - } - }); - assert.ok(foundRootSpan, 'could not find root span in message'); - assert.ok( - foundChildSpan, 'could not find child span in message'); - done(); - }); + // When the stream is connected, we end both spans, which should + // trigger the spans to be sent to the agent. + server.once(MockAgentEvent.ExportStreamConnected, () => { + childSpan.end(); + rootSpan.end(); }); + + // When the stream receives data, validate that the two spans we just + // ended are present. + server.once( + MockAgentEvent.ExportStreamMessageReceived, + ( + message: opencensus.proto.agent.trace.v1.ExportTraceServiceRequest + ) => { + let foundRootSpan = false; + let foundChildSpan = false; + message.spans.forEach(span => { + if (!span || !span.name) return; + + switch (span.name.value) { + case ROOT_SPAN_NAME: { + foundRootSpan = true; + break; + } + case CHILD_SPAN_NAME: { + foundChildSpan = true; + break; + } + default: { + break; + } + } + }); + assert.ok(foundRootSpan, 'could not find root span in message'); + assert.ok(foundChildSpan, 'could not find child span in message'); + done(); + } + ); + } + ); }); - it('should adapt a span correctly', (done) => { + it('should adapt a span correctly', done => { const rootSpanOptions: TraceOptions = { name: 'root', kind: SpanKind.SERVER, @@ -241,8 +267,8 @@ describe('OpenCensus Agent Exporter', () => { traceId: hexId(), spanId: hexId(), traceState: 'foo=bar,baz=buzz', - options: 0x1 - } + options: 0x1, + }, }; tracing.tracer.startRootSpan(rootSpanOptions, (rootSpan: Span) => { @@ -258,14 +284,26 @@ describe('OpenCensus Agent Exporter', () => { rootSpan.addAttribute('my_attribute_boolean', false); // Annotation - rootSpan.addAnnotation( - 'my_annotation', {myString: 'bar', myNumber: 123, myBoolean: true}); - rootSpan.addAnnotation( - 'my_annotation1', {myString: 'bar1', myNumber: 456, myBoolean: true}); - rootSpan.addAnnotation( - 'my_annotation2', {myString: 'bar2', myNumber: 789, myBoolean: true}); - rootSpan.addAnnotation( - 'my_annotation3', {myString: 'bar3', myNumber: 789, myBoolean: true}); + rootSpan.addAnnotation('my_annotation', { + myString: 'bar', + myNumber: 123, + myBoolean: true, + }); + rootSpan.addAnnotation('my_annotation1', { + myString: 'bar1', + myNumber: 456, + myBoolean: true, + }); + rootSpan.addAnnotation('my_annotation2', { + myString: 'bar2', + myNumber: 789, + myBoolean: true, + }); + rootSpan.addAnnotation('my_annotation3', { + myString: 'bar3', + myNumber: 789, + myBoolean: true, + }); // Message Event const timeStamp = 123456789; @@ -280,9 +318,9 @@ describe('OpenCensus Agent Exporter', () => { rootSpan.addLink('aaaaa', 'aaa', LinkType.CHILD_LINKED_SPAN); rootSpan.addLink('bbbbb', 'bbbbb', LinkType.CHILD_LINKED_SPAN); rootSpan.addLink('ffff', 'ffff', LinkType.CHILD_LINKED_SPAN, { - 'child_link_attribute_string': 'foo1', - 'child_link_attribute_number': 123, - 'child_link_attribute_boolean': true, + child_link_attribute_string: 'foo1', + child_link_attribute_number: 123, + child_link_attribute_boolean: true, }); rootSpan.addLink('ffff', 'ffff', LinkType.PARENT_LINKED_SPAN); // Use of `null` is to force a `TYPE_UNSPECIFIED` value @@ -290,349 +328,366 @@ describe('OpenCensus Agent Exporter', () => { rootSpan.addLink('ffff', 'ffff', null as any); server.on( - MockAgentEvent.ExportStreamMessageReceived, - (message: - opencensus.proto.agent.trace.v1.ExportTraceServiceRequest) => { - assert.strictEqual(message.spans.length, 1); - const span = message.spans[0]; - if (!span) { - assert.fail('span is null or undefined'); - return; - } + MockAgentEvent.ExportStreamMessageReceived, + ( + message: opencensus.proto.agent.trace.v1.ExportTraceServiceRequest + ) => { + assert.strictEqual(message.spans.length, 1); + const span = message.spans[0]; + if (!span) { + assert.fail('span is null or undefined'); + return; + } - // Name / Context - if (!span.name) { - assert.fail('span.name is null or undefined'); - return; - } - assert.strictEqual(span.name.value, 'root'); - assert.strictEqual(span.kind, 'SERVER'); + // Name / Context + if (!span.name) { + assert.fail('span.name is null or undefined'); + return; + } + assert.strictEqual(span.name.value, 'root'); + assert.strictEqual(span.kind, 'SERVER'); - if (!span.tracestate) { - assert.fail('span.tracestate is null or undefined'); - return; - } - assert.deepStrictEqual( - span.tracestate.entries, - [{key: 'foo', value: 'bar'}, {key: 'baz', value: 'buzz'}]); - - if (!span.status) { - assert.fail('span.status is null or undefined'); - } else { - assert.deepStrictEqual(span.status, {code: 0, message: ''}); - } + if (!span.tracestate) { + assert.fail('span.tracestate is null or undefined'); + return; + } + assert.deepStrictEqual(span.tracestate.entries, [ + { key: 'foo', value: 'bar' }, + { key: 'baz', value: 'buzz' }, + ]); + + if (!span.status) { + assert.fail('span.status is null or undefined'); + } else { + assert.deepStrictEqual(span.status, { code: 0, message: '' }); + } - // Attributes - if (!span.attributes) { - assert.fail('span.attributes is null or undefined'); - return; - } - assert.deepStrictEqual(span.attributes.attributeMap, { - my_first_attribute: { - value: 'stringValue', - stringValue: {value: 'foo1', truncatedByteCount: 0} - }, - my_attribute_string: { - value: 'stringValue', - stringValue: {value: 'bar2', truncatedByteCount: 0} - }, - my_attribute_number: {value: 'intValue', intValue: '456'}, - my_attribute_boolean: {value: 'boolValue', boolValue: false} - }); - assert.strictEqual(span.attributes.droppedAttributesCount, 1); - - // Time Events - assert.deepStrictEqual(span.timeEvents, { - droppedAnnotationsCount: 2, - droppedMessageEventsCount: 1, - timeEvent: [ - { - value: 'annotation', - time: null, - annotation: { - description: - {value: 'my_annotation2', truncatedByteCount: 0}, - attributes: { - attributeMap: { - myString: { - value: 'stringValue', - stringValue: {value: 'bar2', truncatedByteCount: 0} - }, - myNumber: {value: 'intValue', intValue: '789'}, - myBoolean: {value: 'boolValue', boolValue: true} + // Attributes + if (!span.attributes) { + assert.fail('span.attributes is null or undefined'); + return; + } + assert.deepStrictEqual(span.attributes.attributeMap, { + my_first_attribute: { + value: 'stringValue', + stringValue: { value: 'foo1', truncatedByteCount: 0 }, + }, + my_attribute_string: { + value: 'stringValue', + stringValue: { value: 'bar2', truncatedByteCount: 0 }, + }, + my_attribute_number: { value: 'intValue', intValue: '456' }, + my_attribute_boolean: { value: 'boolValue', boolValue: false }, + }); + assert.strictEqual(span.attributes.droppedAttributesCount, 1); + + // Time Events + assert.deepStrictEqual(span.timeEvents, { + droppedAnnotationsCount: 2, + droppedMessageEventsCount: 1, + timeEvent: [ + { + value: 'annotation', + time: null, + annotation: { + description: { + value: 'my_annotation2', + truncatedByteCount: 0, + }, + attributes: { + attributeMap: { + myString: { + value: 'stringValue', + stringValue: { value: 'bar2', truncatedByteCount: 0 }, }, - droppedAttributesCount: 0 - } + myNumber: { value: 'intValue', intValue: '789' }, + myBoolean: { value: 'boolValue', boolValue: true }, + }, + droppedAttributesCount: 0, }, }, - { - value: 'annotation', - time: null, - annotation: { - description: - {value: 'my_annotation3', truncatedByteCount: 0}, - attributes: { - attributeMap: { - myString: { - value: 'stringValue', - stringValue: {value: 'bar3', truncatedByteCount: 0} - }, - myNumber: {value: 'intValue', intValue: '789'}, - myBoolean: {value: 'boolValue', boolValue: true} + }, + { + value: 'annotation', + time: null, + annotation: { + description: { + value: 'my_annotation3', + truncatedByteCount: 0, + }, + attributes: { + attributeMap: { + myString: { + value: 'stringValue', + stringValue: { value: 'bar3', truncatedByteCount: 0 }, }, - droppedAttributesCount: 0 - } + myNumber: { value: 'intValue', intValue: '789' }, + myBoolean: { value: 'boolValue', boolValue: true }, + }, + droppedAttributesCount: 0, }, }, - { - messageEvent: { - compressedSize: '12', - id: '2', - type: 'SENT', - uncompressedSize: '100' - }, - time: {seconds: '123456', nanos: 789000000}, - value: 'messageEvent' + }, + { + messageEvent: { + compressedSize: '12', + id: '2', + type: 'SENT', + uncompressedSize: '100', }, - { - value: 'messageEvent', - messageEvent: { - compressedSize: '0', - id: '1', - type: 'RECEIVED', - uncompressedSize: '0' - }, - time: {seconds: '123456', nanos: 789000000}, + time: { seconds: '123456', nanos: 789000000 }, + value: 'messageEvent', + }, + { + value: 'messageEvent', + messageEvent: { + compressedSize: '0', + id: '1', + type: 'RECEIVED', + uncompressedSize: '0', + }, + time: { seconds: '123456', nanos: 789000000 }, + }, + { + value: 'messageEvent', + messageEvent: { + compressedSize: '0', + id: '2', + type: 'TYPE_UNSPECIFIED', + uncompressedSize: '0', }, - { - value: 'messageEvent', - messageEvent: { - compressedSize: '0', - id: '2', - type: 'TYPE_UNSPECIFIED', - uncompressedSize: '0' + time: { seconds: '123456', nanos: 789000000 }, + }, + ], + }); + + // Links + const buff = Buffer.from([255, 255]); + assert.deepStrictEqual(span.links, { + droppedLinksCount: 2, + link: [ + { + type: 'CHILD_LINKED_SPAN', + traceId: buff, + spanId: buff, + attributes: { + droppedAttributesCount: 0, + attributeMap: { + child_link_attribute_string: { + value: 'stringValue', + stringValue: { value: 'foo1', truncatedByteCount: 0 }, + }, + child_link_attribute_number: { + value: 'intValue', + intValue: '123', + }, + child_link_attribute_boolean: { + value: 'boolValue', + boolValue: true, + }, }, - time: {seconds: '123456', nanos: 789000000}, - } - ] - }); + }, + }, + { + type: 'PARENT_LINKED_SPAN', + traceId: buff, + spanId: buff, + attributes: { attributeMap: {}, droppedAttributesCount: 0 }, + }, + { + type: 'TYPE_UNSPECIFIED', + traceId: buff, + spanId: buff, + attributes: { attributeMap: {}, droppedAttributesCount: 0 }, + }, + ], + }); + + done(); + } + ); + + rootSpan.end(); + }); + }); + + it('should adapt a span correctly without overflowing trace param limits', done => { + const rootSpanOptions: TraceOptions = { + name: 'root', + kind: SpanKind.SERVER, + spanContext: { + traceId: hexId(), + spanId: hexId(), + traceState: 'foo=bar,baz=buzz', + options: 0x1, + }, + }; + + tracing.tracer.startRootSpan(rootSpanOptions, (rootSpan: Span) => { + // Status + rootSpan.setStatus(CanonicalCode.OK); + + // Attribute + rootSpan.addAttribute('my_first_attribute', 'foo'); + rootSpan.addAttribute('my_second_attribute', 'foo2'); + + // Annotation + rootSpan.addAnnotation('my_annotation', { + myString: 'bar', + myNumber: 123, + myBoolean: true, + }); + + // Message Event + const timeStamp = 123456789; + rootSpan.addMessageEvent(MessageEventType.SENT, 1, timeStamp); + rootSpan.addMessageEvent(MessageEventType.RECEIVED, 1, timeStamp); - // Links - const buff = Buffer.from([255, 255]); - assert.deepStrictEqual(span.links, { - droppedLinksCount: 2, - link: [ - { - type: 'CHILD_LINKED_SPAN', - traceId: buff, - spanId: buff, + // Links + rootSpan.addLink('ffff', 'ffff', LinkType.CHILD_LINKED_SPAN, { + child_link_attribute_string: 'foo1', + child_link_attribute_number: 123, + child_link_attribute_boolean: true, + }); + rootSpan.addLink('ffff', 'ffff', LinkType.PARENT_LINKED_SPAN); + + server.on( + MockAgentEvent.ExportStreamMessageReceived, + ( + message: opencensus.proto.agent.trace.v1.ExportTraceServiceRequest + ) => { + assert.strictEqual(message.spans.length, 1); + const span = message.spans[0]; + // Name / Context + if (!span.name) { + assert.fail('span.name is null or undefined'); + return; + } + assert.strictEqual(span.name.value, 'root'); + assert.strictEqual(span.kind, 'SERVER'); + + if (!span.tracestate) { + assert.fail('span.tracestate is null or undefined'); + return; + } + assert.deepStrictEqual(span.tracestate.entries, [ + { key: 'foo', value: 'bar' }, + { key: 'baz', value: 'buzz' }, + ]); + + if (!span.status) { + assert.fail('span.status is null or undefined'); + } else { + assert.deepStrictEqual(span.status, { code: 0, message: '' }); + } + + // Attributes + if (!span.attributes) { + assert.fail('span.attributes is null or undefined'); + return; + } + assert.deepStrictEqual(span.attributes.attributeMap, { + my_first_attribute: { + value: 'stringValue', + stringValue: { value: 'foo', truncatedByteCount: 0 }, + }, + my_second_attribute: { + value: 'stringValue', + stringValue: { value: 'foo2', truncatedByteCount: 0 }, + }, + }); + assert.strictEqual(span.attributes.droppedAttributesCount, 0); + + // Time Events + assert.deepStrictEqual(span.timeEvents, { + droppedAnnotationsCount: 0, + droppedMessageEventsCount: 0, + timeEvent: [ + { + value: 'annotation', + time: null, + annotation: { + description: { + value: 'my_annotation', + truncatedByteCount: 0, + }, attributes: { - droppedAttributesCount: 0, attributeMap: { - child_link_attribute_string: { + myString: { value: 'stringValue', - stringValue: {value: 'foo1', truncatedByteCount: 0} + stringValue: { value: 'bar', truncatedByteCount: 0 }, }, - child_link_attribute_number: - {value: 'intValue', intValue: '123'}, - child_link_attribute_boolean: - {value: 'boolValue', boolValue: true} - } - } + myNumber: { value: 'intValue', intValue: '123' }, + myBoolean: { value: 'boolValue', boolValue: true }, + }, + droppedAttributesCount: 0, + }, }, - { - type: 'PARENT_LINKED_SPAN', - traceId: buff, - spanId: buff, - attributes: - {'attributeMap': {}, 'droppedAttributesCount': 0} + }, + { + messageEvent: { + compressedSize: '0', + id: '1', + type: 'SENT', + uncompressedSize: '0', }, - { - type: 'TYPE_UNSPECIFIED', - traceId: buff, - spanId: buff, - attributes: - {'attributeMap': {}, 'droppedAttributesCount': 0} - } - ] - }); + time: { seconds: '123456', nanos: 789000000 }, + value: 'messageEvent', + }, + { + value: 'messageEvent', + messageEvent: { + compressedSize: '0', + id: '1', + type: 'RECEIVED', + uncompressedSize: '0', + }, + time: { seconds: '123456', nanos: 789000000 }, + }, + ], + }); - done(); + // Links + const buff = Buffer.from([255, 255]); + assert.deepStrictEqual(span.links, { + droppedLinksCount: 0, + link: [ + { + type: 'CHILD_LINKED_SPAN', + traceId: buff, + spanId: buff, + attributes: { + droppedAttributesCount: 0, + attributeMap: { + child_link_attribute_string: { + value: 'stringValue', + stringValue: { value: 'foo1', truncatedByteCount: 0 }, + }, + child_link_attribute_number: { + value: 'intValue', + intValue: '123', + }, + child_link_attribute_boolean: { + value: 'boolValue', + boolValue: true, + }, + }, + }, + }, + { + type: 'PARENT_LINKED_SPAN', + traceId: buff, + spanId: buff, + attributes: { attributeMap: {}, droppedAttributesCount: 0 }, + }, + ], }); + done(); + } + ); + rootSpan.end(); }); }); - - it('should adapt a span correctly without overflowing trace param limits', - (done) => { - const rootSpanOptions: TraceOptions = { - name: 'root', - kind: SpanKind.SERVER, - spanContext: { - traceId: hexId(), - spanId: hexId(), - traceState: 'foo=bar,baz=buzz', - options: 0x1 - } - }; - - tracing.tracer.startRootSpan(rootSpanOptions, (rootSpan: Span) => { - // Status - rootSpan.setStatus(CanonicalCode.OK); - - // Attribute - rootSpan.addAttribute('my_first_attribute', 'foo'); - rootSpan.addAttribute('my_second_attribute', 'foo2'); - - // Annotation - rootSpan.addAnnotation( - 'my_annotation', - {myString: 'bar', myNumber: 123, myBoolean: true}); - - // Message Event - const timeStamp = 123456789; - rootSpan.addMessageEvent(MessageEventType.SENT, 1, timeStamp); - rootSpan.addMessageEvent(MessageEventType.RECEIVED, 1, timeStamp); - - // Links - rootSpan.addLink('ffff', 'ffff', LinkType.CHILD_LINKED_SPAN, { - 'child_link_attribute_string': 'foo1', - 'child_link_attribute_number': 123, - 'child_link_attribute_boolean': true, - }); - rootSpan.addLink('ffff', 'ffff', LinkType.PARENT_LINKED_SPAN); - - server.on( - MockAgentEvent.ExportStreamMessageReceived, - (message: opencensus.proto.agent.trace.v1 - .ExportTraceServiceRequest) => { - assert.strictEqual(message.spans.length, 1); - const span = message.spans[0]; - // Name / Context - if (!span.name) { - assert.fail('span.name is null or undefined'); - return; - } - assert.strictEqual(span.name.value, 'root'); - assert.strictEqual(span.kind, 'SERVER'); - - if (!span.tracestate) { - assert.fail('span.tracestate is null or undefined'); - return; - } - assert.deepStrictEqual( - span.tracestate.entries, - [{key: 'foo', value: 'bar'}, {key: 'baz', value: 'buzz'}]); - - if (!span.status) { - assert.fail('span.status is null or undefined'); - } else { - assert.deepStrictEqual(span.status, {code: 0, message: ''}); - } - - // Attributes - if (!span.attributes) { - assert.fail('span.attributes is null or undefined'); - return; - } - assert.deepStrictEqual(span.attributes.attributeMap, { - my_first_attribute: { - value: 'stringValue', - stringValue: {value: 'foo', truncatedByteCount: 0} - }, - my_second_attribute: { - value: 'stringValue', - stringValue: {value: 'foo2', truncatedByteCount: 0} - } - }); - assert.strictEqual(span.attributes.droppedAttributesCount, 0); - - // Time Events - assert.deepStrictEqual(span.timeEvents, { - droppedAnnotationsCount: 0, - droppedMessageEventsCount: 0, - timeEvent: [ - { - value: 'annotation', - time: null, - annotation: { - description: - {value: 'my_annotation', truncatedByteCount: 0}, - attributes: { - attributeMap: { - myString: { - value: 'stringValue', - stringValue: - {value: 'bar', truncatedByteCount: 0} - }, - myNumber: {value: 'intValue', intValue: '123'}, - myBoolean: {value: 'boolValue', boolValue: true} - }, - droppedAttributesCount: 0 - } - } - }, - { - messageEvent: { - compressedSize: '0', - id: '1', - type: 'SENT', - uncompressedSize: '0' - }, - time: {seconds: '123456', nanos: 789000000}, - value: 'messageEvent' - }, - { - value: 'messageEvent', - messageEvent: { - compressedSize: '0', - id: '1', - type: 'RECEIVED', - uncompressedSize: '0' - }, - time: {seconds: '123456', nanos: 789000000}, - } - ] - }); - - // Links - const buff = Buffer.from([255, 255]); - assert.deepStrictEqual(span.links, { - droppedLinksCount: 0, - link: [ - { - type: 'CHILD_LINKED_SPAN', - traceId: buff, - spanId: buff, - attributes: { - droppedAttributesCount: 0, - attributeMap: { - child_link_attribute_string: { - value: 'stringValue', - stringValue: {value: 'foo1', truncatedByteCount: 0} - }, - child_link_attribute_number: - {value: 'intValue', intValue: '123'}, - child_link_attribute_boolean: - {value: 'boolValue', boolValue: true} - } - } - }, - { - type: 'PARENT_LINKED_SPAN', - traceId: buff, - spanId: buff, - attributes: - {'attributeMap': {}, 'droppedAttributesCount': 0} - } - ] - }); - - done(); - }); - - rootSpan.end(); - }); - }); }); diff --git a/packages/opencensus-exporter-prometheus/package-lock.json b/packages/opencensus-exporter-prometheus/package-lock.json index 8ecaba8bd..a11e10b63 100644 --- a/packages/opencensus-exporter-prometheus/package-lock.json +++ b/packages/opencensus-exporter-prometheus/package-lock.json @@ -236,9 +236,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -299,11 +299,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, "axios": { "version": "0.19.0", "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.0.tgz", @@ -313,53 +308,6 @@ "is-buffer": "^2.0.2" } }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -532,16 +480,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -624,8 +562,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -1198,37 +1135,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -1259,21 +1196,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1370,29 +1292,42 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } } } }, @@ -1629,15 +1564,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2543,6 +2473,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "prom-client": { "version": "11.1.1", "resolved": "https://registry.npmjs.org/prom-client/-/prom-client-11.1.1.tgz", @@ -2670,9 +2605,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2705,11 +2640,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2743,9 +2678,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2927,17 +2862,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -3181,29 +3116,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -3392,9 +3321,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-exporter-prometheus/package.json b/packages/opencensus-exporter-prometheus/package.json index 6a8c75080..e42d8bd81 100644 --- a/packages/opencensus-exporter-prometheus/package.json +++ b/packages/opencensus-exporter-prometheus/package.json @@ -55,7 +55,7 @@ "@types/node": "^10.12.12", "axios": "^0.19.0", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "^14.0.0", "ts-mocha": "^6.0.0", diff --git a/packages/opencensus-exporter-prometheus/src/prometheus-stats.ts b/packages/opencensus-exporter-prometheus/src/prometheus-stats.ts index 3c9cfe194..120603632 100644 --- a/packages/opencensus-exporter-prometheus/src/prometheus-stats.ts +++ b/packages/opencensus-exporter-prometheus/src/prometheus-stats.ts @@ -14,10 +14,28 @@ * limitations under the License. */ -import {AggregationType, DistributionData, ExporterConfig, logger, Logger, Measurement, StatsEventListener, TagKey, TagValue, View} from '@opencensus/core'; +import { + AggregationType, + DistributionData, + ExporterConfig, + logger, + Logger, + Measurement, + StatsEventListener, + TagKey, + TagValue, + View, +} from '@opencensus/core'; import * as express from 'express'; import * as http from 'http'; -import {Counter, Gauge, Histogram, labelValues, Metric, Registry} from 'prom-client'; +import { + Counter, + Gauge, + Histogram, + labelValues, + Metric, + Registry, +} from 'prom-client'; export interface PrometheusExporterOptions extends ExporterConfig { /** App prefix for metrics, if needed - default opencensus */ @@ -40,7 +58,7 @@ export class PrometheusStatsExporter implements StatsEventListener { port: 9464, startServer: false, contentType: 'text/plain; text/plain; version=0.0.13; charset=utf-8', - prefix: '' + prefix: '', }; private logger: Logger; @@ -58,7 +76,7 @@ export class PrometheusStatsExporter implements StatsEventListener { this.logger = options.logger || logger.logger(); this.port = options.port || PrometheusStatsExporter.DEFAULT_OPTIONS.port; this.prefix = - options.prefix || PrometheusStatsExporter.DEFAULT_OPTIONS.prefix; + options.prefix || PrometheusStatsExporter.DEFAULT_OPTIONS.prefix; /** Start the server if the startServer option is true */ if (options.startServer) { @@ -80,7 +98,10 @@ export class PrometheusStatsExporter implements StatsEventListener { * @param tags The tags to which the value is applied */ onRecord( - views: View[], measurement: Measurement, tags: Map) { + views: View[], + measurement: Measurement, + tags: Map + ) { for (const view of views) { this.updateMetric(view, measurement, tags); } @@ -100,17 +121,19 @@ export class PrometheusStatsExporter implements StatsEventListener { this.stopServer(); } - private getLabelValues(columns: TagKey[], tags: Map): - labelValues { + private getLabelValues( + columns: TagKey[], + tags: Map + ): labelValues { const labels: labelValues = {}; // TODO: Consider make original tags map with string:TagValue type. - const tagsWithStringKey: Map = new Map(); + const tagsWithStringKey: Map = new Map(); for (const key of tags.keys()) { tagsWithStringKey.set(key.name, tags.get(key)); } - columns.forEach((tagKey) => { + columns.forEach(tagKey => { if (tagsWithStringKey.has(tagKey.name)) { const tagValue = tagsWithStringKey.get(tagKey.name); if (tagValue) { @@ -135,9 +158,9 @@ export class PrometheusStatsExporter implements StatsEventListener { return metric; } - const labelNames = view.getColumns().map((tagKey) => tagKey.name); + const labelNames = view.getColumns().map(tagKey => tagKey.name); // Create a new metric if there is no one - const metricObj = {name: metricName, help: view.description, labelNames}; + const metricObj = { name: metricName, help: view.description, labelNames }; // Creating the metric based on aggregation type switch (view.aggregation) { @@ -154,7 +177,7 @@ export class PrometheusStatsExporter implements StatsEventListener { name: metricName, help: view.description, labelNames, - buckets: this.getBoundaries(view, tags) + buckets: this.getBoundaries(view, tags), }; metric = new Histogram(distribution); break; @@ -172,18 +195,24 @@ export class PrometheusStatsExporter implements StatsEventListener { * @param measurement Measurement with the new value to update the metric */ private updateMetric( - view: View, measurement: Measurement, tags: Map) { + view: View, + measurement: Measurement, + tags: Map + ) { const metric = this.registerMetric(view, tags); // Updating the metric based on metric instance type and aggregation type const labelValues = this.getLabelValues(view.getColumns(), tags); if (metric instanceof Counter) { metric.inc(labelValues); } else if ( - view.aggregation === AggregationType.SUM && metric instanceof Gauge) { + view.aggregation === AggregationType.SUM && + metric instanceof Gauge + ) { metric.inc(labelValues, measurement.value); } else if ( - view.aggregation === AggregationType.LAST_VALUE && - metric instanceof Gauge) { + view.aggregation === AggregationType.LAST_VALUE && + metric instanceof Gauge + ) { metric.set(labelValues, measurement.value); } else if (metric instanceof Histogram) { metric.observe(labelValues, measurement.value); @@ -221,9 +250,11 @@ export class PrometheusStatsExporter implements StatsEventListener { private validateDisallowedLeLabelForHistogram(labels: string[]): void { labels.forEach(label => { if (label === PrometheusStatsExporter.RESERVED_HISTOGRAM_LABEL) { - throw new Error(`${ - PrometheusStatsExporter - .RESERVED_HISTOGRAM_LABEL} is a reserved label keyword`); + throw new Error( + `${ + PrometheusStatsExporter.RESERVED_HISTOGRAM_LABEL + } is a reserved label keyword` + ); } }); } @@ -234,8 +265,7 @@ export class PrometheusStatsExporter implements StatsEventListener { * @param tags Tags used to get the DistributionData */ private getBoundaries(view: View, tags: Map): number[] { - const tagValues = - view.getColumns().map((tagKey) => (tags.get(tagKey) || null)); + const tagValues = view.getColumns().map(tagKey => tags.get(tagKey) || null); const data = view.getSnapshot(tagValues) as DistributionData; return data.buckets; } @@ -247,7 +277,9 @@ export class PrometheusStatsExporter implements StatsEventListener { const self = this; this.app.get('/metrics', (req, res) => { res.set( - 'Content-Type', PrometheusStatsExporter.DEFAULT_OPTIONS.contentType); + 'Content-Type', + PrometheusStatsExporter.DEFAULT_OPTIONS.contentType + ); res.end(this.registry.metrics()); }); diff --git a/packages/opencensus-exporter-prometheus/test/test-prometheus-stats.ts b/packages/opencensus-exporter-prometheus/test/test-prometheus-stats.ts index 7157d9506..40b047044 100644 --- a/packages/opencensus-exporter-prometheus/test/test-prometheus-stats.ts +++ b/packages/opencensus-exporter-prometheus/test/test-prometheus-stats.ts @@ -14,260 +14,346 @@ * limitations under the License. */ -import {AggregationType, globalStats, Measure, MeasureUnit, TagMap} from '@opencensus/core'; +import { + AggregationType, + globalStats, + Measure, + MeasureUnit, + TagMap, +} from '@opencensus/core'; import * as assert from 'assert'; import * as http from 'http'; -import {PrometheusStatsExporter} from '../src/'; +import { PrometheusStatsExporter } from '../src/'; describe('Prometheus Stats Exporter', () => { - const options = {port: 9464, startServer: false}; + const options = { port: 9464, startServer: false }; const prometheusServerUrl = `http://localhost:${options.port}/metrics`; - const tagKey1 = {name: 'tagKey1'}; - const tagValue1 = {value: 'tagValue1'}; - const tagKeys = [{name: 'tagKey1'}]; + const tagKey1 = { name: 'tagKey1' }; + const tagValue1 = { value: 'tagValue1' }; + const tagKeys = [{ name: 'tagKey1' }]; const tagMap = new TagMap(); tagMap.set(tagKey1, tagValue1); let exporter: PrometheusStatsExporter; let measure: Measure; - beforeEach((done) => { - measure = - globalStats.createMeasureDouble('testMeasureDouble', MeasureUnit.UNIT); + beforeEach(done => { + measure = globalStats.createMeasureDouble( + 'testMeasureDouble', + MeasureUnit.UNIT + ); exporter = new PrometheusStatsExporter(options); globalStats.registerExporter(exporter); exporter.startServer(done); }); - afterEach((done) => { + afterEach(done => { exporter.stopServer(done); globalStats.clear(); }); - it('should create a count aggregation', (done) => { + it('should create a count aggregation', done => { const view = globalStats.createView( - 'ocnodemetrics/countview', measure, AggregationType.COUNT, tagKeys, - 'A count aggregation example'); - const measurement = {measure, value: 2}; - const measurement2 = {measure, value: 3}; + 'ocnodemetrics/countview', + measure, + AggregationType.COUNT, + tagKeys, + 'A count aggregation example' + ); + const measurement = { measure, value: 2 }; + const measurement2 = { measure, value: 3 }; globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - http.get(prometheusServerUrl, (res) => { - res.on('data', (chunk) => { - const body = chunk.toString(); - const lines = body.split('\n'); + http + .get(prometheusServerUrl, res => { + res.on('data', chunk => { + const body = chunk.toString(); + const lines = body.split('\n'); - assert.strictEqual( - lines[0], - '# HELP ocnodemetrics_countview A count aggregation example'); - assert.strictEqual( - lines[1], '# TYPE ocnodemetrics_countview counter'); - assert.strictEqual( - lines[2], 'ocnodemetrics_countview{tagKey1="tagValue1"} 2'); - done(); - }); - }).on('error', done); + assert.strictEqual( + lines[0], + '# HELP ocnodemetrics_countview A count aggregation example' + ); + assert.strictEqual( + lines[1], + '# TYPE ocnodemetrics_countview counter' + ); + assert.strictEqual( + lines[2], + 'ocnodemetrics_countview{tagKey1="tagValue1"} 2' + ); + done(); + }); + }) + .on('error', done); }); - it('should create a sum aggregation', (done) => { - const measure = - globalStats.createMeasureDouble('testMeasureDouble', MeasureUnit.UNIT); + it('should create a sum aggregation', done => { + const measure = globalStats.createMeasureDouble( + 'testMeasureDouble', + MeasureUnit.UNIT + ); const view = globalStats.createView( - 'ocnodemetrics/sumview', measure, AggregationType.SUM, tagKeys, - 'A sum aggregation example'); - const measurement = {measure, value: 2}; - const measurement2 = {measure, value: 3}; + 'ocnodemetrics/sumview', + measure, + AggregationType.SUM, + tagKeys, + 'A sum aggregation example' + ); + const measurement = { measure, value: 2 }; + const measurement2 = { measure, value: 3 }; globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - http.get(prometheusServerUrl, (res) => { - res.on('data', (chunk) => { - const body = chunk.toString(); - const lines = body.split('\n'); + http + .get(prometheusServerUrl, res => { + res.on('data', chunk => { + const body = chunk.toString(); + const lines = body.split('\n'); - assert.strictEqual( - lines[0], - '# HELP ocnodemetrics_sumview A sum aggregation example'); - assert.strictEqual(lines[1], '# TYPE ocnodemetrics_sumview gauge'); - assert.strictEqual( - lines[2], 'ocnodemetrics_sumview{tagKey1="tagValue1"} 5'); - done(); - }); - }).on('error', done); + assert.strictEqual( + lines[0], + '# HELP ocnodemetrics_sumview A sum aggregation example' + ); + assert.strictEqual(lines[1], '# TYPE ocnodemetrics_sumview gauge'); + assert.strictEqual( + lines[2], + 'ocnodemetrics_sumview{tagKey1="tagValue1"} 5' + ); + done(); + }); + }) + .on('error', done); }); - it('should create a sum aggregation with empty tagMap', (done) => { - const measure = - globalStats.createMeasureDouble('testMeasureDouble', MeasureUnit.UNIT); + it('should create a sum aggregation with empty tagMap', done => { + const measure = globalStats.createMeasureDouble( + 'testMeasureDouble', + MeasureUnit.UNIT + ); const view = globalStats.createView( - 'ocnodemetrics/sumview1', measure, AggregationType.SUM, tagKeys, - 'A sum aggregation example'); - const measurement = {measure, value: 2}; - const measurement2 = {measure, value: 3}; + 'ocnodemetrics/sumview1', + measure, + AggregationType.SUM, + tagKeys, + 'A sum aggregation example' + ); + const measurement = { measure, value: 2 }; + const measurement2 = { measure, value: 3 }; globalStats.registerView(view); globalStats.record([measurement, measurement2]); - http.get(prometheusServerUrl, (res) => { - res.on('data', (chunk) => { - const body = chunk.toString(); - const lines = body.split('\n'); + http + .get(prometheusServerUrl, res => { + res.on('data', chunk => { + const body = chunk.toString(); + const lines = body.split('\n'); - assert.strictEqual( - lines[0], - '# HELP ocnodemetrics_sumview1 A sum aggregation example'); - assert.strictEqual(lines[1], '# TYPE ocnodemetrics_sumview1 gauge'); - assert.strictEqual(lines[2], 'ocnodemetrics_sumview1 5'); - done(); - }); - }).on('error', done); + assert.strictEqual( + lines[0], + '# HELP ocnodemetrics_sumview1 A sum aggregation example' + ); + assert.strictEqual(lines[1], '# TYPE ocnodemetrics_sumview1 gauge'); + assert.strictEqual(lines[2], 'ocnodemetrics_sumview1 5'); + done(); + }); + }) + .on('error', done); }); - it('should create a last value aggregation', (done) => { - const measure = - globalStats.createMeasureDouble('testMeasureDouble', MeasureUnit.UNIT); + it('should create a last value aggregation', done => { + const measure = globalStats.createMeasureDouble( + 'testMeasureDouble', + MeasureUnit.UNIT + ); const view = globalStats.createView( - 'ocnodemetrics/lastvalueview', measure, AggregationType.LAST_VALUE, - tagKeys, 'A last value aggregation example'); - const measurement = {measure, value: 2}; - const measurement2 = {measure, value: 3}; + 'ocnodemetrics/lastvalueview', + measure, + AggregationType.LAST_VALUE, + tagKeys, + 'A last value aggregation example' + ); + const measurement = { measure, value: 2 }; + const measurement2 = { measure, value: 3 }; globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - http.get(prometheusServerUrl, (res) => { - res.on('data', (chunk) => { - const body = chunk.toString(); - const lines = body.split('\n'); + http + .get(prometheusServerUrl, res => { + res.on('data', chunk => { + const body = chunk.toString(); + const lines = body.split('\n'); - assert.strictEqual( - lines[0], - '# HELP ocnodemetrics_lastvalueview A last value aggregation example'); - assert.strictEqual( - lines[1], '# TYPE ocnodemetrics_lastvalueview gauge'); - assert.strictEqual( - lines[2], 'ocnodemetrics_lastvalueview{tagKey1="tagValue1"} 3'); - done(); - }); - }).on('error', done); + assert.strictEqual( + lines[0], + '# HELP ocnodemetrics_lastvalueview A last value aggregation example' + ); + assert.strictEqual( + lines[1], + '# TYPE ocnodemetrics_lastvalueview gauge' + ); + assert.strictEqual( + lines[2], + 'ocnodemetrics_lastvalueview{tagKey1="tagValue1"} 3' + ); + done(); + }); + }) + .on('error', done); }); - it('should create a distribution aggregation', (done) => { - const measure = - globalStats.createMeasureDouble('testMeasureDouble', MeasureUnit.UNIT); + it('should create a distribution aggregation', done => { + const measure = globalStats.createMeasureDouble( + 'testMeasureDouble', + MeasureUnit.UNIT + ); const boundaries = [10, 20, 30, 40]; const view = globalStats.createView( - 'ocnodemetrics/distributionview', measure, AggregationType.DISTRIBUTION, - tagKeys, 'A distribution aggregation example', boundaries); - const measurement = {measure, value: 12}; - const measurement2 = {measure, value: 31}; + 'ocnodemetrics/distributionview', + measure, + AggregationType.DISTRIBUTION, + tagKeys, + 'A distribution aggregation example', + boundaries + ); + const measurement = { measure, value: 12 }; + const measurement2 = { measure, value: 31 }; globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - http.get(prometheusServerUrl, (res) => { - res.on('data', (chunk) => { - const body = chunk.toString(); - const lines = body.split('\n'); - assert.strictEqual( - lines[0], - '# HELP ocnodemetrics_distributionview A distribution aggregation example'); - assert.strictEqual( - lines[1], '# TYPE ocnodemetrics_distributionview histogram'); - assert.strictEqual( - lines[2], - 'ocnodemetrics_distributionview_bucket{le="10",tagKey1="tagValue1"} 0'); - assert.strictEqual( - lines[3], - 'ocnodemetrics_distributionview_bucket{le="20",tagKey1="tagValue1"} 1'); - assert.strictEqual( - lines[4], - 'ocnodemetrics_distributionview_bucket{le="30",tagKey1="tagValue1"} 1'); - assert.strictEqual( - lines[5], - 'ocnodemetrics_distributionview_bucket{le="40",tagKey1="tagValue1"} 2'); - assert.strictEqual( - lines[6], - 'ocnodemetrics_distributionview_bucket{le="+Inf",tagKey1="tagValue1"} 2'); - assert.strictEqual( - lines[7], - 'ocnodemetrics_distributionview_sum{tagKey1="tagValue1"} 43'); - assert.strictEqual( - lines[8], - 'ocnodemetrics_distributionview_count{tagKey1="tagValue1"} 2'); - done(); - }); - }).on('error', done); + http + .get(prometheusServerUrl, res => { + res.on('data', chunk => { + const body = chunk.toString(); + const lines = body.split('\n'); + assert.strictEqual( + lines[0], + '# HELP ocnodemetrics_distributionview A distribution aggregation example' + ); + assert.strictEqual( + lines[1], + '# TYPE ocnodemetrics_distributionview histogram' + ); + assert.strictEqual( + lines[2], + 'ocnodemetrics_distributionview_bucket{le="10",tagKey1="tagValue1"} 0' + ); + assert.strictEqual( + lines[3], + 'ocnodemetrics_distributionview_bucket{le="20",tagKey1="tagValue1"} 1' + ); + assert.strictEqual( + lines[4], + 'ocnodemetrics_distributionview_bucket{le="30",tagKey1="tagValue1"} 1' + ); + assert.strictEqual( + lines[5], + 'ocnodemetrics_distributionview_bucket{le="40",tagKey1="tagValue1"} 2' + ); + assert.strictEqual( + lines[6], + 'ocnodemetrics_distributionview_bucket{le="+Inf",tagKey1="tagValue1"} 2' + ); + assert.strictEqual( + lines[7], + 'ocnodemetrics_distributionview_sum{tagKey1="tagValue1"} 43' + ); + assert.strictEqual( + lines[8], + 'ocnodemetrics_distributionview_count{tagKey1="tagValue1"} 2' + ); + done(); + }); + }) + .on('error', done); }); - it('should throw error when labels contains "le" label name in histogram label names', - () => { - const measure = globalStats.createMeasureDouble( - 'testMeasureDouble', MeasureUnit.UNIT); - const tagKeyWithLe = {name: 'le'}; - const tagKeys = [tagKeyWithLe]; - const tagMap = new TagMap(); - tagMap.set(tagKeyWithLe, tagValue1); + it('should throw error when labels contains "le" label name in histogram label names', () => { + const measure = globalStats.createMeasureDouble( + 'testMeasureDouble', + MeasureUnit.UNIT + ); + const tagKeyWithLe = { name: 'le' }; + const tagKeys = [tagKeyWithLe]; + const tagMap = new TagMap(); + tagMap.set(tagKeyWithLe, tagValue1); - const boundaries = [10, 20, 30, 40]; - const view = globalStats.createView( - 'ocnodemetrics/distributionview1', measure, - AggregationType.DISTRIBUTION, tagKeys, - 'A distribution aggregation example', boundaries); - globalStats.registerView(view); - const measurement = {measure, value: 2}; + const boundaries = [10, 20, 30, 40]; + const view = globalStats.createView( + 'ocnodemetrics/distributionview1', + measure, + AggregationType.DISTRIBUTION, + tagKeys, + 'A distribution aggregation example', + boundaries + ); + globalStats.registerView(view); + const measurement = { measure, value: 2 }; - assert.throws(() => { - globalStats.record([measurement], tagMap); - }, /^Error: le is a reserved label keyword$/); - }); + assert.throws(() => { + globalStats.record([measurement], tagMap); + }, /^Error: le is a reserved label keyword$/); + }); }); describe('Prometheus Stats Exporter with prefix option', () => { - const options = {port: 9464, startServer: false, prefix: 'opencensus'}; + const options = { port: 9464, startServer: false, prefix: 'opencensus' }; const prometheusServerUrl = `http://localhost:${options.port}/metrics`; - const tagKeyWithLe = {name: 'le'}; - const tagValue1 = {value: 'tagValue1'}; + const tagKeyWithLe = { name: 'le' }; + const tagValue1 = { value: 'tagValue1' }; const tagKeys = [tagKeyWithLe]; const tagMap = new TagMap(); tagMap.set(tagKeyWithLe, tagValue1); let exporter: PrometheusStatsExporter; let measure: Measure; - beforeEach((done) => { - measure = - globalStats.createMeasureDouble('testMeasureDouble', MeasureUnit.UNIT); + beforeEach(done => { + measure = globalStats.createMeasureDouble( + 'testMeasureDouble', + MeasureUnit.UNIT + ); exporter = new PrometheusStatsExporter(options); globalStats.registerExporter(exporter); exporter.startServer(done); }); - afterEach((done) => { + afterEach(done => { exporter.stopServer(done); globalStats.clear(); }); - it('should create a count aggregation with le labels', (done) => { + it('should create a count aggregation with le labels', done => { const view = globalStats.createView( - 'test/key-1', measure, AggregationType.COUNT, tagKeys, - 'A count aggregation example'); - const measurement = {measure, value: 2}; - const measurement2 = {measure, value: 3}; + 'test/key-1', + measure, + AggregationType.COUNT, + tagKeys, + 'A count aggregation example' + ); + const measurement = { measure, value: 2 }; + const measurement2 = { measure, value: 3 }; globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - http.get(prometheusServerUrl, (res) => { - res.on('data', (chunk) => { - const body = chunk.toString(); - const lines = body.split('\n'); + http + .get(prometheusServerUrl, res => { + res.on('data', chunk => { + const body = chunk.toString(); + const lines = body.split('\n'); - assert.strictEqual( - lines[0], - '# HELP opencensus_test_key_1 A count aggregation example'); - assert.strictEqual( - lines[1], '# TYPE opencensus_test_key_1 counter'); - assert.strictEqual( - lines[2], 'opencensus_test_key_1{le="tagValue1"} 2'); - done(); - }); - }).on('error', done); + assert.strictEqual( + lines[0], + '# HELP opencensus_test_key_1 A count aggregation example' + ); + assert.strictEqual(lines[1], '# TYPE opencensus_test_key_1 counter'); + assert.strictEqual( + lines[2], + 'opencensus_test_key_1{le="tagValue1"} 2' + ); + done(); + }); + }) + .on('error', done); }); }); diff --git a/packages/opencensus-exporter-stackdriver/package-lock.json b/packages/opencensus-exporter-stackdriver/package-lock.json index 60ad99337..680d4f08e 100644 --- a/packages/opencensus-exporter-stackdriver/package-lock.json +++ b/packages/opencensus-exporter-stackdriver/package-lock.json @@ -174,9 +174,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -237,58 +237,6 @@ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -462,16 +410,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -554,8 +492,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -1130,37 +1067,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "pify": { "version": "4.0.1", @@ -1196,21 +1133,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1299,29 +1221,42 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } } } }, @@ -1563,15 +1498,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2483,6 +2413,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "propagate": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/propagate/-/propagate-1.0.0.tgz", @@ -2559,9 +2494,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2594,11 +2529,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2632,9 +2567,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2765,17 +2700,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -3011,29 +2946,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -3208,9 +3137,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-exporter-stackdriver/package.json b/packages/opencensus-exporter-stackdriver/package.json index cd4d64a46..d8c701a7c 100644 --- a/packages/opencensus-exporter-stackdriver/package.json +++ b/packages/opencensus-exporter-stackdriver/package.json @@ -55,7 +55,7 @@ "@types/nock": "^10.0.0", "@types/node": "^10.12.12", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nock": "^10.0.0", "nyc": "^14.0.0", diff --git a/packages/opencensus-exporter-stackdriver/src/common-utils.ts b/packages/opencensus-exporter-stackdriver/src/common-utils.ts index 3c4d5206b..a057c7260 100644 --- a/packages/opencensus-exporter-stackdriver/src/common-utils.ts +++ b/packages/opencensus-exporter-stackdriver/src/common-utils.ts @@ -14,10 +14,15 @@ * limitations under the License. */ -import {Labels} from '@opencensus/core'; +import { Labels } from '@opencensus/core'; import * as resource from '@opencensus/resource-util'; -import {CLOUD_RESOURCE, CONTAINER_RESOURCE, HOST_RESOURCE, K8S_RESOURCE} from '@opencensus/resource-util'; -import {MonitoredResource} from './types'; +import { + CLOUD_RESOURCE, + CONTAINER_RESOURCE, + HOST_RESOURCE, + K8S_RESOURCE, +} from '@opencensus/resource-util'; +import { MonitoredResource } from './types'; const STACKDRIVER_PROJECT_ID_KEY = 'project_id'; const AWS_REGION_VALUE_PREFIX = 'aws:'; @@ -26,57 +31,64 @@ const GCP_GCE_INSTANCE = 'gce_instance'; const AWS_EC2_INSTANCE = 'aws_ec2_instance'; /* Return a self-configured StackDriver monitored resource. */ -export async function getDefaultResource(projectId: string): - Promise { - const labels: Labels = {project_id: projectId}; +export async function getDefaultResource( + projectId: string +): Promise { + const labels: Labels = { project_id: projectId }; const autoDetectedResource = await resource.detectResource(); const [type, mappings] = getTypeAndMappings(autoDetectedResource.type); - Object.keys(mappings).forEach((key) => { + Object.keys(mappings).forEach(key => { if (autoDetectedResource.labels[mappings[key]]) { - if (type === AWS_EC2_INSTANCE && - mappings[key] === CLOUD_RESOURCE.REGION_KEY) { + if ( + type === AWS_EC2_INSTANCE && + mappings[key] === CLOUD_RESOURCE.REGION_KEY + ) { labels[key] = `${AWS_REGION_VALUE_PREFIX}${ - autoDetectedResource.labels[mappings[key]]}`; + autoDetectedResource.labels[mappings[key]] + }`; } else { labels[key] = autoDetectedResource.labels[mappings[key]]; } } }); - return {type, labels}; + return { type, labels }; } -function getTypeAndMappings(resourceType: string|null): [string, Labels] { +function getTypeAndMappings(resourceType: string | null): [string, Labels] { switch (resourceType) { case resource.GCP_GCE_INSTANCE_TYPE: // https://cloud.google.com/monitoring/api/resources#tag_gce_instance return [ - GCP_GCE_INSTANCE, { - 'project_id': STACKDRIVER_PROJECT_ID_KEY, - 'instance_id': HOST_RESOURCE.ID_KEY, - 'zone': CLOUD_RESOURCE.ZONE_KEY - } + GCP_GCE_INSTANCE, + { + project_id: STACKDRIVER_PROJECT_ID_KEY, + instance_id: HOST_RESOURCE.ID_KEY, + zone: CLOUD_RESOURCE.ZONE_KEY, + }, ]; case resource.K8S_CONTAINER_TYPE: // https://cloud.google.com/monitoring/api/resources#tag_k8s_container return [ - K8S_CONTAINER, { - 'project_id': STACKDRIVER_PROJECT_ID_KEY, - 'location': CLOUD_RESOURCE.ZONE_KEY, - 'cluster_name': K8S_RESOURCE.CLUSTER_NAME_KEY, - 'namespace_name': K8S_RESOURCE.NAMESPACE_NAME_KEY, - 'pod_name': K8S_RESOURCE.POD_NAME_KEY, - 'container_name': CONTAINER_RESOURCE.NAME_KEY - } + K8S_CONTAINER, + { + project_id: STACKDRIVER_PROJECT_ID_KEY, + location: CLOUD_RESOURCE.ZONE_KEY, + cluster_name: K8S_RESOURCE.CLUSTER_NAME_KEY, + namespace_name: K8S_RESOURCE.NAMESPACE_NAME_KEY, + pod_name: K8S_RESOURCE.POD_NAME_KEY, + container_name: CONTAINER_RESOURCE.NAME_KEY, + }, ]; case resource.AWS_EC2_INSTANCE_TYPE: // https://cloud.google.com/monitoring/api/resources#tag_aws_ec2_instance return [ - AWS_EC2_INSTANCE, { - 'project_id': STACKDRIVER_PROJECT_ID_KEY, - 'instance_id': HOST_RESOURCE.ID_KEY, - 'region': CLOUD_RESOURCE.REGION_KEY, - 'aws_account': CLOUD_RESOURCE.ACCOUNT_ID_KEY - } + AWS_EC2_INSTANCE, + { + project_id: STACKDRIVER_PROJECT_ID_KEY, + instance_id: HOST_RESOURCE.ID_KEY, + region: CLOUD_RESOURCE.REGION_KEY, + aws_account: CLOUD_RESOURCE.ACCOUNT_ID_KEY, + }, ]; default: return ['global', {}]; diff --git a/packages/opencensus-exporter-stackdriver/src/stackdriver-cloudtrace-utils.ts b/packages/opencensus-exporter-stackdriver/src/stackdriver-cloudtrace-utils.ts index b305f071e..629c8dcdb 100644 --- a/packages/opencensus-exporter-stackdriver/src/stackdriver-cloudtrace-utils.ts +++ b/packages/opencensus-exporter-stackdriver/src/stackdriver-cloudtrace-utils.ts @@ -28,8 +28,10 @@ const AGENT_LABEL_VALUE = createAttributeValue(AGENT_LABEL_VALUE_STRING); * @returns types.Links */ export function createLinks( - links: coreTypes.Link[], droppedLinksCount: number): types.Links { - return {link: links.map((link) => createLink(link)), droppedLinksCount}; + links: coreTypes.Link[], + droppedLinksCount: number +): types.Links { + return { link: links.map(link => createLink(link)), droppedLinksCount }; } /** @@ -40,16 +42,22 @@ export function createLinks( * @returns types.Attributes */ export function createAttributes( - attributes: coreTypes.Attributes, - resourceLabels: Record, - droppedAttributesCount: number): types.Attributes { - const attributesBuilder = - createAttributesBuilder(attributes, droppedAttributesCount); + attributes: coreTypes.Attributes, + resourceLabels: Record, + droppedAttributesCount: number +): types.Attributes { + const attributesBuilder = createAttributesBuilder( + attributes, + droppedAttributesCount + ); if (attributesBuilder.attributeMap) { attributesBuilder.attributeMap[AGENT_LABEL_KEY] = AGENT_LABEL_VALUE; } - attributesBuilder.attributeMap = - Object.assign({}, attributesBuilder.attributeMap, resourceLabels); + attributesBuilder.attributeMap = Object.assign( + {}, + attributesBuilder.attributeMap, + resourceLabels + ); return attributesBuilder; } @@ -62,47 +70,50 @@ export function createAttributes( * @returns types.TimeEvents */ export function createTimeEvents( - annotationTimedEvents: coreTypes.Annotation[], - messageEventTimedEvents: coreTypes.MessageEvent[], - droppedAnnotationsCount: number, - droppedMessageEventsCount: number): types.TimeEvents { + annotationTimedEvents: coreTypes.Annotation[], + messageEventTimedEvents: coreTypes.MessageEvent[], + droppedAnnotationsCount: number, + droppedMessageEventsCount: number +): types.TimeEvents { let timeEvents: types.TimeEvent[] = []; if (annotationTimedEvents) { - timeEvents = annotationTimedEvents.map( - (annotation) => ({ - time: new Date(annotation.timestamp).toISOString(), - annotation: { - description: stringToTruncatableString(annotation.description), - attributes: createAttributesBuilder(annotation.attributes, 0) - } - })); + timeEvents = annotationTimedEvents.map(annotation => ({ + time: new Date(annotation.timestamp).toISOString(), + annotation: { + description: stringToTruncatableString(annotation.description), + attributes: createAttributesBuilder(annotation.attributes, 0), + }, + })); } if (messageEventTimedEvents) { - timeEvents.push(...messageEventTimedEvents.map( - (messageEvent) => ({ - time: new Date(messageEvent.timestamp).toISOString(), - messageEvent: { - id: String(messageEvent.id), - type: createMessageEventType(messageEvent.type), - uncompressedSizeBytes: String(messageEvent.uncompressedSize || 0), - compressedSizeBytes: String(messageEvent.compressedSize || 0) - } - }))); + timeEvents.push( + ...messageEventTimedEvents.map(messageEvent => ({ + time: new Date(messageEvent.timestamp).toISOString(), + messageEvent: { + id: String(messageEvent.id), + type: createMessageEventType(messageEvent.type), + uncompressedSizeBytes: String(messageEvent.uncompressedSize || 0), + compressedSizeBytes: String(messageEvent.compressedSize || 0), + }, + })) + ); } return { timeEvent: timeEvents, droppedAnnotationsCount, - droppedMessageEventsCount + droppedMessageEventsCount, }; } -export function stringToTruncatableString(value: string): - types.TruncatableString { - return {value}; +export function stringToTruncatableString( + value: string +): types.TruncatableString { + return { value }; } export async function getResourceLabels( - monitoredResource: Promise) { + monitoredResource: Promise +) { const resource = await monitoredResource; const resourceLabels: Record = {}; if (resource.type === 'global') { @@ -116,13 +127,14 @@ export async function getResourceLabels( } function createAttributesBuilder( - attributes: coreTypes.Attributes, - droppedAttributesCount: number): types.Attributes { + attributes: coreTypes.Attributes, + droppedAttributesCount: number +): types.Attributes { const attributeMap: Record = {}; for (const key of Object.keys(attributes)) { attributeMap[key] = createAttributeValue(attributes[key]); } - return {attributeMap, droppedAttributesCount}; + return { attributeMap, droppedAttributesCount }; } function createLink(link: coreTypes.Link): types.Link { @@ -130,19 +142,20 @@ function createLink(link: coreTypes.Link): types.Link { const spanId = link.spanId; const type = createLinkType(link.type); const attributes = createAttributesBuilder(link.attributes, 0); - return {traceId, spanId, type, attributes}; + return { traceId, spanId, type, attributes }; } -function createAttributeValue(value: string|number| - boolean): types.AttributeValue { +function createAttributeValue( + value: string | number | boolean +): types.AttributeValue { switch (typeof value) { case 'number': // TODO: Consider to change to doubleValue when available in V2 API. - return {intValue: String(value)}; + return { intValue: String(value) }; case 'boolean': - return {boolValue: value as boolean}; + return { boolValue: value as boolean }; case 'string': - return {stringValue: stringToTruncatableString(value)}; + return { stringValue: stringToTruncatableString(value) }; default: throw new Error(`Unsupported type : ${typeof value}`); } @@ -156,7 +169,9 @@ function createMessageEventType(type: coreTypes.MessageEventType) { case coreTypes.MessageEventType.RECEIVED: { return types.Type.RECEIVED; } - default: { return types.Type.TYPE_UNSPECIFIED; } + default: { + return types.Type.TYPE_UNSPECIFIED; + } } } @@ -168,6 +183,8 @@ function createLinkType(type: coreTypes.LinkType) { case coreTypes.LinkType.PARENT_LINKED_SPAN: { return types.LinkType.PARENT_LINKED_SPAN; } - default: { return types.LinkType.UNSPECIFIED; } + default: { + return types.LinkType.UNSPECIFIED; + } } } diff --git a/packages/opencensus-exporter-stackdriver/src/stackdriver-cloudtrace.ts b/packages/opencensus-exporter-stackdriver/src/stackdriver-cloudtrace.ts index c15d3b67c..0af7c8631 100644 --- a/packages/opencensus-exporter-stackdriver/src/stackdriver-cloudtrace.ts +++ b/packages/opencensus-exporter-stackdriver/src/stackdriver-cloudtrace.ts @@ -14,15 +14,31 @@ * limitations under the License. */ -import {Exporter, ExporterBuffer, Span as OCSpan, SpanContext} from '@opencensus/core'; -import {logger, Logger} from '@opencensus/core'; -import {auth as globalAuth, GoogleAuth, JWT} from 'google-auth-library'; -import {google} from 'googleapis'; -import {getDefaultResource} from './common-utils'; -import {createAttributes, createLinks, createTimeEvents, getResourceLabels, stringToTruncatableString} from './stackdriver-cloudtrace-utils'; -import {AttributeValue, Span, SpansWithCredentials, StackdriverExporterOptions} from './types'; +import { + Exporter, + ExporterBuffer, + Span as OCSpan, + SpanContext, +} from '@opencensus/core'; +import { logger, Logger } from '@opencensus/core'; +import { auth as globalAuth, GoogleAuth, JWT } from 'google-auth-library'; +import { google } from 'googleapis'; +import { getDefaultResource } from './common-utils'; +import { + createAttributes, + createLinks, + createTimeEvents, + getResourceLabels, + stringToTruncatableString, +} from './stackdriver-cloudtrace-utils'; +import { + AttributeValue, + Span, + SpansWithCredentials, + StackdriverExporterOptions, +} from './types'; -google.options({headers: {'x-opencensus-outgoing-request': 0x1}}); +google.options({ headers: { 'x-opencensus-outgoing-request': 0x1 } }); const cloudTrace = google.cloudtrace('v2'); let auth = globalAuth; @@ -38,10 +54,11 @@ export class StackdriverTraceExporter implements Exporter { this.projectId = options.projectId; this.logger = options.logger || logger.logger(); this.exporterBuffer = new ExporterBuffer(this, options); - this.RESOURCE_LABELS = - getResourceLabels(getDefaultResource(this.projectId)); + this.RESOURCE_LABELS = getResourceLabels( + getDefaultResource(this.projectId) + ); if (options.credentials) { - auth = new GoogleAuth({credentials: options.credentials}); + auth = new GoogleAuth({ credentials: options.credentials }); } } @@ -67,15 +84,15 @@ export class StackdriverTraceExporter implements Exporter { const spanList = await this.translateSpan(spans); return this.authorize(spanList) - .then((spans: SpansWithCredentials) => { - return this.batchWriteSpans(spans); - }) - .catch(err => { - for (const span of spans) { - this.failBuffer.push(span.spanContext); - } - return err; - }); + .then((spans: SpansWithCredentials) => { + return this.batchWriteSpans(spans); + }) + .catch(err => { + for (const span of spans) { + this.failBuffer.push(span.spanContext); + } + return err; + }); } async translateSpan(spans: OCSpan[]) { @@ -84,7 +101,8 @@ export class StackdriverTraceExporter implements Exporter { spans.forEach(span => { // RootSpan data spanList.push( - this.createSpan(span, resourceLabel, span.numberOfChildren)); + this.createSpan(span, resourceLabel, span.numberOfChildren) + ); span.spans.forEach(child => { // Builds spans data spanList.push(this.createSpan(child, resourceLabel)); @@ -94,10 +112,13 @@ export class StackdriverTraceExporter implements Exporter { } private createSpan( - span: OCSpan, resourceLabels: Record, - numberOfChildren = 0): Span { - const spanName = - `projects/${this.projectId}/traces/${span.traceId}/spans/${span.id}`; + span: OCSpan, + resourceLabels: Record, + numberOfChildren = 0 + ): Span { + const spanName = `projects/${this.projectId}/traces/${span.traceId}/spans/${ + span.id + }`; const spanBuilder: Span = { name: spanName, @@ -106,15 +127,21 @@ export class StackdriverTraceExporter implements Exporter { startTime: span.startTime.toISOString(), endTime: span.endTime.toISOString(), attributes: createAttributes( - span.attributes, resourceLabels, span.droppedAttributesCount), + span.attributes, + resourceLabels, + span.droppedAttributesCount + ), timeEvents: createTimeEvents( - span.annotations, span.messageEvents, span.droppedAnnotationsCount, - span.droppedMessageEventsCount), + span.annotations, + span.messageEvents, + span.droppedAnnotationsCount, + span.droppedMessageEventsCount + ), links: createLinks(span.links, span.droppedLinksCount), - status: {code: span.status.code}, + status: { code: span.status.code }, sameProcessAsParentSpan: !span.remoteParent, childSpanCount: numberOfChildren, - stackTrace: undefined, // Unsupported by nodejs + stackTrace: undefined, // Unsupported by nodejs }; if (span.parentSpanId) { spanBuilder.parentSpanId = span.parentSpanId; @@ -137,7 +164,7 @@ export class StackdriverTraceExporter implements Exporter { // data to backend : // https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools. // cloudtrace.v2#google.devtools.cloudtrace.v2.TraceService - cloudTrace.projects.traces.batchWrite(spans, (err: Error|null) => { + cloudTrace.projects.traces.batchWrite(spans, (err: Error | null) => { if (err) { err.message = `batchWriteSpans error: ${err.message}`; this.logger.error(err.message); @@ -156,21 +183,23 @@ export class StackdriverTraceExporter implements Exporter { * authenticates the client and calls a method to send the spans data. * @param stackdriverSpans The spans to export */ - private async authorize(stackdriverSpans: Span[]): - Promise { + private async authorize( + stackdriverSpans: Span[] + ): Promise { try { - const client = await auth.getClient( - {scopes: ['https://www.googleapis.com/auth/cloud-platform']}); + const client = await auth.getClient({ + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + }); return { name: `projects/${this.projectId}`, - resource: {spans: stackdriverSpans}, - auth: client as JWT + resource: { spans: stackdriverSpans }, + auth: client as JWT, }; } catch (err) { err.message = `authorize error: ${err.message}`; this.logger.error(err.message); - throw (err); + throw err; } } } diff --git a/packages/opencensus-exporter-stackdriver/src/stackdriver-monitoring-utils.ts b/packages/opencensus-exporter-stackdriver/src/stackdriver-monitoring-utils.ts index a4e883ba3..277783626 100644 --- a/packages/opencensus-exporter-stackdriver/src/stackdriver-monitoring-utils.ts +++ b/packages/opencensus-exporter-stackdriver/src/stackdriver-monitoring-utils.ts @@ -14,17 +14,40 @@ * limitations under the License. */ -import {BucketOptions, DistributionBucket, DistributionValue, Exemplar as OCExemplar, LabelKey, LabelValue, Metric, MetricDescriptor as OCMetricDescriptor, MetricDescriptorType, TimeSeriesPoint, Timestamp} from '@opencensus/core'; +import { + BucketOptions, + DistributionBucket, + DistributionValue, + Exemplar as OCExemplar, + LabelKey, + LabelValue, + Metric, + MetricDescriptor as OCMetricDescriptor, + MetricDescriptorType, + TimeSeriesPoint, + Timestamp, +} from '@opencensus/core'; import * as os from 'os'; import * as path from 'path'; -import {Any, Distribution, Exemplar, LabelDescriptor, MetricDescriptor, MetricKind, MonitoredResource, Point, TimeSeries, ValueType} from './types'; +import { + Any, + Distribution, + Exemplar, + LabelDescriptor, + MetricDescriptor, + MetricKind, + MonitoredResource, + Point, + TimeSeries, + ValueType, +} from './types'; const OPENCENSUS_TASK = 'opencensus_task'; const OPENCENSUS_TASK_DESCRIPTION = 'Opencensus task identifier'; export const OPENCENSUS_TASK_VALUE_DEFAULT = generateDefaultTaskValue(); const EXEMPLAR_ATTACHMENT_TYPE_STRING = - 'type.googleapis.com/google.protobuf.StringValue'; + 'type.googleapis.com/google.protobuf.StringValue'; // TODO: add support for SpanContext attachment. // const EXEMPLAR_ATTACHMENT_TYPE_SPAN_CONTEXT = // 'type.googleapis.com/google.monitoring.v3.SpanContext'; @@ -36,8 +59,10 @@ const ATTACHMENT_KEY_SPAN_CONTEXT = 'SpanContext'; /** Converts a OpenCensus MetricDescriptor to a StackDriver MetricDescriptor. */ export function createMetricDescriptorData( - metricDescriptor: OCMetricDescriptor, metricPrefix: string, - displayNamePrefix: string): MetricDescriptor { + metricDescriptor: OCMetricDescriptor, + metricPrefix: string, + displayNamePrefix: string +): MetricDescriptor { return { type: createMetricType(metricDescriptor.name, metricPrefix), description: metricDescriptor.description, @@ -45,7 +70,7 @@ export function createMetricDescriptorData( metricKind: createMetricKind(metricDescriptor.type), valueType: createValueType(metricDescriptor.type), unit: metricDescriptor.unit, - labels: createLabelDescriptor(metricDescriptor.labelKeys) + labels: createLabelDescriptor(metricDescriptor.labelKeys), }; } @@ -54,8 +79,10 @@ export function createMetricDescriptorData( * uploaded to StackDriver. */ export function createTimeSeriesList( - metric: Metric, monitoredResource: MonitoredResource, - metricPrefix: string): TimeSeries[] { + metric: Metric, + monitoredResource: MonitoredResource, + metricPrefix: string +): TimeSeries[] { const timeSeriesList: TimeSeries[] = []; // TODO(mayurkale): Use Resource API here, once available (PR#173) @@ -65,14 +92,17 @@ export function createTimeSeriesList( for (const timeSeries of metric.timeseries) { timeSeriesList.push({ - metric: - createMetric(metricDescriptor, timeSeries.labelValues, metricPrefix), + metric: createMetric( + metricDescriptor, + timeSeries.labelValues, + metricPrefix + ), resource: monitoredResource, metricKind, valueType, points: timeSeries.points.map(point => { return createPoint(point, valueType, timeSeries.startTimestamp); - }) + }), }); } return timeSeriesList; @@ -89,33 +119,42 @@ function createDisplayName(name: string, displayNamePrefix: string): string { } /** Converts a OpenCensus Type to a StackDriver MetricKind. */ -function createMetricKind(metricDescriptorType: MetricDescriptorType): - MetricKind { - if (metricDescriptorType === MetricDescriptorType.GAUGE_INT64 || - metricDescriptorType === MetricDescriptorType.GAUGE_DOUBLE) { +function createMetricKind( + metricDescriptorType: MetricDescriptorType +): MetricKind { + if ( + metricDescriptorType === MetricDescriptorType.GAUGE_INT64 || + metricDescriptorType === MetricDescriptorType.GAUGE_DOUBLE + ) { return MetricKind.GAUGE; } else if ( - metricDescriptorType === MetricDescriptorType.CUMULATIVE_INT64 || - metricDescriptorType === MetricDescriptorType.CUMULATIVE_DOUBLE || - metricDescriptorType === MetricDescriptorType.CUMULATIVE_DISTRIBUTION) { + metricDescriptorType === MetricDescriptorType.CUMULATIVE_INT64 || + metricDescriptorType === MetricDescriptorType.CUMULATIVE_DOUBLE || + metricDescriptorType === MetricDescriptorType.CUMULATIVE_DISTRIBUTION + ) { return MetricKind.CUMULATIVE; } return MetricKind.UNSPECIFIED; } /** Converts a OpenCensus Type to a StackDriver ValueType. */ -function createValueType(metricDescriptorType: MetricDescriptorType): - ValueType { - if (metricDescriptorType === MetricDescriptorType.CUMULATIVE_DOUBLE || - metricDescriptorType === MetricDescriptorType.GAUGE_DOUBLE) { +function createValueType( + metricDescriptorType: MetricDescriptorType +): ValueType { + if ( + metricDescriptorType === MetricDescriptorType.CUMULATIVE_DOUBLE || + metricDescriptorType === MetricDescriptorType.GAUGE_DOUBLE + ) { return ValueType.DOUBLE; } else if ( - metricDescriptorType === MetricDescriptorType.GAUGE_INT64 || - metricDescriptorType === MetricDescriptorType.CUMULATIVE_INT64) { + metricDescriptorType === MetricDescriptorType.GAUGE_INT64 || + metricDescriptorType === MetricDescriptorType.CUMULATIVE_INT64 + ) { return ValueType.INT64; } else if ( - metricDescriptorType === MetricDescriptorType.GAUGE_DISTRIBUTION || - metricDescriptorType === MetricDescriptorType.CUMULATIVE_DISTRIBUTION) { + metricDescriptorType === MetricDescriptorType.GAUGE_DISTRIBUTION || + metricDescriptorType === MetricDescriptorType.CUMULATIVE_DISTRIBUTION + ) { return ValueType.DISTRIBUTION; } else { return ValueType.VALUE_TYPE_UNSPECIFIED; @@ -124,32 +163,36 @@ function createValueType(metricDescriptorType: MetricDescriptorType): /** Constructs a LabelDescriptor from a LabelKey. */ function createLabelDescriptor(labelKeys: LabelKey[]): LabelDescriptor[] { - const labelDescriptorList: LabelDescriptor[] = - labelKeys.map(labelKey => ({ - key: labelKey.key, - valueType: 'STRING', // Now we only support String type. - description: labelKey.description - })); + const labelDescriptorList: LabelDescriptor[] = labelKeys.map(labelKey => ({ + key: labelKey.key, + valueType: 'STRING', // Now we only support String type. + description: labelKey.description, + })); // add default "opencensus_task" label. labelDescriptorList.push({ key: OPENCENSUS_TASK, valueType: 'STRING', - description: OPENCENSUS_TASK_DESCRIPTION + description: OPENCENSUS_TASK_DESCRIPTION, }); return labelDescriptorList; } /** Creates a Metric using the LabelKeys and LabelValues. */ function createMetric( - metricDescriptor: OCMetricDescriptor, labelValues: LabelValue[], - metricPrefix: string): {type: string; labels: {[key: string]: string};} { + metricDescriptor: OCMetricDescriptor, + labelValues: LabelValue[], + metricPrefix: string +): { type: string; labels: { [key: string]: string } } { const type = createMetricType(metricDescriptor.name, metricPrefix); - const labels: {[key: string]: string} = {}; + const labels: { [key: string]: string } = {}; for (let i = 0; i < labelValues.length; i++) { const value = labelValues[i].value; - if (value !== null && value !== undefined && - metricDescriptor.labelKeys[i]) { + if ( + value !== null && + value !== undefined && + metricDescriptor.labelKeys[i] + ) { labels[metricDescriptor.labelKeys[i].key] = value; } else { // TODO(mayurkale) : consider to throw an error when LabelValue and @@ -157,34 +200,36 @@ function createMetric( } } labels[OPENCENSUS_TASK] = OPENCENSUS_TASK_VALUE_DEFAULT; - return {type, labels}; + return { type, labels }; } /** * Converts timeseries's point, so that metric can be uploaded to StackDriver. */ function createPoint( - point: TimeSeriesPoint, valueType: ValueType, - startTimeStamp?: Timestamp): Point { + point: TimeSeriesPoint, + valueType: ValueType, + startTimeStamp?: Timestamp +): Point { const value = createValue(valueType, point); const endTime = toISOString(point.timestamp); if (startTimeStamp) { // Must be present for cumulative metrics. const startTime = toISOString(startTimeStamp); - return {interval: {startTime, endTime}, value}; + return { interval: { startTime, endTime }, value }; } - return {interval: {endTime}, value}; + return { interval: { endTime }, value }; } /** Converts a OpenCensus Point's value to a StackDriver Point value. */ function createValue(valueType: ValueType, point: TimeSeriesPoint) { if (valueType === ValueType.INT64) { - return {int64Value: point.value as number}; + return { int64Value: point.value as number }; } else if (valueType === ValueType.DOUBLE) { - return {doubleValue: point.value as number}; + return { doubleValue: point.value as number }; } else if (valueType === ValueType.DISTRIBUTION) { return { - distributionValue: createDistribution(point.value as DistributionValue) + distributionValue: createDistribution(point.value as DistributionValue), }; } throw Error(`unsupported value type: ${valueType}`); @@ -197,11 +242,12 @@ function createDistribution(distribution: DistributionValue): Distribution { mean: distribution.count === 0 ? 0 : distribution.sum / distribution.count, sumOfSquaredDeviation: distribution.sumOfSquaredDeviation, bucketOptions: { - explicitBuckets: - {bounds: createExplicitBucketOptions(distribution.bucketOptions)} + explicitBuckets: { + bounds: createExplicitBucketOptions(distribution.bucketOptions), + }, }, bucketCounts: createBucketCounts(distribution.buckets), - exemplars: createExemplars(distribution.buckets) + exemplars: createExemplars(distribution.buckets), }; } @@ -230,32 +276,33 @@ function createBucketCounts(buckets: DistributionBucket[]): number[] { /** Converts a OpenCensus Buckets to a list of proto Exemplars. */ function createExemplars(buckets: DistributionBucket[]): Exemplar[] { - return buckets.filter((bucket => !!bucket.exemplar)) - .map((bucket) => ({ - value: bucket.exemplar!.value, - timestamp: toISOString(bucket.exemplar!.timestamp), - attachments: _createAttachments(bucket.exemplar!) - })) - .filter((exemplar) => exemplar.attachments.length > 0); + return buckets + .filter(bucket => !!bucket.exemplar) + .map(bucket => ({ + value: bucket.exemplar!.value, + timestamp: toISOString(bucket.exemplar!.timestamp), + attachments: _createAttachments(bucket.exemplar!), + })) + .filter(exemplar => exemplar.attachments.length > 0); } function _createAttachments(exemplar: OCExemplar): Any[] { return Object.keys(exemplar.attachments) - .map((key) => { - if (key === ATTACHMENT_KEY_SPAN_CONTEXT) { - // TODO: add support for SpanContext - // attachment. - return null; - } else { - // Everything else will be treated as plain - // strings for now. - return { - '@type': EXEMPLAR_ATTACHMENT_TYPE_STRING, - value: exemplar.attachments[key] - }; - } - }) - .filter(attachment => !!attachment) as Any[]; + .map(key => { + if (key === ATTACHMENT_KEY_SPAN_CONTEXT) { + // TODO: add support for SpanContext + // attachment. + return null; + } else { + // Everything else will be treated as plain + // strings for now. + return { + '@type': EXEMPLAR_ATTACHMENT_TYPE_STRING, + value: exemplar.attachments[key], + }; + } + }) + .filter(attachment => !!attachment) as Any[]; } /** Returns a task label value in the format of 'nodejs-@'. */ @@ -289,5 +336,5 @@ export const TEST_ONLY = { createDistribution, createExplicitBucketOptions, createValue, - createBucketCounts + createBucketCounts, }; diff --git a/packages/opencensus-exporter-stackdriver/src/stackdriver-monitoring.ts b/packages/opencensus-exporter-stackdriver/src/stackdriver-monitoring.ts index 7d9eff29d..e1a914673 100644 --- a/packages/opencensus-exporter-stackdriver/src/stackdriver-monitoring.ts +++ b/packages/opencensus-exporter-stackdriver/src/stackdriver-monitoring.ts @@ -14,22 +14,42 @@ * limitations under the License. */ -import {logger, Logger, Measurement, Metric, MetricDescriptor as OCMetricDescriptor, MetricProducerManager, Metrics, StatsEventListener, TagKey, TagValue, version, View} from '@opencensus/core'; -import {auth as globalAuth, GoogleAuth, JWT} from 'google-auth-library'; -import {google} from 'googleapis'; -import {getDefaultResource} from './common-utils'; -import {createMetricDescriptorData, createTimeSeriesList} from './stackdriver-monitoring-utils'; -import {MonitoredResource, StackdriverExporterOptions, TimeSeries} from './types'; +import { + logger, + Logger, + Measurement, + Metric, + MetricDescriptor as OCMetricDescriptor, + MetricProducerManager, + Metrics, + StatsEventListener, + TagKey, + TagValue, + version, + View, +} from '@opencensus/core'; +import { auth as globalAuth, GoogleAuth, JWT } from 'google-auth-library'; +import { google } from 'googleapis'; +import { getDefaultResource } from './common-utils'; +import { + createMetricDescriptorData, + createTimeSeriesList, +} from './stackdriver-monitoring-utils'; +import { + MonitoredResource, + StackdriverExporterOptions, + TimeSeries, +} from './types'; const OC_USER_AGENT = { product: 'opencensus-node', - version + version, }; const OC_HEADER = { - 'x-opencensus-outgoing-request': 0x1 + 'x-opencensus-outgoing-request': 0x1, }; -google.options({headers: OC_HEADER}); +google.options({ headers: OC_HEADER }); const monitoring = google.monitoring('v3'); let auth = globalAuth; @@ -43,29 +63,32 @@ export class StackdriverStatsExporter implements StatsEventListener { private timer!: NodeJS.Timer; static readonly DEFAULT_DISPLAY_NAME_PREFIX: string = 'OpenCensus'; static readonly CUSTOM_OPENCENSUS_DOMAIN: string = - 'custom.googleapis.com/opencensus'; + 'custom.googleapis.com/opencensus'; static readonly PERIOD: number = 60000; - private registeredMetricDescriptors: Map = - new Map(); + private registeredMetricDescriptors: Map< + string, + OCMetricDescriptor + > = new Map(); private DEFAULT_RESOURCE: Promise; logger: Logger; constructor(options: StackdriverExporterOptions) { - this.period = options.period !== undefined ? - options.period : - StackdriverStatsExporter.PERIOD; + this.period = + options.period !== undefined + ? options.period + : StackdriverStatsExporter.PERIOD; this.projectId = options.projectId; this.metricPrefix = - options.prefix || StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN; + options.prefix || StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN; this.displayNamePrefix = - options.prefix || StackdriverStatsExporter.DEFAULT_DISPLAY_NAME_PREFIX; + options.prefix || StackdriverStatsExporter.DEFAULT_DISPLAY_NAME_PREFIX; this.logger = options.logger || logger.logger(); if (options.onMetricUploadError) { this.onMetricUploadError = options.onMetricUploadError; } this.DEFAULT_RESOURCE = getDefaultResource(this.projectId); if (options.credentials) { - auth = new GoogleAuth({credentials: options.credentials}); + auth = new GoogleAuth({ credentials: options.credentials }); } } @@ -90,13 +113,13 @@ export class StackdriverStatsExporter implements StatsEventListener { */ async export() { const metricsList: Metric[] = []; - const metricProducerManager: MetricProducerManager = - Metrics.getMetricProducerManager(); + const metricProducerManager: MetricProducerManager = Metrics.getMetricProducerManager(); for (const metricProducer of metricProducerManager.getAllMetricProducer()) { for (const metric of metricProducer.getMetrics()) { // TODO(mayurkale): OPTIMIZATION: consider to call in parallel. - const isRegistered = - await this.registerMetricDescriptor(metric.descriptor); + const isRegistered = await this.registerMetricDescriptor( + metric.descriptor + ); if (metric && isRegistered) { metricsList.push(metric); } @@ -113,8 +136,9 @@ export class StackdriverStatsExporter implements StatsEventListener { * @param metricDescriptor The OpenCensus MetricDescriptor. */ private async registerMetricDescriptor(metricDescriptor: OCMetricDescriptor) { - const existingMetricDescriptor = - this.registeredMetricDescriptors.get(metricDescriptor.name); + const existingMetricDescriptor = this.registeredMetricDescriptors.get( + metricDescriptor.name + ); if (existingMetricDescriptor) { if (existingMetricDescriptor === metricDescriptor) { @@ -122,21 +146,23 @@ export class StackdriverStatsExporter implements StatsEventListener { return true; } else { this.logger.warn( - `A different metric with the same name is already registered: ${ - existingMetricDescriptor}`); + `A different metric with the same name is already registered: ${existingMetricDescriptor}` + ); return false; } } const isRegistered = await this.createMetricDescriptor(metricDescriptor) - .then(() => { - this.registeredMetricDescriptors.set( - metricDescriptor.name, metricDescriptor); - return true; - }) - .catch((err) => { - this.logger.error(err); - return false; - }); + .then(() => { + this.registeredMetricDescriptors.set( + metricDescriptor.name, + metricDescriptor + ); + return true; + }) + .catch(err => { + this.logger.error(err); + return false; + }); return isRegistered; } @@ -149,8 +175,9 @@ export class StackdriverStatsExporter implements StatsEventListener { const timeSeries: TimeSeries[] = []; const monitoredResource = await this.DEFAULT_RESOURCE; for (const metric of metricsList) { - timeSeries.push(...createTimeSeriesList( - metric, monitoredResource, this.metricPrefix)); + timeSeries.push( + ...createTimeSeriesList(metric, monitoredResource, this.metricPrefix) + ); } if (timeSeries.length === 0) { @@ -160,18 +187,19 @@ export class StackdriverStatsExporter implements StatsEventListener { return this.authorize().then(authClient => { const request = { name: `projects/${this.projectId}`, - resource: {timeSeries}, - auth: authClient + resource: { timeSeries }, + auth: authClient, }; return new Promise((resolve, reject) => { monitoring.projects.timeSeries.create( - request, {headers: OC_HEADER, userAgentDirectives: [OC_USER_AGENT]}, - (err: Error|null) => { - this.logger.debug( - 'sent time series', request.resource.timeSeries); - err ? reject(err) : resolve(); - }); + request, + { headers: OC_HEADER, userAgentDirectives: [OC_USER_AGENT] }, + (err: Error | null) => { + this.logger.debug('sent time series', request.resource.timeSeries); + err ? reject(err) : resolve(); + } + ); }); }); } @@ -181,30 +209,32 @@ export class StackdriverStatsExporter implements StatsEventListener { * @param metricDescriptor The OpenCensus MetricDescriptor. */ private createMetricDescriptor(metricDescriptor: OCMetricDescriptor) { - return this.authorize().then((authClient) => { + return this.authorize().then(authClient => { const request = { name: `projects/${this.projectId}`, resource: createMetricDescriptorData( - metricDescriptor, this.metricPrefix, this.displayNamePrefix), - auth: authClient + metricDescriptor, + this.metricPrefix, + this.displayNamePrefix + ), + auth: authClient, }; return new Promise((resolve, reject) => { - monitoring.projects.metricDescriptors.create( - request, - {headers: OC_HEADER, userAgentDirectives: [OC_USER_AGENT]}, - (err: Error|null) => { - this.logger.debug( - 'sent metric descriptor', request.resource); - err ? reject(err) : resolve(); - }); - }) - .catch((err) => { - this.logger.error( - `StackdriverStatsExporter: Failed to write data: ${ - err.message}`); - this.stop(); - }); + monitoring.projects.metricDescriptors.create( + request, + { headers: OC_HEADER, userAgentDirectives: [OC_USER_AGENT] }, + (err: Error | null) => { + this.logger.debug('sent metric descriptor', request.resource); + err ? reject(err) : resolve(); + } + ); + }).catch(err => { + this.logger.error( + `StackdriverStatsExporter: Failed to write data: ${err.message}` + ); + this.stop(); + }); }); } @@ -221,8 +251,9 @@ export class StackdriverStatsExporter implements StatsEventListener { * and authenticates the client. */ private async authorize(): Promise { - const client = await auth.getClient( - {scopes: ['https://www.googleapis.com/auth/cloud-platform']}); + const client = await auth.getClient({ + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + }); return client as JWT; } @@ -241,5 +272,8 @@ export class StackdriverStatsExporter implements StatsEventListener { * @param tags The tags to which the value is applied */ onRecord( - views: View[], measurement: Measurement, tags: Map) {} + views: View[], + measurement: Measurement, + tags: Map + ) {} } diff --git a/packages/opencensus-exporter-stackdriver/src/types.ts b/packages/opencensus-exporter-stackdriver/src/types.ts index 8712bd998..e3e96a573 100644 --- a/packages/opencensus-exporter-stackdriver/src/types.ts +++ b/packages/opencensus-exporter-stackdriver/src/types.ts @@ -14,64 +14,64 @@ * limitations under the License. */ -import {Bucket, ExporterConfig} from '@opencensus/core'; -import {JWT, JWTInput} from 'google-auth-library'; - -export type Span = { - name?: string, - spanId?: string, - parentSpanId?: string, - displayName?: TruncatableString, - startTime?: string, - endTime?: string, - attributes?: Attributes, - stackTrace?: StackTrace, - timeEvents?: TimeEvents, - links?: Links, - status?: Status, - sameProcessAsParentSpan?: boolean, - childSpanCount?: number -}; - -export type Attributes = { - attributeMap?: {[key: string]: AttributeValue;}; +import { Bucket, ExporterConfig } from '@opencensus/core'; +import { JWT, JWTInput } from 'google-auth-library'; + +export interface Span { + name?: string; + spanId?: string; + parentSpanId?: string; + displayName?: TruncatableString; + startTime?: string; + endTime?: string; + attributes?: Attributes; + stackTrace?: StackTrace; + timeEvents?: TimeEvents; + links?: Links; + status?: Status; + sameProcessAsParentSpan?: boolean; + childSpanCount?: number; +} + +export interface Attributes { + attributeMap?: { [key: string]: AttributeValue }; droppedAttributesCount?: number; -}; +} -export type AttributeValue = { +export interface AttributeValue { boolValue?: boolean; intValue?: string; stringValue?: TruncatableString; -}; +} -export type TruncatableString = { +export interface TruncatableString { value?: string; truncatedByteCount?: number; -}; +} -export type Links = { +export interface Links { droppedLinksCount?: number; link?: Link[]; -}; +} -export type Link = { +export interface Link { attributes?: Attributes; spanId?: string; traceId?: string; type?: LinkType; -}; +} -export type StackTrace = { +export interface StackTrace { stackFrames?: StackFrames; stackTraceHashId?: string; -}; +} -export type StackFrames = { +export interface StackFrames { droppedFramesCount?: number; frame?: StackFrame[]; -}; +} -export type StackFrame = { +export interface StackFrame { columnNumber?: string; fileName?: TruncatableString; functionName?: TruncatableString; @@ -79,57 +79,57 @@ export type StackFrame = { loadModule?: Module; originalFunctionName?: TruncatableString; sourceVersion?: TruncatableString; -}; +} -export type Module = { +export interface Module { buildId?: TruncatableString; module?: TruncatableString; -}; +} -export type Status = { +export interface Status { code?: number; message?: string; -}; +} -export type TimeEvents = { +export interface TimeEvents { droppedAnnotationsCount?: number; droppedMessageEventsCount?: number; timeEvent?: TimeEvent[]; -}; +} -export type TimeEvent = { +export interface TimeEvent { annotation?: Annotation; messageEvent?: MessageEvent; time?: string; -}; +} -export type Annotation = { +export interface Annotation { attributes?: Attributes; description?: TruncatableString; -}; +} -export type MessageEvent = { +export interface MessageEvent { id?: string; type?: Type; compressedSizeBytes?: string; uncompressedSizeBytes?: string; -}; +} export enum Type { TYPE_UNSPECIFIED = 0, SENT = 1, - RECEIVED = 2 + RECEIVED = 2, } export enum LinkType { UNSPECIFIED = 0, CHILD_LINKED_SPAN = 1, - PARENT_LINKED_SPAN = 2 + PARENT_LINKED_SPAN = 2, } export interface SpansWithCredentials { name: string; - resource: {spans: {}}; + resource: { spans: {} }; auth: JWT; } @@ -168,14 +168,14 @@ export enum MetricKind { UNSPECIFIED = 'METRIC_KIND_UNSPECIFIED', GAUGE = 'GAUGE', DELTA = 'DELTA', - CUMULATIVE = 'CUMULATIVE' + CUMULATIVE = 'CUMULATIVE', } export enum ValueType { VALUE_TYPE_UNSPECIFIED = 'VALUE_TYPE_UNSPECIFIED', INT64 = 'INT64', DOUBLE = 'DOUBLE', - DISTRIBUTION = 'DISTRIBUTION' + DISTRIBUTION = 'DISTRIBUTION', } export interface LabelDescriptor { @@ -198,13 +198,13 @@ export interface Distribution { count: number; mean: number; sumOfSquaredDeviation: number; - bucketOptions: {explicitBuckets: {bounds: Bucket[];}}; + bucketOptions: { explicitBuckets: { bounds: Bucket[] } }; bucketCounts: number[]; exemplars?: Exemplar[]; } export interface Point { - interval: {endTime: string, startTime?: string}; + interval: { endTime: string; startTime?: string }; value: { boolValue?: boolean; int64Value?: number; @@ -215,7 +215,7 @@ export interface Point { } export interface TimeSeries { - metric: {type: string; labels: {[key: string]: string};}; + metric: { type: string; labels: { [key: string]: string } }; resource: MonitoredResource; metricKind: MetricKind; valueType: ValueType; @@ -228,7 +228,7 @@ export interface MonitoredResource { type: string; /** Set of labels that describe the resource. */ - labels: {[key: string]: string}; + labels: { [key: string]: string }; } /** diff --git a/packages/opencensus-exporter-stackdriver/test/nocks.ts b/packages/opencensus-exporter-stackdriver/test/nocks.ts index 4e8fd7e71..30ee20a6b 100644 --- a/packages/opencensus-exporter-stackdriver/test/nocks.ts +++ b/packages/opencensus-exporter-stackdriver/test/nocks.ts @@ -22,106 +22,130 @@ import * as nock from 'nock'; const accept = () => true; const HEADERS = { - ['metadata-flavor']: 'Google' + ['metadata-flavor']: 'Google', }; const HOST_ADDRESS = 'http://metadata.google.internal.'; -export function oauth2(validator?: (body: T) => boolean): - nock.Scope { +export function oauth2( + validator?: (body: T) => boolean +): nock.Scope { validator = validator || accept; return nock(/https:\/\/(accounts\.google\.com|www\.googleapis\.com)/) - .persist() - .post(/\/oauth2.*token/, validator) - .reply(200, { - refresh_token: 'hello', - access_token: 'goodbye', - expiry_date: new Date(9999, 1, 1) - }); + .persist() + .post(/\/oauth2.*token/, validator) + .reply(200, { + refresh_token: 'hello', + access_token: 'goodbye', + expiry_date: new Date(9999, 1, 1), + }); } -export function projectId(status: number|(() => string), reply?: () => string) { +export function projectId( + status: number | (() => string), + reply?: () => string +) { if (typeof status === 'function') { reply = status; status = 200; } return nock(HOST_ADDRESS) - .get('/computeMetadata/v1/project/project-id') - .once() - .reply(status, reply, {'Metadata-Flavor': 'Google'}); + .get('/computeMetadata/v1/project/project-id') + .once() + .reply(status, reply, { 'Metadata-Flavor': 'Google' }); } export function noDetectResource() { const scopes = [ nock(HOST_ADDRESS) - .get('/computeMetadata/v1/instance') - .once() - .replyWithError({code: 'ENOTFOUND'}), + .get('/computeMetadata/v1/instance') + .once() + .replyWithError({ code: 'ENOTFOUND' }), nock('http://169.254.169.254/latest/dynamic/instance-identity/document') - .get('') - .replyWithError({code: 'ENOTFOUND'}) + .get('') + .replyWithError({ code: 'ENOTFOUND' }), ]; return scopes; } export function detectGceResource() { return nock(HOST_ADDRESS) - .get('/computeMetadata/v1/instance') - .reply(200, {}, HEADERS) - .get('/computeMetadata/v1/project/project-id') - .reply(200, () => 'my-project-id', HEADERS) - .get('/computeMetadata/v1/instance/zone') - .reply(200, () => 'project/zone/my-zone', HEADERS) - .get('/computeMetadata/v1/instance/id') - .reply(200, () => 4520031799277581759, HEADERS); + .get('/computeMetadata/v1/instance') + .reply(200, {}, HEADERS) + .get('/computeMetadata/v1/project/project-id') + .reply(200, () => 'my-project-id', HEADERS) + .get('/computeMetadata/v1/instance/zone') + .reply(200, () => 'project/zone/my-zone', HEADERS) + .get('/computeMetadata/v1/instance/id') + .reply(200, () => 4520031799277581759, HEADERS); } export function instanceId( - status: number|(() => string), reply?: () => string) { + status: number | (() => string), + reply?: () => string +) { if (typeof status === 'function') { reply = status; status = 200; } return nock(HOST_ADDRESS) - .get('/computeMetadata/v1/instance/id') - .once() - .reply(status, reply, {'Metadata-Flavor': 'Google'}); + .get('/computeMetadata/v1/instance/id') + .once() + .reply(status, reply, { 'Metadata-Flavor': 'Google' }); } -export function hostname(status: number|(() => string), reply?: () => string) { +export function hostname( + status: number | (() => string), + reply?: () => string +) { if (typeof status === 'function') { reply = status; status = 200; } return nock(HOST_ADDRESS) - .get('/computeMetadata/v1/instance/hostname') - .once() - .reply(status, reply, {'Metadata-Flavor': 'Google'}); + .get('/computeMetadata/v1/instance/hostname') + .once() + .reply(status, reply, { 'Metadata-Flavor': 'Google' }); } export function batchWrite( - project: string, validator?: (body: T) => boolean, reply?: () => string) { + project: string, + validator?: (body: T) => boolean, + reply?: () => string, + withError?: boolean +) { validator = validator || accept; - const interceptor = - nock('https://cloudtrace.googleapis.com') - .post('/v2/projects/' + project + '/traces:batchWrite', validator); + const interceptor = nock('https://cloudtrace.googleapis.com').post( + '/v2/projects/' + project + '/traces:batchWrite', + validator + ); return reply ? interceptor.reply(reply) : interceptor.reply(200); } export function timeSeries( - project: string, validator?: (body: T) => boolean, reply?: () => string) { + project: string, + validator?: (body: T) => boolean, + reply?: () => string, + withError?: boolean +) { validator = validator || accept; - const interceptor = - nock('https://monitoring.googleapis.com') - .post('/v3/projects/' + project + '/timeSeries', validator); + const interceptor = nock('https://monitoring.googleapis.com').post( + '/v3/projects/' + project + '/timeSeries', + validator + ); return reply ? interceptor.reply(reply) : interceptor.reply(200); } export function metricDescriptors( - project: string, validator?: (body: T) => boolean, reply?: () => string) { + project: string, + validator?: (body: T) => boolean, + reply?: () => string, + withError?: boolean +) { validator = validator || accept; - const interceptor = - nock('https://monitoring.googleapis.com') - .post('/v3/projects/' + project + '/metricDescriptors', validator); + const interceptor = nock('https://monitoring.googleapis.com').post( + '/v3/projects/' + project + '/metricDescriptors', + validator + ); return reply ? interceptor.reply(reply) : interceptor.reply(200); } diff --git a/packages/opencensus-exporter-stackdriver/test/test-stackdriver-cloudtrace-utils.ts b/packages/opencensus-exporter-stackdriver/test/test-stackdriver-cloudtrace-utils.ts index 1a8c8b598..7b3967caa 100644 --- a/packages/opencensus-exporter-stackdriver/test/test-stackdriver-cloudtrace-utils.ts +++ b/packages/opencensus-exporter-stackdriver/test/test-stackdriver-cloudtrace-utils.ts @@ -15,7 +15,12 @@ */ import * as coreTypes from '@opencensus/core'; import * as assert from 'assert'; -import {createAttributes, createLinks, createTimeEvents, getResourceLabels} from '../src/stackdriver-cloudtrace-utils'; +import { + createAttributes, + createLinks, + createTimeEvents, + getResourceLabels, +} from '../src/stackdriver-cloudtrace-utils'; describe('Stackdriver CloudTrace Exporter Utils', () => { describe('createLinks()', () => { @@ -25,23 +30,23 @@ describe('Stackdriver CloudTrace Exporter Utils', () => { spanId: 'spanId1', type: coreTypes.LinkType.PARENT_LINKED_SPAN, attributes: { - 'child_link_attribute_string': 'foo1', - 'child_link_attribute_number': 123, - 'child_link_attribute_boolean': true, - } + child_link_attribute_string: 'foo1', + child_link_attribute_number: 123, + child_link_attribute_boolean: true, + }, }, { traceId: 'traceId2', spanId: 'spanId2', type: coreTypes.LinkType.CHILD_LINKED_SPAN, - attributes: {} + attributes: {}, }, { traceId: 'traceId3', spanId: 'spanId3', type: coreTypes.LinkType.UNSPECIFIED, - attributes: {} - } + attributes: {}, + }, ]; const expectedLink = [ @@ -52,24 +57,24 @@ describe('Stackdriver CloudTrace Exporter Utils', () => { attributes: { droppedAttributesCount: 0, attributeMap: { - child_link_attribute_string: {stringValue: {value: 'foo1'}}, - child_link_attribute_number: {intValue: '123'}, - child_link_attribute_boolean: {boolValue: true} - } - } + child_link_attribute_string: { stringValue: { value: 'foo1' } }, + child_link_attribute_number: { intValue: '123' }, + child_link_attribute_boolean: { boolValue: true }, + }, + }, }, { type: 1, traceId: 'traceId2', spanId: 'spanId2', - attributes: {'attributeMap': {}, 'droppedAttributesCount': 0} + attributes: { attributeMap: {}, droppedAttributesCount: 0 }, }, { type: 0, traceId: 'traceId3', spanId: 'spanId3', - attributes: {'attributeMap': {}, 'droppedAttributesCount': 0} - } + attributes: { attributeMap: {}, droppedAttributesCount: 0 }, + }, ]; it('should return stackdriver links', () => { @@ -87,14 +92,14 @@ describe('Stackdriver CloudTrace Exporter Utils', () => { { description: 'my_annotation', timestamp: ts, - attributes: {myString: 'bar', myNumber: 123, myBoolean: true} + attributes: { myString: 'bar', myNumber: 123, myBoolean: true }, }, { description: 'my_annotation1', timestamp: ts, - attributes: {myString: 'bar1', myNumber: 456} + attributes: { myString: 'bar1', myNumber: 456 }, }, - {description: 'my_annotation2', timestamp: ts, attributes: {}} + { description: 'my_annotation2', timestamp: ts, attributes: {} }, ]; const messageEvents: coreTypes.MessageEvent[] = [ { @@ -102,53 +107,53 @@ describe('Stackdriver CloudTrace Exporter Utils', () => { timestamp: ts, type: coreTypes.MessageEventType.SENT, compressedSize: 100, - uncompressedSize: 12 + uncompressedSize: 12, }, - {id: 1, timestamp: ts, type: coreTypes.MessageEventType.RECEIVED}, - {id: 1, timestamp: ts, type: coreTypes.MessageEventType.UNSPECIFIED} + { id: 1, timestamp: ts, type: coreTypes.MessageEventType.RECEIVED }, + { id: 1, timestamp: ts, type: coreTypes.MessageEventType.UNSPECIFIED }, ]; const expectedTimeEvent = [ { time: '1970-01-02T10:17:36.789Z', annotation: { - description: {value: 'my_annotation'}, + description: { value: 'my_annotation' }, attributes: { attributeMap: { - myString: {stringValue: {value: 'bar'}}, - myNumber: {intValue: '123'}, - myBoolean: {boolValue: true} + myString: { stringValue: { value: 'bar' } }, + myNumber: { intValue: '123' }, + myBoolean: { boolValue: true }, }, - droppedAttributesCount: 0 - } - } + droppedAttributesCount: 0, + }, + }, }, { time: '1970-01-02T10:17:36.789Z', annotation: { - description: {value: 'my_annotation1'}, + description: { value: 'my_annotation1' }, attributes: { attributeMap: { - myString: {stringValue: {value: 'bar1'}}, - myNumber: {intValue: '456'} + myString: { stringValue: { value: 'bar1' } }, + myNumber: { intValue: '456' }, }, - droppedAttributesCount: 0 - } - } + droppedAttributesCount: 0, + }, + }, }, { time: '1970-01-02T10:17:36.789Z', annotation: { - description: {value: 'my_annotation2'}, - attributes: {attributeMap: {}, droppedAttributesCount: 0} - } + description: { value: 'my_annotation2' }, + attributes: { attributeMap: {}, droppedAttributesCount: 0 }, + }, }, { messageEvent: { compressedSizeBytes: '100', id: '1', type: 1, - uncompressedSizeBytes: '12' + uncompressedSizeBytes: '12', }, time: '1970-01-02T10:17:36.789Z', }, @@ -157,7 +162,7 @@ describe('Stackdriver CloudTrace Exporter Utils', () => { compressedSizeBytes: '0', id: '1', type: 2, - uncompressedSizeBytes: '0' + uncompressedSizeBytes: '0', }, time: '1970-01-02T10:17:36.789Z', }, @@ -166,67 +171,83 @@ describe('Stackdriver CloudTrace Exporter Utils', () => { compressedSizeBytes: '0', id: '1', type: 0, - uncompressedSizeBytes: '0' + uncompressedSizeBytes: '0', }, time: '1970-01-02T10:17:36.789Z', - } + }, ]; it('should return stackdriver TimeEvents', () => { - const stackdriverTimeEvents = - createTimeEvents(annotations, messageEvents, 2, 3); + const stackdriverTimeEvents = createTimeEvents( + annotations, + messageEvents, + 2, + 3 + ); assert.strictEqual(stackdriverTimeEvents.droppedAnnotationsCount, 2); assert.strictEqual(stackdriverTimeEvents.droppedMessageEventsCount, 3); assert.strictEqual(stackdriverTimeEvents.timeEvent!.length, 6); assert.deepStrictEqual( - stackdriverTimeEvents.timeEvent, expectedTimeEvent); + stackdriverTimeEvents.timeEvent, + expectedTimeEvent + ); }); - it('should return stackdriver TimeEvents when empty annotations and messageEvents', - () => { - const stackdriverTimeEvents = createTimeEvents([], [], 0, 0); + it('should return stackdriver TimeEvents when empty annotations and messageEvents', () => { + const stackdriverTimeEvents = createTimeEvents([], [], 0, 0); - assert.strictEqual(stackdriverTimeEvents.droppedAnnotationsCount, 0); - assert.strictEqual(stackdriverTimeEvents.droppedMessageEventsCount, 0); - assert.strictEqual(stackdriverTimeEvents.timeEvent!.length, 0); - }); + assert.strictEqual(stackdriverTimeEvents.droppedAnnotationsCount, 0); + assert.strictEqual(stackdriverTimeEvents.droppedMessageEventsCount, 0); + assert.strictEqual(stackdriverTimeEvents.timeEvent!.length, 0); + }); }); describe('createAttributes()', () => { - const attributes = {'my-attribute': 100, 'my-attribute1': 'test'}; + const attributes = { 'my-attribute': 100, 'my-attribute1': 'test' }; let expectedAttributeMap = { - 'g.co/agent': - {'stringValue': {'value': `opencensus-node [${coreTypes.version}]`}}, - 'my-attribute': {'intValue': '100'}, - 'my-attribute1': {'stringValue': {'value': 'test'}} + 'g.co/agent': { + stringValue: { value: `opencensus-node [${coreTypes.version}]` }, + }, + 'my-attribute': { intValue: '100' }, + 'my-attribute1': { stringValue: { value: 'test' } }, }; it('should return stackdriver Attributes', () => { const stackdriverAttribute = createAttributes(attributes, {}, 0); assert.strictEqual(stackdriverAttribute.droppedAttributesCount, 0); assert.strictEqual( - Object.keys(stackdriverAttribute.attributeMap!).length, 3); + Object.keys(stackdriverAttribute.attributeMap!).length, + 3 + ); assert.deepStrictEqual( - stackdriverAttribute.attributeMap, expectedAttributeMap); + stackdriverAttribute.attributeMap, + expectedAttributeMap + ); }); it('should return stackdriver Attributes with labels', () => { const stackdriverAttribute = createAttributes( - attributes, { - 'g.co/r/podId': {'intValue': '100'}, - 'g.co/r/project_id': {'stringValue': {'value': 'project1'}} - }, - 2); + attributes, + { + 'g.co/r/podId': { intValue: '100' }, + 'g.co/r/project_id': { stringValue: { value: 'project1' } }, + }, + 2 + ); expectedAttributeMap = Object.assign({}, expectedAttributeMap, { - 'g.co/r/podId': {'intValue': '100'}, - 'g.co/r/project_id': {'stringValue': {'value': 'project1'}} + 'g.co/r/podId': { intValue: '100' }, + 'g.co/r/project_id': { stringValue: { value: 'project1' } }, }); assert.strictEqual(stackdriverAttribute.droppedAttributesCount, 2); assert.strictEqual( - Object.keys(stackdriverAttribute.attributeMap!).length, 5); + Object.keys(stackdriverAttribute.attributeMap!).length, + 5 + ); assert.deepStrictEqual( - stackdriverAttribute.attributeMap, expectedAttributeMap); + stackdriverAttribute.attributeMap, + expectedAttributeMap + ); }); }); @@ -235,22 +256,25 @@ describe('Stackdriver CloudTrace Exporter Utils', () => { const resource = { type: 'k8s_container', labels: { - 'container_name': 'c1', - 'namespace_name': 'default', - 'pod_name': 'pod-xyz-123', - 'project_id': 'my-project-id', - 'location': 'zone1' - } + container_name: 'c1', + namespace_name: 'default', + pod_name: 'pod-xyz-123', + project_id: 'my-project-id', + location: 'zone1', + }, }; const expectedLabels = { - 'g.co/r/k8s_container/container_name': {'stringValue': {'value': 'c1'}}, - 'g.co/r/k8s_container/location': {'stringValue': {'value': 'zone1'}}, - 'g.co/r/k8s_container/namespace_name': - {'stringValue': {'value': 'default'}}, - 'g.co/r/k8s_container/pod_name': - {'stringValue': {'value': 'pod-xyz-123'}}, - 'g.co/r/k8s_container/project_id': - {'stringValue': {'value': 'my-project-id'}} + 'g.co/r/k8s_container/container_name': { stringValue: { value: 'c1' } }, + 'g.co/r/k8s_container/location': { stringValue: { value: 'zone1' } }, + 'g.co/r/k8s_container/namespace_name': { + stringValue: { value: 'default' }, + }, + 'g.co/r/k8s_container/pod_name': { + stringValue: { value: 'pod-xyz-123' }, + }, + 'g.co/r/k8s_container/project_id': { + stringValue: { value: 'my-project-id' }, + }, }; const resolvingPromise = Promise.resolve(resource); @@ -263,17 +287,19 @@ describe('Stackdriver CloudTrace Exporter Utils', () => { const resource = { type: 'gce_instance', labels: { - 'instance_id': 'instance1', - 'zone': 'zone1', - 'project_id': 'my-project-id', - } + instance_id: 'instance1', + zone: 'zone1', + project_id: 'my-project-id', + }, }; const expectedLabels = { - 'g.co/r/gce_instance/instance_id': - {'stringValue': {'value': 'instance1'}}, - 'g.co/r/gce_instance/project_id': - {'stringValue': {'value': 'my-project-id'}}, - 'g.co/r/gce_instance/zone': {'stringValue': {'value': 'zone1'}} + 'g.co/r/gce_instance/instance_id': { + stringValue: { value: 'instance1' }, + }, + 'g.co/r/gce_instance/project_id': { + stringValue: { value: 'my-project-id' }, + }, + 'g.co/r/gce_instance/zone': { stringValue: { value: 'zone1' } }, }; const resolvingPromise = Promise.resolve(resource); const resourceLabels = await getResourceLabels(resolvingPromise); @@ -285,21 +311,23 @@ describe('Stackdriver CloudTrace Exporter Utils', () => { const resource = { type: 'aws_ec2_instance', labels: { - 'instance_id': 'instance1', - 'region': 'region1', - 'project_id': 'my-project-id', - 'aws_account': 'my-account-id', - } + instance_id: 'instance1', + region: 'region1', + project_id: 'my-project-id', + aws_account: 'my-account-id', + }, }; const expectedLabels = { - 'g.co/r/aws_ec2_instance/aws_account': - {'stringValue': {'value': 'my-account-id'}}, - 'g.co/r/aws_ec2_instance/instance_id': - {'stringValue': {'value': 'instance1'}}, - 'g.co/r/aws_ec2_instance/project_id': - {'stringValue': {'value': 'my-project-id'}}, - 'g.co/r/aws_ec2_instance/region': - {'stringValue': {'value': 'region1'}} + 'g.co/r/aws_ec2_instance/aws_account': { + stringValue: { value: 'my-account-id' }, + }, + 'g.co/r/aws_ec2_instance/instance_id': { + stringValue: { value: 'instance1' }, + }, + 'g.co/r/aws_ec2_instance/project_id': { + stringValue: { value: 'my-project-id' }, + }, + 'g.co/r/aws_ec2_instance/region': { stringValue: { value: 'region1' } }, }; const resolvingPromise = Promise.resolve(resource); diff --git a/packages/opencensus-exporter-stackdriver/test/test-stackdriver-cloudtrace.ts b/packages/opencensus-exporter-stackdriver/test/test-stackdriver-cloudtrace.ts index da08ee981..b2bc13269 100644 --- a/packages/opencensus-exporter-stackdriver/test/test-stackdriver-cloudtrace.ts +++ b/packages/opencensus-exporter-stackdriver/test/test-stackdriver-cloudtrace.ts @@ -14,12 +14,16 @@ * limitations under the License. */ -import {CoreTracer, logger, Span as OCSpan, version} from '@opencensus/core'; +import { CoreTracer, logger, Span as OCSpan, version } from '@opencensus/core'; import * as assert from 'assert'; import * as fs from 'fs'; import * as nock from 'nock'; -import {Span, StackdriverExporterOptions, StackdriverTraceExporter} from '../src/'; +import { + Span, + StackdriverExporterOptions, + StackdriverTraceExporter, +} from '../src/'; import * as nocks from './nocks'; @@ -39,7 +43,7 @@ describe('Stackdriver Trace Exporter', function() { exporterOptions = { projectId: PROJECT_ID, bufferTimeout: 200, - logger: testLogger + logger: testLogger, }; }); @@ -47,101 +51,108 @@ describe('Stackdriver Trace Exporter', function() { nocks.noDetectResource(); exporter = new StackdriverTraceExporter(exporterOptions); tracer = new CoreTracer(); - tracer.start({samplingRate: 1}); + tracer.start({ samplingRate: 1 }); tracer.registerSpanEventListener(exporter); }); describe('onEndSpan()', () => { it('should add a root span to an exporter buffer', () => { - const rootSpanOptions = {name: 'sdBufferTestRootSpan'}; + const rootSpanOptions = { name: 'sdBufferTestRootSpan' }; return tracer.startRootSpan(rootSpanOptions, (rootSpan: OCSpan) => { assert.strictEqual(exporter.exporterBuffer.getQueue().length, 0); const spanName = 'sdBufferTestChildSpan'; - const span = tracer.startChildSpan({name: spanName}); + const span = tracer.startChildSpan({ name: spanName }); span.end(); rootSpan.end(); assert.strictEqual(exporter.exporterBuffer.getQueue().length, 1); assert.strictEqual( - exporter.exporterBuffer.getQueue()[0].name, rootSpanOptions.name); + exporter.exporterBuffer.getQueue()[0].name, + rootSpanOptions.name + ); assert.strictEqual( - exporter.exporterBuffer.getQueue()[0].spans.length, 1); + exporter.exporterBuffer.getQueue()[0].spans.length, + 1 + ); assert.strictEqual( - exporter.exporterBuffer.getQueue()[0].spans[0].name, spanName); + exporter.exporterBuffer.getQueue()[0].spans[0].name, + spanName + ); }); }); }); - describe('translateSpan()', () => { it('should translate to stackdriver spans', () => { return tracer.startRootSpan( - {name: 'root-test'}, async (rootSpan: OCSpan) => { - const span = tracer.startChildSpan({name: 'spanTest'}); - span.end(); - rootSpan.end(); - - const spanList = await exporter.translateSpan([rootSpan]); - assert.strictEqual(spanList.length, 2); - assert.deepStrictEqual(spanList, [ - { - 'attributes': { - 'attributeMap': { - 'g.co/agent': { - 'stringValue': - {'value': `opencensus-node [${version}]`} - } + { name: 'root-test' }, + async (rootSpan: OCSpan) => { + const span = tracer.startChildSpan({ name: 'spanTest' }); + span.end(); + rootSpan.end(); + + const spanList = await exporter.translateSpan([rootSpan]); + assert.strictEqual(spanList.length, 2); + assert.deepStrictEqual(spanList, [ + { + attributes: { + attributeMap: { + 'g.co/agent': { + stringValue: { value: `opencensus-node [${version}]` }, }, - 'droppedAttributesCount': 0 }, - 'childSpanCount': 1, - 'displayName': {'value': 'root-test'}, - 'endTime': rootSpan.endTime.toISOString(), - 'links': {'droppedLinksCount': 0, 'link': []}, - 'name': `projects/fake-project-id/traces/${ - rootSpan.traceId}/spans/${rootSpan.id}`, - 'sameProcessAsParentSpan': true, - 'spanId': rootSpan.id, - 'stackTrace': undefined, - 'startTime': rootSpan.startTime.toISOString(), - 'status': {'code': 0}, - 'timeEvents': { - 'droppedAnnotationsCount': 0, - 'droppedMessageEventsCount': 0, - 'timeEvent': [] - } + droppedAttributesCount: 0, + }, + childSpanCount: 1, + displayName: { value: 'root-test' }, + endTime: rootSpan.endTime.toISOString(), + links: { droppedLinksCount: 0, link: [] }, + name: `projects/fake-project-id/traces/${ + rootSpan.traceId + }/spans/${rootSpan.id}`, + sameProcessAsParentSpan: true, + spanId: rootSpan.id, + stackTrace: undefined, + startTime: rootSpan.startTime.toISOString(), + status: { code: 0 }, + timeEvents: { + droppedAnnotationsCount: 0, + droppedMessageEventsCount: 0, + timeEvent: [], }, - { - 'attributes': { - 'attributeMap': { - 'g.co/agent': { - 'stringValue': - {'value': `opencensus-node [${version}]`} - } + }, + { + attributes: { + attributeMap: { + 'g.co/agent': { + stringValue: { value: `opencensus-node [${version}]` }, }, - 'droppedAttributesCount': 0 - }, - 'childSpanCount': 0, - 'displayName': {'value': 'spanTest'}, - 'endTime': span.endTime.toISOString(), - 'links': {'droppedLinksCount': 0, 'link': []}, - 'name': `projects/fake-project-id/traces/${ - span.traceId}/spans/${span.id}`, - 'parentSpanId': rootSpan.id, - 'sameProcessAsParentSpan': true, - 'spanId': span.id, - 'stackTrace': undefined, - 'startTime': span.startTime.toISOString(), - 'status': {'code': 0}, - 'timeEvents': { - 'droppedAnnotationsCount': 0, - 'droppedMessageEventsCount': 0, - 'timeEvent': [] }, - } - ]); - }); + droppedAttributesCount: 0, + }, + childSpanCount: 0, + displayName: { value: 'spanTest' }, + endTime: span.endTime.toISOString(), + links: { droppedLinksCount: 0, link: [] }, + name: `projects/fake-project-id/traces/${span.traceId}/spans/${ + span.id + }`, + parentSpanId: rootSpan.id, + sameProcessAsParentSpan: true, + spanId: span.id, + stackTrace: undefined, + startTime: span.startTime.toISOString(), + status: { code: 0 }, + timeEvents: { + droppedAnnotationsCount: 0, + droppedMessageEventsCount: 0, + timeEvent: [], + }, + }, + ]); + } + ); }); }); @@ -150,85 +161,99 @@ describe('Stackdriver Trace Exporter', function() { nock.enableNetConnect(); const NOEXIST_PROJECT_ID = 'no-existent-project-id-99999'; process.env.GOOGLE_APPLICATION_CREDENTIALS = - __dirname + '/fixtures/fakecredentials.json'; + __dirname + '/fixtures/fakecredentials.json'; nocks.oauth2(body => true); const failExporterOptions = { projectId: NOEXIST_PROJECT_ID, - logger: logger.logger('debug') + logger: logger.logger('debug'), }; const failExporter = new StackdriverTraceExporter(failExporterOptions); const failTracer = new CoreTracer(); - failTracer.start({samplingRate: 1}); + failTracer.start({ samplingRate: 1 }); failTracer.registerSpanEventListener(failExporter); return failTracer.startRootSpan( - {name: 'sdNoExportTestRootSpan'}, async (rootSpan: OCSpan) => { - const span = - failTracer.startChildSpan({name: 'sdNoExportTestChildSpan'}); - span.end(); - rootSpan.end(); + { name: 'sdNoExportTestRootSpan' }, + async (rootSpan: OCSpan) => { + const span = failTracer.startChildSpan({ + name: 'sdNoExportTestChildSpan', + }); + span.end(); + rootSpan.end(); - return failExporter.publish([rootSpan]).then(result => { - assert.strictEqual(result.code, 401); - assert.ok(result.message.indexOf('batchWriteSpans error') >= 0); + return failExporter.publish([rootSpan]).then(result => { + assert.strictEqual(result.code, 401); + assert.ok(result.message.indexOf('batchWriteSpans error') >= 0); - assert.strictEqual( - failExporter.failBuffer[0].traceId, - rootSpan.spanContext.traceId); - }); + assert.strictEqual( + failExporter.failBuffer[0].traceId, + rootSpan.spanContext.traceId + ); }); + } + ); }); it('should export traces to stackdriver', () => { return tracer.startRootSpan( - {name: 'sdExportTestRootSpan'}, async (rootSpan: OCSpan) => { - const span = tracer.startChildSpan({name: 'sdExportTestChildSpan'}); - - nocks.oauth2(body => true); - nocks.batchWrite(PROJECT_ID, (body: {spans: Span[]}): boolean => { + { name: 'sdExportTestRootSpan' }, + async (rootSpan: OCSpan) => { + const span = tracer.startChildSpan({ name: 'sdExportTestChildSpan' }); + + nocks.oauth2(body => true); + nocks.batchWrite( + PROJECT_ID, + (body: { spans: Span[] }): boolean => { assert.strictEqual(body.spans.length, 2); const spans = body.spans; assert.strictEqual(spans[0].spanId, rootSpan.id); assert.strictEqual(spans[1].spanId, span.id); return true; - }); - span.end(); - rootSpan.end(); + } + ); + span.end(); + rootSpan.end(); - return exporter.publish([rootSpan]).then(result => { - assert.ok(result.indexOf('batchWriteSpans sucessfully') >= 0); - }); + return exporter.publish([rootSpan]).then(result => { + assert.ok(result.indexOf('batchWriteSpans sucessfully') >= 0); }); + } + ); }); it('should fail exporting by network error', async () => { nock('https://cloudtrace.googleapis.com') - .intercept( - '/v2/projects/' + exporterOptions.projectId + - '/traces:batchWrite', - 'post') - .reply(443, 'Simulated Network Error'); + .intercept( + '/v2/projects/' + exporterOptions.projectId + '/traces:batchWrite', + 'post' + ) + .reply(443, 'Simulated Network Error'); nocks.oauth2(body => true); return tracer.startRootSpan( - {name: 'sdErrorExportTestRootSpan'}, (rootSpan: OCSpan) => { - const span = - tracer.startChildSpan({name: 'sdErrorExportTestChildSpan'}); - span.end(); - rootSpan.end(); - - return exporter.publish([rootSpan]).then(result => { - assert.ok( - result.message.indexOf( - 'batchWriteSpans error: Simulated Network Error') >= 0); - }); + { name: 'sdErrorExportTestRootSpan' }, + (rootSpan: OCSpan) => { + const span = tracer.startChildSpan({ + name: 'sdErrorExportTestChildSpan', + }); + span.end(); + rootSpan.end(); + + return exporter.publish([rootSpan]).then(result => { + assert.ok( + result.message.indexOf( + 'batchWriteSpans error: Simulated Network Error' + ) >= 0 + ); }); + } + ); }); describe('with credentials option', () => { const FAKE_CREDENTIALS = JSON.parse( - fs.readFileSync(__dirname + '/fixtures/fakecredentials.json') - .toString()); + fs.readFileSync(__dirname + '/fixtures/fakecredentials.json').toString() + ); before(() => { exporterOptions = { @@ -241,50 +266,61 @@ describe('Stackdriver Trace Exporter', function() { it('should export traces to stackdriver', () => { return tracer.startRootSpan( - {name: 'sdExportTestRootSpan'}, async (rootSpan: OCSpan) => { - const span = - tracer.startChildSpan({name: 'sdExportTestChildSpan'}); + { name: 'sdExportTestRootSpan' }, + async (rootSpan: OCSpan) => { + const span = tracer.startChildSpan({ + name: 'sdExportTestChildSpan', + }); - nocks.oauth2(body => true); - nocks.batchWrite(PROJECT_ID, (body: {spans: Span[]}): boolean => { + nocks.oauth2(body => true); + nocks.batchWrite( + PROJECT_ID, + (body: { spans: Span[] }): boolean => { assert.strictEqual(body.spans.length, 2); const spans = body.spans; assert.strictEqual(spans[0].spanId, rootSpan.id); assert.strictEqual(spans[1].spanId, span.id); return true; - }); - span.end(); - rootSpan.end(); + } + ); + span.end(); + rootSpan.end(); - return exporter.publish([rootSpan]).then(result => { - assert.ok(result.indexOf('batchWriteSpans sucessfully') >= 0); - }); + return exporter.publish([rootSpan]).then(result => { + assert.ok(result.indexOf('batchWriteSpans sucessfully') >= 0); }); + } + ); }); it('should fail exporting by network error', async () => { nock('https://cloudtrace.googleapis.com') - .intercept( - '/v2/projects/' + exporterOptions.projectId + - '/traces:batchWrite', - 'post') - .reply(443, 'Simulated Network Error'); + .intercept( + '/v2/projects/' + exporterOptions.projectId + '/traces:batchWrite', + 'post' + ) + .reply(443, 'Simulated Network Error'); nocks.oauth2(body => true); return tracer.startRootSpan( - {name: 'sdErrorExportTestRootSpan'}, (rootSpan: OCSpan) => { - const span = - tracer.startChildSpan({name: 'sdErrorExportTestChildSpan'}); - span.end(); - rootSpan.end(); - - return exporter.publish([rootSpan]).then(result => { - assert.ok( - result.message.indexOf( - 'batchWriteSpans error: Simulated Network Error') >= 0); - }); + { name: 'sdErrorExportTestRootSpan' }, + (rootSpan: OCSpan) => { + const span = tracer.startChildSpan({ + name: 'sdErrorExportTestChildSpan', + }); + span.end(); + rootSpan.end(); + + return exporter.publish([rootSpan]).then(result => { + assert.ok( + result.message.indexOf( + 'batchWriteSpans error: Simulated Network Error' + ) >= 0 + ); }); + } + ); }); }); }); diff --git a/packages/opencensus-exporter-stackdriver/test/test-stackdriver-monitoring-utils.ts b/packages/opencensus-exporter-stackdriver/test/test-stackdriver-monitoring-utils.ts index 8ffed24f6..8feae4e88 100644 --- a/packages/opencensus-exporter-stackdriver/test/test-stackdriver-monitoring-utils.ts +++ b/packages/opencensus-exporter-stackdriver/test/test-stackdriver-monitoring-utils.ts @@ -14,12 +14,31 @@ * limitations under the License. */ -import {CoreResource, DistributionValue, LabelKey, LabelValue, MetricDescriptor as OCMetricDescriptor, MetricDescriptorType, TimeSeriesPoint, Timestamp} from '@opencensus/core'; +import { + CoreResource, + DistributionValue, + LabelKey, + LabelValue, + MetricDescriptor as OCMetricDescriptor, + MetricDescriptorType, + TimeSeriesPoint, + Timestamp, +} from '@opencensus/core'; import * as assert from 'assert'; -import {getDefaultResource} from '../src/common-utils'; -import {StackdriverStatsExporter} from '../src/stackdriver-monitoring'; -import {createMetricDescriptorData, createTimeSeriesList, OPENCENSUS_TASK_VALUE_DEFAULT, TEST_ONLY} from '../src/stackdriver-monitoring-utils'; -import {Distribution, MetricDescriptor, MetricKind, ValueType} from '../src/types'; +import { getDefaultResource } from '../src/common-utils'; +import { StackdriverStatsExporter } from '../src/stackdriver-monitoring'; +import { + createMetricDescriptorData, + createTimeSeriesList, + OPENCENSUS_TASK_VALUE_DEFAULT, + TEST_ONLY, +} from '../src/stackdriver-monitoring-utils'; +import { + Distribution, + MetricDescriptor, + MetricKind, + ValueType, +} from '../src/types'; import * as nocks from './nocks'; const METRIC_NAME = 'metric-name'; @@ -30,57 +49,68 @@ describe('Stackdriver Stats Exporter Utils', () => { describe('createMetricKind()', () => { it('should return a Stackdriver MetricKind', () => { assert.strictEqual( - TEST_ONLY.createMetricKind(MetricDescriptorType.CUMULATIVE_INT64), - MetricKind.CUMULATIVE); + TEST_ONLY.createMetricKind(MetricDescriptorType.CUMULATIVE_INT64), + MetricKind.CUMULATIVE + ); assert.strictEqual( - TEST_ONLY.createMetricKind(MetricDescriptorType.GAUGE_INT64), - MetricKind.GAUGE); + TEST_ONLY.createMetricKind(MetricDescriptorType.GAUGE_INT64), + MetricKind.GAUGE + ); assert.strictEqual( - TEST_ONLY.createMetricKind(MetricDescriptorType.GAUGE_DOUBLE), - MetricKind.GAUGE); + TEST_ONLY.createMetricKind(MetricDescriptorType.GAUGE_DOUBLE), + MetricKind.GAUGE + ); assert.strictEqual( - TEST_ONLY.createMetricKind(MetricDescriptorType.SUMMARY), - MetricKind.UNSPECIFIED); + TEST_ONLY.createMetricKind(MetricDescriptorType.SUMMARY), + MetricKind.UNSPECIFIED + ); }); }); describe('createValueType()', () => { it('should return a Stackdriver ValueType', () => { assert.strictEqual( - TEST_ONLY.createValueType(MetricDescriptorType.GAUGE_DOUBLE), - ValueType.DOUBLE); + TEST_ONLY.createValueType(MetricDescriptorType.GAUGE_DOUBLE), + ValueType.DOUBLE + ); assert.strictEqual( - TEST_ONLY.createValueType(MetricDescriptorType.CUMULATIVE_INT64), - ValueType.INT64); + TEST_ONLY.createValueType(MetricDescriptorType.CUMULATIVE_INT64), + ValueType.INT64 + ); assert.strictEqual( - TEST_ONLY.createValueType(MetricDescriptorType.GAUGE_INT64), - ValueType.INT64); + TEST_ONLY.createValueType(MetricDescriptorType.GAUGE_INT64), + ValueType.INT64 + ); assert.strictEqual( - TEST_ONLY.createValueType(MetricDescriptorType.CUMULATIVE_DOUBLE), - ValueType.DOUBLE); + TEST_ONLY.createValueType(MetricDescriptorType.CUMULATIVE_DOUBLE), + ValueType.DOUBLE + ); assert.strictEqual( - TEST_ONLY.createValueType( - MetricDescriptorType.CUMULATIVE_DISTRIBUTION), - ValueType.DISTRIBUTION); + TEST_ONLY.createValueType(MetricDescriptorType.CUMULATIVE_DISTRIBUTION), + ValueType.DISTRIBUTION + ); assert.strictEqual( - TEST_ONLY.createValueType(MetricDescriptorType.GAUGE_DISTRIBUTION), - ValueType.DISTRIBUTION); + TEST_ONLY.createValueType(MetricDescriptorType.GAUGE_DISTRIBUTION), + ValueType.DISTRIBUTION + ); assert.strictEqual( - TEST_ONLY.createValueType(MetricDescriptorType.SUMMARY), - ValueType.VALUE_TYPE_UNSPECIFIED); + TEST_ONLY.createValueType(MetricDescriptorType.SUMMARY), + ValueType.VALUE_TYPE_UNSPECIFIED + ); }); }); describe('createLabelDescriptor()', () => { - const labelKeys: LabelKey[] = [{'key': 'key', 'description': 'desc'}]; + const labelKeys: LabelKey[] = [{ key: 'key', description: 'desc' }]; it('should return a Stackdriver LabelDescriptor', () => { assert.deepStrictEqual(TEST_ONLY.createLabelDescriptor(labelKeys), [ - {description: 'desc', key: 'key', valueType: 'STRING'}, { + { description: 'desc', key: 'key', valueType: 'STRING' }, + { description: 'Opencensus task identifier', key: 'opencensus_task', - valueType: 'STRING' - } + valueType: 'STRING', + }, ]); }); }); @@ -88,232 +118,279 @@ describe('Stackdriver Stats Exporter Utils', () => { describe('createDisplayName()', () => { it('should return a Stackdriver DisplayName', () => { assert.strictEqual( - TEST_ONLY.createDisplayName( - 'demo/latency', 'custom.googleapis.com/opencensus'), - 'custom.googleapis.com/opencensus/demo/latency'); + TEST_ONLY.createDisplayName( + 'demo/latency', + 'custom.googleapis.com/opencensus' + ), + 'custom.googleapis.com/opencensus/demo/latency' + ); }); }); describe('createMetricType()', () => { it('should return a Stackdriver MetricType', () => { assert.strictEqual( - TEST_ONLY.createMetricType('demo/latency', 'opencensus'), - 'opencensus/demo/latency'); + TEST_ONLY.createMetricType('demo/latency', 'opencensus'), + 'opencensus/demo/latency' + ); }); }); describe('createMetric()', () => { - const labelKeys: LabelKey[] = [{'key': 'key1', 'description': 'desc'}]; - const labelValues: LabelValue[] = [{'value': 'value1'}]; - const emptyLabelValues: LabelValue[] = [{'value': ''}]; + const labelKeys: LabelKey[] = [{ key: 'key1', description: 'desc' }]; + const labelValues: LabelValue[] = [{ value: 'value1' }]; + const emptyLabelValues: LabelValue[] = [{ value: '' }]; const metricDescriptor: OCMetricDescriptor = { name: METRIC_NAME, description: METRIC_DESCRIPTION, unit: DEFAULT_UNIT, type: MetricDescriptorType.GAUGE_INT64, - labelKeys + labelKeys, }; it('should return a Stackdriver Metric', () => { const metric = TEST_ONLY.createMetric( - metricDescriptor, labelValues, - StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN); + metricDescriptor, + labelValues, + StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN + ); assert.strictEqual( - metric.type, `custom.googleapis.com/opencensus/${METRIC_NAME}`); - assert.deepStrictEqual( - metric.labels, - {'key1': 'value1', 'opencensus_task': OPENCENSUS_TASK_VALUE_DEFAULT}); + metric.type, + `custom.googleapis.com/opencensus/${METRIC_NAME}` + ); + assert.deepStrictEqual(metric.labels, { + key1: 'value1', + opencensus_task: OPENCENSUS_TASK_VALUE_DEFAULT, + }); }); it('should return a Stackdriver Metric With External Metric Domain', () => { const prometheusDomain = 'external.googleapis.com/prometheus/'; const metric = TEST_ONLY.createMetric( - metricDescriptor, labelValues, prometheusDomain); + metricDescriptor, + labelValues, + prometheusDomain + ); assert.strictEqual(metric.type, `${prometheusDomain}${METRIC_NAME}`); - assert.deepStrictEqual( - metric.labels, - {'key1': 'value1', 'opencensus_task': OPENCENSUS_TASK_VALUE_DEFAULT}); + assert.deepStrictEqual(metric.labels, { + key1: 'value1', + opencensus_task: OPENCENSUS_TASK_VALUE_DEFAULT, + }); }); it('should return a Stackdriver Metric With Empty Label', () => { const prometheusDomain = 'external.googleapis.com/prometheus/'; - const metric = - TEST_ONLY.createMetric(metricDescriptor, [], prometheusDomain); + const metric = TEST_ONLY.createMetric( + metricDescriptor, + [], + prometheusDomain + ); assert.strictEqual(metric.type, `${prometheusDomain}${METRIC_NAME}`); - assert.deepStrictEqual( - metric.labels, {'opencensus_task': OPENCENSUS_TASK_VALUE_DEFAULT}); + assert.deepStrictEqual(metric.labels, { + opencensus_task: OPENCENSUS_TASK_VALUE_DEFAULT, + }); }); it('should return a Stackdriver Metric With Empty label value', () => { const metric = TEST_ONLY.createMetric( - metricDescriptor, emptyLabelValues, - StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN); + metricDescriptor, + emptyLabelValues, + StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN + ); assert.strictEqual( - metric.type, `custom.googleapis.com/opencensus/${METRIC_NAME}`); - assert.deepStrictEqual( - metric.labels, - {'key1': '', 'opencensus_task': OPENCENSUS_TASK_VALUE_DEFAULT}); + metric.type, + `custom.googleapis.com/opencensus/${METRIC_NAME}` + ); + assert.deepStrictEqual(metric.labels, { + key1: '', + opencensus_task: OPENCENSUS_TASK_VALUE_DEFAULT, + }); }); }); describe('createDistribution()', () => { - const attachments = {'k1': 'v1'}; + const attachments = { k1: 'v1' }; const spanContext = { traceId: '3ad17e665f514aabb896341f670179ed', spanId: '3aaeb440a89d9e82', - options: 0x1 + options: 0x1, }; const distributionValue: DistributionValue = { count: 3, sum: 2, sumOfSquaredDeviation: 14, - bucketOptions: {explicit: {bounds: [1.0, 3.0, 5.0]}}, + bucketOptions: { explicit: { bounds: [1.0, 3.0, 5.0] } }, buckets: [ { count: 3, exemplar: { value: 5, - timestamp: {seconds: 1450000000, nanos: 0}, - attachments - } + timestamp: { seconds: 1450000000, nanos: 0 }, + attachments, + }, }, - {count: 1}, {count: 2}, { + { count: 1 }, + { count: 2 }, + { count: 4, exemplar: { value: 5, - timestamp: {seconds: 1450000000, nanos: 0}, - attachments: {'SpanContext': `'${spanContext}'`} - } - } + timestamp: { seconds: 1450000000, nanos: 0 }, + attachments: { SpanContext: `'${spanContext}'` }, + }, + }, ], }; it('should return a Stackdriver Distribution', () => { - const distribution: Distribution = - TEST_ONLY.createDistribution(distributionValue); + const distribution: Distribution = TEST_ONLY.createDistribution( + distributionValue + ); assert.strictEqual(distribution.count, 3); assert.strictEqual(distribution.mean, 0.6666666666666666); assert.strictEqual(distribution.sumOfSquaredDeviation, 14); - assert.deepStrictEqual( - distribution.bucketOptions, - {explicitBuckets: {bounds: [0, 1, 3, 5]}}); + assert.deepStrictEqual(distribution.bucketOptions, { + explicitBuckets: { bounds: [0, 1, 3, 5] }, + }); assert.deepStrictEqual(distribution.bucketCounts, [0, 3, 1, 2, 4]); - assert.deepStrictEqual( - distribution.exemplars, [{ - 'attachments': [{ + assert.deepStrictEqual(distribution.exemplars, [ + { + attachments: [ + { '@type': 'type.googleapis.com/google.protobuf.StringValue', - 'value': 'v1' - }], - 'timestamp': '2015-12-13T09:46:40.Z', - 'value': 5 - }]); + value: 'v1', + }, + ], + timestamp: '2015-12-13T09:46:40.Z', + value: 5, + }, + ]); }); }); describe('createMetricDescriptorData()', () => { - const labelKeys: LabelKey[] = [{'key': 'key1', 'description': 'desc'}]; + const labelKeys: LabelKey[] = [{ key: 'key1', description: 'desc' }]; const metricDescriptor: OCMetricDescriptor = { name: METRIC_NAME, description: METRIC_DESCRIPTION, unit: DEFAULT_UNIT, type: MetricDescriptorType.GAUGE_INT64, - labelKeys + labelKeys, }; const metricDescriptor1: OCMetricDescriptor = { name: METRIC_NAME, description: METRIC_DESCRIPTION, unit: DEFAULT_UNIT, type: MetricDescriptorType.CUMULATIVE_INT64, - labelKeys + labelKeys, }; it('should return a Stackdriver MetricDescriptor', () => { const descriptor: MetricDescriptor = createMetricDescriptorData( - metricDescriptor, 'custom.googleapis.com/myorg/', 'myorg/'); + metricDescriptor, + 'custom.googleapis.com/myorg/', + 'myorg/' + ); assert.strictEqual(descriptor.description, METRIC_DESCRIPTION); assert.strictEqual(descriptor.displayName, `myorg/${METRIC_NAME}`); assert.strictEqual( - descriptor.type, `custom.googleapis.com/myorg/${METRIC_NAME}`); + descriptor.type, + `custom.googleapis.com/myorg/${METRIC_NAME}` + ); assert.strictEqual(descriptor.unit, DEFAULT_UNIT); assert.strictEqual(descriptor.metricKind, MetricKind.GAUGE); assert.strictEqual(descriptor.valueType, ValueType.INT64); assert.deepStrictEqual(descriptor.labels, [ - {description: 'desc', key: 'key1', valueType: 'STRING'}, { + { description: 'desc', key: 'key1', valueType: 'STRING' }, + { description: 'Opencensus task identifier', key: 'opencensus_task', - valueType: 'STRING' - } + valueType: 'STRING', + }, ]); }); it('should return a Cumulative Stackdriver MetricDescriptor', () => { const descriptor: MetricDescriptor = createMetricDescriptorData( - metricDescriptor1, StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN, - 'OpenCensus'); + metricDescriptor1, + StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN, + 'OpenCensus' + ); assert.strictEqual(descriptor.description, METRIC_DESCRIPTION); assert.strictEqual(descriptor.displayName, `OpenCensus/${METRIC_NAME}`); assert.strictEqual( - descriptor.type, - `${StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN}/${ - METRIC_NAME}`); + descriptor.type, + `${StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN}/${METRIC_NAME}` + ); assert.strictEqual(descriptor.unit, DEFAULT_UNIT); assert.strictEqual(descriptor.metricKind, MetricKind.CUMULATIVE); assert.strictEqual(descriptor.valueType, ValueType.INT64); assert.deepStrictEqual(descriptor.labels, [ - {description: 'desc', key: 'key1', valueType: 'STRING'}, { + { description: 'desc', key: 'key1', valueType: 'STRING' }, + { description: 'Opencensus task identifier', key: 'opencensus_task', - valueType: 'STRING' - } + valueType: 'STRING', + }, ]); }); }); describe('createPoint()', () => { - const startTimestamp: Timestamp = {seconds: 1546998712, nanos: 20}; - const pointTimestamp = {seconds: 1546998775, nanos: 10}; - const intPoint: - TimeSeriesPoint = {value: 12345678, timestamp: pointTimestamp}; - const doublePoint: - TimeSeriesPoint = {value: 12345678.2, timestamp: pointTimestamp}; + const startTimestamp: Timestamp = { seconds: 1546998712, nanos: 20 }; + const pointTimestamp = { seconds: 1546998775, nanos: 10 }; + const intPoint: TimeSeriesPoint = { + value: 12345678, + timestamp: pointTimestamp, + }; + const doublePoint: TimeSeriesPoint = { + value: 12345678.2, + timestamp: pointTimestamp, + }; const distributionPoint: TimeSeriesPoint = { value: { count: 3, sum: 2, sumOfSquaredDeviation: 14, - bucketOptions: {explicit: {bounds: [1.2, 3.2, 5.2]}}, - buckets: [{count: 3}, {count: 1}, {count: 2}, {count: 4}], + bucketOptions: { explicit: { bounds: [1.2, 3.2, 5.2] } }, + buckets: [{ count: 3 }, { count: 1 }, { count: 2 }, { count: 4 }], }, - timestamp: pointTimestamp + timestamp: pointTimestamp, }; it('should return a Stackdriver Point', () => { const pt = TEST_ONLY.createPoint(doublePoint, ValueType.DOUBLE); assert.deepStrictEqual(pt, { - value: {doubleValue: 12345678.2}, - interval: {endTime: '2019-01-09T01:52:55.00000001Z'} + value: { doubleValue: 12345678.2 }, + interval: { endTime: '2019-01-09T01:52:55.00000001Z' }, }); }); it('should return a Stackdriver Cumulative Point', () => { - const pt = - TEST_ONLY.createPoint(intPoint, ValueType.INT64, startTimestamp); + const pt = TEST_ONLY.createPoint( + intPoint, + ValueType.INT64, + startTimestamp + ); assert.deepStrictEqual(pt, { - value: {int64Value: 12345678}, + value: { int64Value: 12345678 }, interval: { startTime: '2019-01-09T01:51:52.00000002Z', - endTime: '2019-01-09T01:52:55.00000001Z' - } + endTime: '2019-01-09T01:52:55.00000001Z', + }, }); }); it('should return a Stackdriver Distribution Point', () => { const pt = TEST_ONLY.createPoint( - distributionPoint, ValueType.DISTRIBUTION, startTimestamp); + distributionPoint, + ValueType.DISTRIBUTION, + startTimestamp + ); assert.deepStrictEqual(pt, { value: { @@ -321,47 +398,47 @@ describe('Stackdriver Stats Exporter Utils', () => { count: 3, mean: 0.6666666666666666, sumOfSquaredDeviation: 14, - bucketOptions: {explicitBuckets: {bounds: [0, 1.2, 3.2, 5.2]}}, + bucketOptions: { explicitBuckets: { bounds: [0, 1.2, 3.2, 5.2] } }, bucketCounts: [0, 3, 1, 2, 4], - exemplars: [] - } + exemplars: [], + }, }, interval: { startTime: '2019-01-09T01:51:52.00000002Z', - endTime: '2019-01-09T01:52:55.00000001Z' - } + endTime: '2019-01-09T01:52:55.00000001Z', + }, }); }); }); describe('createTimeSeriesList()', () => { const metricPrefix = StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN; - const defaultResource = {type: 'global', labels: {}}; + const defaultResource = { type: 'global', labels: {} }; const customResource = { type: 'global', - labels: {'name': 'p0001', 'zone': 'us-west-1'} + labels: { name: 'p0001', zone: 'us-west-1' }, }; - const labelKeys = [{'key': 'key1', 'description': 'desc'}]; - const labelValues = [{'value': 'value1'}]; - const labelValues2 = [{'value': 'value2'}]; + const labelKeys = [{ key: 'key1', description: 'desc' }]; + const labelValues = [{ value: 'value1' }]; + const labelValues2 = [{ value: 'value2' }]; const cumulativeMetricDescriptor = { name: METRIC_NAME, description: METRIC_DESCRIPTION, unit: DEFAULT_UNIT, type: MetricDescriptorType.CUMULATIVE_DOUBLE, - labelKeys + labelKeys, }; - const pointTimestamp = {seconds: 100, nanos: 1e7}; - const doublePoint = {value: 12345678.2, timestamp: pointTimestamp}; - const startTimestamp: Timestamp = {seconds: 90, nanos: 1e7}; + const pointTimestamp = { seconds: 100, nanos: 1e7 }; + const doublePoint = { value: 12345678.2, timestamp: pointTimestamp }; + const startTimestamp: Timestamp = { seconds: 90, nanos: 1e7 }; const cumulativeTimeSeries = { labelValues, points: [doublePoint], - startTimestamp + startTimestamp, }; const metric = { descriptor: cumulativeMetricDescriptor, - timeseries: [cumulativeTimeSeries] + timeseries: [cumulativeTimeSeries], }; const gaugeMetricDescriptor = { @@ -369,83 +446,103 @@ describe('Stackdriver Stats Exporter Utils', () => { description: METRIC_DESCRIPTION, unit: DEFAULT_UNIT, type: MetricDescriptorType.GAUGE_DOUBLE, - labelKeys + labelKeys, + }; + const gaugePoint1 = { value: 10, timestamp: pointTimestamp }; + const gaugePoint2 = { value: 15, timestamp: pointTimestamp }; + const gaugeTimeSeries1 = { labelValues, points: [gaugePoint1] }; + const gaugeTimeSeries2 = { + labelValues: labelValues2, + points: [gaugePoint2], }; - const gaugePoint1 = {value: 10, timestamp: pointTimestamp}; - const gaugePoint2 = {value: 15, timestamp: pointTimestamp}; - const gaugeTimeSeries1 = {labelValues, points: [gaugePoint1]}; - const gaugeTimeSeries2 = {labelValues: labelValues2, points: [gaugePoint2]}; const gaugeMetric = { descriptor: gaugeMetricDescriptor, - timeseries: [gaugeTimeSeries1, gaugeTimeSeries2] + timeseries: [gaugeTimeSeries1, gaugeTimeSeries2], }; it('should return a Stackdriver TimeSeries', () => { - const timeSeriesList = - createTimeSeriesList(metric, defaultResource, metricPrefix); + const timeSeriesList = createTimeSeriesList( + metric, + defaultResource, + metricPrefix + ); assert.strictEqual(timeSeriesList.length, 1); const [timeseries] = timeSeriesList; assert.deepStrictEqual( - timeseries.metric.type, - 'custom.googleapis.com/opencensus/metric-name'); - assert.deepStrictEqual( - timeseries.metric.labels, - {'key1': 'value1', 'opencensus_task': OPENCENSUS_TASK_VALUE_DEFAULT}); + timeseries.metric.type, + 'custom.googleapis.com/opencensus/metric-name' + ); + assert.deepStrictEqual(timeseries.metric.labels, { + key1: 'value1', + opencensus_task: OPENCENSUS_TASK_VALUE_DEFAULT, + }); assert.deepStrictEqual(timeseries.metricKind, MetricKind.CUMULATIVE); assert.deepStrictEqual(timeseries.valueType, ValueType.DOUBLE); - assert.deepStrictEqual(timeseries.resource, {type: 'global', labels: {}}); + assert.deepStrictEqual(timeseries.resource, { + type: 'global', + labels: {}, + }); assert.deepStrictEqual(timeseries.points.length, 1); const [point] = timeseries.points; - assert.deepStrictEqual(point.value, {doubleValue: 12345678.2}); + assert.deepStrictEqual(point.value, { doubleValue: 12345678.2 }); }); - it('should return a Stackdriver TimeSeries with custom monitored resource', - () => { - const timeSeriesList = - createTimeSeriesList(metric, customResource, metricPrefix); - - assert.strictEqual(timeSeriesList.length, 1); - const [timeseries] = timeSeriesList; - assert.deepStrictEqual( - timeseries.metric.type, - 'custom.googleapis.com/opencensus/metric-name'); - assert.deepStrictEqual(timeseries.metric.labels, { - 'key1': 'value1', - 'opencensus_task': OPENCENSUS_TASK_VALUE_DEFAULT - }); - assert.deepStrictEqual( - timeseries.resource, - {type: 'global', labels: {'name': 'p0001', 'zone': 'us-west-1'}}); - assert.deepStrictEqual(timeseries.points.length, 1); - const [point] = timeseries.points; - assert.deepStrictEqual(point.value, {doubleValue: 12345678.2}); - }); - - it('should return a Stackdriver TimeSeries with Gauge and multiple timeseries', - () => { - const timeSeriesList = - createTimeSeriesList(gaugeMetric, defaultResource, metricPrefix); - - assert.strictEqual(timeSeriesList.length, 2); - const [timeseries1, timeseries2] = timeSeriesList; - assert.deepStrictEqual( - timeseries1.metric.type, - 'custom.googleapis.com/opencensus/metric-name'); - assert.deepStrictEqual(timeseries1.metric.labels, { - 'key1': 'value1', - 'opencensus_task': OPENCENSUS_TASK_VALUE_DEFAULT - }); - assert.deepStrictEqual(timeseries1.metricKind, MetricKind.GAUGE); - assert.deepStrictEqual(timeseries1.valueType, ValueType.DOUBLE); - assert.deepStrictEqual( - timeseries1.resource, {type: 'global', labels: {}}); - assert.deepStrictEqual(timeseries1.points.length, 1); - const [point1] = timeseries1.points; - assert.deepStrictEqual(point1.value, {doubleValue: 10}); - const [point2] = timeseries2.points; - assert.deepStrictEqual(point2.value, {doubleValue: 15}); - }); + it('should return a Stackdriver TimeSeries with custom monitored resource', () => { + const timeSeriesList = createTimeSeriesList( + metric, + customResource, + metricPrefix + ); + + assert.strictEqual(timeSeriesList.length, 1); + const [timeseries] = timeSeriesList; + assert.deepStrictEqual( + timeseries.metric.type, + 'custom.googleapis.com/opencensus/metric-name' + ); + assert.deepStrictEqual(timeseries.metric.labels, { + key1: 'value1', + opencensus_task: OPENCENSUS_TASK_VALUE_DEFAULT, + }); + assert.deepStrictEqual(timeseries.resource, { + type: 'global', + labels: { name: 'p0001', zone: 'us-west-1' }, + }); + assert.deepStrictEqual(timeseries.points.length, 1); + const [point] = timeseries.points; + assert.deepStrictEqual(point.value, { doubleValue: 12345678.2 }); + }); + + it('should return a Stackdriver TimeSeries with Gauge and multiple timeseries', () => { + const timeSeriesList = createTimeSeriesList( + gaugeMetric, + defaultResource, + metricPrefix + ); + + assert.strictEqual(timeSeriesList.length, 2); + const [timeseries1, timeseries2] = timeSeriesList; + assert.deepStrictEqual( + timeseries1.metric.type, + 'custom.googleapis.com/opencensus/metric-name' + ); + assert.deepStrictEqual(timeseries1.metric.labels, { + key1: 'value1', + opencensus_task: OPENCENSUS_TASK_VALUE_DEFAULT, + }); + assert.deepStrictEqual(timeseries1.metricKind, MetricKind.GAUGE); + assert.deepStrictEqual(timeseries1.valueType, ValueType.DOUBLE); + assert.deepStrictEqual(timeseries1.resource, { + type: 'global', + labels: {}, + }); + assert.deepStrictEqual(timeseries1.points.length, 1); + const [point1] = timeseries1.points; + assert.deepStrictEqual(point1.value, { doubleValue: 10 }); + const [point2] = timeseries2.points; + assert.deepStrictEqual(point2.value, { doubleValue: 15 }); + }); }); describe('getDefaultResource()', () => { @@ -458,29 +555,30 @@ describe('Stackdriver Stats Exporter Utils', () => { it('should return a global MonitoredResource', async () => { nocks.noDetectResource(); const monitoredResource = await getDefaultResource('my-project-id'); - const {type, labels} = monitoredResource; + const { type, labels } = monitoredResource; assert.strictEqual(type, 'global'); - assert.deepStrictEqual(labels, {project_id: 'my-project-id'}); + assert.deepStrictEqual(labels, { project_id: 'my-project-id' }); }); it('should return a k8s MonitoredResource', async () => { process.env.OC_RESOURCE_TYPE = 'k8s.io/container'; - process.env.OC_RESOURCE_LABELS = 'k8s.pod.name=pod-xyz-123,' + - 'container.name=c1,k8s.namespace.name=default,' + - 'cloud.zone=zone1'; + process.env.OC_RESOURCE_LABELS = + 'k8s.pod.name=pod-xyz-123,' + + 'container.name=c1,k8s.namespace.name=default,' + + 'cloud.zone=zone1'; CoreResource.setup(); const monitoredResource = await getDefaultResource('my-project-id'); - const {type, labels} = monitoredResource; + const { type, labels } = monitoredResource; assert.strictEqual(type, 'k8s_container'); assert.strictEqual(Object.keys(labels).length, 5); assert.deepStrictEqual(labels, { - 'container_name': 'c1', - 'namespace_name': 'default', - 'pod_name': 'pod-xyz-123', - 'project_id': 'my-project-id', - 'location': 'zone1' + container_name: 'c1', + namespace_name: 'default', + pod_name: 'pod-xyz-123', + project_id: 'my-project-id', + location: 'zone1', }); }); @@ -489,32 +587,32 @@ describe('Stackdriver Stats Exporter Utils', () => { process.env.OC_RESOURCE_LABELS = 'host.id=id1,cloud.zone=zone1'; CoreResource.setup(); const monitoredResource = await getDefaultResource('my-project-id'); - const {type, labels} = monitoredResource; + const { type, labels } = monitoredResource; assert.strictEqual(type, 'gce_instance'); assert.strictEqual(Object.keys(labels).length, 3); assert.deepStrictEqual(labels, { - 'instance_id': 'id1', - 'project_id': 'my-project-id', - 'zone': 'zone1' + instance_id: 'id1', + project_id: 'my-project-id', + zone: 'zone1', }); }); it('should return a aws MonitoredResource', async () => { process.env.OC_RESOURCE_TYPE = 'aws.com/ec2/instance'; - process.env.OC_RESOURCE_LABELS = 'cloud.account.id=id1,' + - 'host.id=instance1,cloud.region=region1'; + process.env.OC_RESOURCE_LABELS = + 'cloud.account.id=id1,' + 'host.id=instance1,cloud.region=region1'; CoreResource.setup(); const monitoredResource = await getDefaultResource('my-project-id'); - const {type, labels} = monitoredResource; + const { type, labels } = monitoredResource; assert.strictEqual(type, 'aws_ec2_instance'); assert.strictEqual(Object.keys(labels).length, 4); assert.deepStrictEqual(labels, { - 'instance_id': 'instance1', - 'region': 'aws:region1', - 'project_id': 'my-project-id', - 'aws_account': 'id1' + instance_id: 'instance1', + region: 'aws:region1', + project_id: 'my-project-id', + aws_account: 'id1', }); }); }); diff --git a/packages/opencensus-exporter-stackdriver/test/test-stackdriver-monitoring.ts b/packages/opencensus-exporter-stackdriver/test/test-stackdriver-monitoring.ts index c6f9ee912..a0c642a08 100644 --- a/packages/opencensus-exporter-stackdriver/test/test-stackdriver-monitoring.ts +++ b/packages/opencensus-exporter-stackdriver/test/test-stackdriver-monitoring.ts @@ -14,10 +14,14 @@ * limitations under the License. */ -import {globalStats, Logger, MeasureUnit, Metrics} from '@opencensus/core'; +import { globalStats, Logger, MeasureUnit, Metrics } from '@opencensus/core'; import * as assert from 'assert'; -import {StackdriverStatsExporter} from '../src/stackdriver-monitoring'; -import {MetricKind, StackdriverExporterOptions, ValueType} from '../src/types'; +import { StackdriverStatsExporter } from '../src/stackdriver-monitoring'; +import { + MetricKind, + StackdriverExporterOptions, + ValueType, +} from '../src/types'; import * as nocks from './nocks'; const PROJECT_ID = 'fake-project-id'; @@ -44,16 +48,18 @@ class MockLogger implements Logger { info(...args: any[]) {} } - describe('Stackdriver Stats Exporter', () => { // CircleCI pre-empts the VM const DELAY = 200; describe('test constants', () => { assert.strictEqual( - StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN, - 'custom.googleapis.com/opencensus'); + StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN, + 'custom.googleapis.com/opencensus' + ); assert.strictEqual( - StackdriverStatsExporter.DEFAULT_DISPLAY_NAME_PREFIX, 'OpenCensus'); + StackdriverStatsExporter.DEFAULT_DISPLAY_NAME_PREFIX, + 'OpenCensus' + ); }); describe('Send data to Stackdriver', () => { @@ -62,7 +68,11 @@ describe('Stackdriver Stats Exporter', () => { let exporter: StackdriverStatsExporter; before(() => { - exporterOptions = {period: 0, projectId: PROJECT_ID, logger: mockLogger}; + exporterOptions = { + period: 0, + projectId: PROJECT_ID, + logger: mockLogger, + }; nocks.noDetectResource(); exporter = new StackdriverStatsExporter(exporterOptions); nocks.oauth2(); @@ -86,7 +96,7 @@ describe('Stackdriver Stats Exporter', () => { const METRIC_OPTIONS = { description: METRIC_DESCRIPTION, unit: UNIT, - labelKeys: [{key: 'code', description: 'desc'}] + labelKeys: [{ key: 'code', description: 'desc' }], }; const metricRegistry = Metrics.getMetricRegistry(); @@ -101,31 +111,32 @@ describe('Stackdriver Stats Exporter', () => { assert.strictEqual(mockLogger.debugBuffer.length, 1); const [metricDescriptor] = mockLogger.debugBuffer; assert.strictEqual( - metricDescriptor.type, - `${StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN}/${ - METRIC_NAME}`); + metricDescriptor.type, + `${StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN}/${METRIC_NAME}` + ); assert.strictEqual(metricDescriptor.description, METRIC_DESCRIPTION); assert.strictEqual( - metricDescriptor.displayName, - `${StackdriverStatsExporter.DEFAULT_DISPLAY_NAME_PREFIX}/${ - METRIC_NAME}`); + metricDescriptor.displayName, + `${StackdriverStatsExporter.DEFAULT_DISPLAY_NAME_PREFIX}/${METRIC_NAME}` + ); assert.strictEqual(metricDescriptor.metricKind, MetricKind.GAUGE); assert.strictEqual(metricDescriptor.valueType, ValueType.INT64); assert.strictEqual(metricDescriptor.unit, UNIT); assert.deepStrictEqual(metricDescriptor.labels, [ - {key: 'code', valueType: 'STRING', description: 'desc'}, { + { key: 'code', valueType: 'STRING', description: 'desc' }, + { key: 'opencensus_task', valueType: 'STRING', - description: 'Opencensus task identifier' - } + description: 'Opencensus task identifier', + }, ]); - await new Promise((resolve) => setTimeout(resolve, DELAY)).then(() => { + await new Promise(resolve => setTimeout(resolve, DELAY)).then(() => { const timeSeries = mockLogger.debugBuffer[1][0]; assert.strictEqual( - timeSeries.metric.type, - `${StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN}/${ - METRIC_NAME}`); + timeSeries.metric.type, + `${StackdriverStatsExporter.CUSTOM_OPENCENSUS_DOMAIN}/${METRIC_NAME}` + ); assert.ok(timeSeries.resource.type); assert.ok(timeSeries.resource.labels.project_id); assert.strictEqual(timeSeries.resource.labels.project_id, PROJECT_ID); diff --git a/packages/opencensus-exporter-zipkin/package-lock.json b/packages/opencensus-exporter-zipkin/package-lock.json index ef29543aa..6f5ed58af 100644 --- a/packages/opencensus-exporter-zipkin/package-lock.json +++ b/packages/opencensus-exporter-zipkin/package-lock.json @@ -169,9 +169,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -232,58 +232,6 @@ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -437,16 +385,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -529,8 +467,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -938,7 +875,7 @@ }, "got": { "version": "6.7.1", - "resolved": "http://registry.npmjs.org/got/-/got-6.7.1.tgz", + "resolved": "https://registry.npmjs.org/got/-/got-6.7.1.tgz", "integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=", "requires": { "create-error-class": "^3.0.0", @@ -965,37 +902,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -1026,21 +963,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1129,29 +1051,42 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } } } }, @@ -1407,15 +1342,10 @@ "handlebars": "^4.1.2" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -1885,7 +1815,7 @@ }, "find-up": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "resolved": false, "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", "requires": { "locate-path": "^3.0.0" @@ -1915,7 +1845,7 @@ }, "locate-path": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "resolved": false, "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", "requires": { "p-locate": "^3.0.0", @@ -1941,7 +1871,7 @@ }, "p-locate": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "resolved": false, "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", "requires": { "p-limit": "^2.0.0" @@ -1954,7 +1884,7 @@ }, "rimraf": { "version": "2.6.3", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "resolved": false, "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", "requires": { "glob": "^7.1.3" @@ -2252,6 +2182,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "propagate": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/propagate/-/propagate-1.0.0.tgz", @@ -2328,9 +2263,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2363,11 +2298,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2401,9 +2336,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2534,17 +2469,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2775,29 +2710,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2967,9 +2896,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-exporter-zipkin/package.json b/packages/opencensus-exporter-zipkin/package.json index 8597b99ab..41d7de92c 100644 --- a/packages/opencensus-exporter-zipkin/package.json +++ b/packages/opencensus-exporter-zipkin/package.json @@ -53,7 +53,7 @@ "@types/nock": "^10.0.0", "@types/node": "^10.12.12", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nock": "^10.0.0", "nyc": "14.1.1", diff --git a/packages/opencensus-exporter-zipkin/src/zipkin.ts b/packages/opencensus-exporter-zipkin/src/zipkin.ts index 0ebb66103..cfc52aee3 100644 --- a/packages/opencensus-exporter-zipkin/src/zipkin.ts +++ b/packages/opencensus-exporter-zipkin/src/zipkin.ts @@ -15,18 +15,24 @@ */ import * as coreTypes from '@opencensus/core'; -import {Exporter, ExporterBuffer, ExporterConfig, Span, SpanKind} from '@opencensus/core'; -import {logger, Logger} from '@opencensus/core'; +import { + Exporter, + ExporterBuffer, + ExporterConfig, + Span, + SpanKind, +} from '@opencensus/core'; +import { logger, Logger } from '@opencensus/core'; import * as http from 'http'; import * as url from 'url'; const STATUS_CODE = 'census.status_code'; const STATUS_DESCRIPTION = 'census.status_description'; -const MESSAGE_EVENT_TYPE_TRANSLATION: {[k: number]: string} = { +const MESSAGE_EVENT_TYPE_TRANSLATION: { [k: number]: string } = { 0: 'UNSPECIFIED', 1: 'SENT', - 2: 'RECEIVED' + 2: 'RECEIVED', }; export const MICROS_PER_MILLI = 1000; @@ -41,17 +47,17 @@ export interface TranslatedSpan { id: string; parentId?: string; kind: string; - timestamp: number; // in microseconds + timestamp: number; // in microseconds duration: number; debug: boolean; shared: boolean; - localEndpoint: {serviceName: string}; + localEndpoint: { serviceName: string }; annotations: Annotation[]; - tags: {[key: string]: string}; + tags: { [key: string]: string }; } export interface Annotation { - timestamp?: number; // in microseconds + timestamp?: number; // in microseconds value?: string; } @@ -64,8 +70,9 @@ export class ZipkinTraceExporter implements Exporter { logger: Logger; constructor(options: ZipkinExporterOptions) { - this.zipkinUrl = options.url && url.parse(options.url) || - url.parse(ZipkinTraceExporter.DEFAULT_URL); + this.zipkinUrl = + (options.url && url.parse(options.url)) || + url.parse(ZipkinTraceExporter.DEFAULT_URL); this.serviceName = options.serviceName; this.buffer = new ExporterBuffer(this, options); this.logger = options.logger || logger.logger(); @@ -98,25 +105,27 @@ export class ZipkinTraceExporter implements Exporter { method: 'POST', headers: { 'Content-Type': 'application/json', - } + }, }; return new Promise((resolve, reject) => { /** Request object */ - const req = http.request(options, (res) => { - res.on('data', (chunk) => {}); + const req = http.request(options, res => { + res.on('data', chunk => {}); // Resolve on end res.on('end', () => { - resolve( - {statusCode: res.statusCode, statusMessage: res.statusMessage}); + resolve({ + statusCode: res.statusCode, + statusMessage: res.statusMessage, + }); }); }); /** Request error event */ - req.on('error', (e) => { + req.on('error', e => { reject({ statusCode: 0, - statusMessage: `Problem with request: ${e.message}` + statusMessage: `Problem with request: ${e.message}`, }); }); @@ -169,9 +178,9 @@ export class ZipkinTraceExporter implements Exporter { duration: Math.round(span.duration * MICROS_PER_MILLI), debug: true, shared: !span.parentSpanId, - localEndpoint: {serviceName: this.serviceName}, + localEndpoint: { serviceName: this.serviceName }, tags: this.createTags(span.attributes, span.status), - annotations: this.createAnnotations(span.annotations, span.messageEvents) + annotations: this.createAnnotations(span.annotations, span.messageEvents), }; if (span.parentSpanId) { @@ -182,8 +191,10 @@ export class ZipkinTraceExporter implements Exporter { /** Converts OpenCensus Attributes and Status to Zipkin Tags format. */ private createTags( - attributes: coreTypes.Attributes, status: coreTypes.Status) { - const tags: {[key: string]: string} = {}; + attributes: coreTypes.Attributes, + status: coreTypes.Status + ) { + const tags: { [key: string]: string } = {}; for (const key of Object.keys(attributes)) { tags[key] = String(attributes[key]); } @@ -199,22 +210,23 @@ export class ZipkinTraceExporter implements Exporter { * format. */ private createAnnotations( - annotationTimedEvents: coreTypes.Annotation[], - messageEventTimedEvents: coreTypes.MessageEvent[]) { + annotationTimedEvents: coreTypes.Annotation[], + messageEventTimedEvents: coreTypes.MessageEvent[] + ) { let annotations: Annotation[] = []; if (annotationTimedEvents) { - annotations = annotationTimedEvents.map( - (annotation) => ({ - timestamp: annotation.timestamp * MICROS_PER_MILLI, - value: annotation.description - })); + annotations = annotationTimedEvents.map(annotation => ({ + timestamp: annotation.timestamp * MICROS_PER_MILLI, + value: annotation.description, + })); } if (messageEventTimedEvents) { - annotations.push(...messageEventTimedEvents.map( - (messageEvent) => ({ - timestamp: messageEvent.timestamp * MICROS_PER_MILLI, - value: MESSAGE_EVENT_TYPE_TRANSLATION[messageEvent.type] - }))); + annotations.push( + ...messageEventTimedEvents.map(messageEvent => ({ + timestamp: messageEvent.timestamp * MICROS_PER_MILLI, + value: MESSAGE_EVENT_TYPE_TRANSLATION[messageEvent.type], + })) + ); } return annotations; } @@ -228,7 +240,7 @@ export class ZipkinTraceExporter implements Exporter { publish(spans: Span[]) { const spanList = this.mountSpanList(spans); - return this.sendTraces(spanList).catch((err) => { + return this.sendTraces(spanList).catch(err => { return err; }); } diff --git a/packages/opencensus-exporter-zipkin/test/test-zipkin.ts b/packages/opencensus-exporter-zipkin/test/test-zipkin.ts index 5ea6b8567..9c987961a 100644 --- a/packages/opencensus-exporter-zipkin/test/test-zipkin.ts +++ b/packages/opencensus-exporter-zipkin/test/test-zipkin.ts @@ -14,11 +14,23 @@ * limitations under the License. */ -import {CanonicalCode, CoreTracer, MessageEventType, Span, SpanKind, TracerConfig} from '@opencensus/core'; +import { + CanonicalCode, + CoreTracer, + MessageEventType, + Span, + SpanKind, + TracerConfig, +} from '@opencensus/core'; import * as assert from 'assert'; import * as nock from 'nock'; -import {MICROS_PER_MILLI, TranslatedSpan, ZipkinExporterOptions, ZipkinTraceExporter} from '../src/zipkin'; +import { + MICROS_PER_MILLI, + TranslatedSpan, + ZipkinExporterOptions, + ZipkinTraceExporter, +} from '../src/zipkin'; /** Zipkin host url */ const zipkinHost = 'http://localhost:9411'; @@ -34,12 +46,12 @@ const OPENCENSUS_NETWORK_TESTS = process.env.OPENCENSUS_NETWORK_TESTS; /** Default options for zipkin tests */ const zipkinOptions: ZipkinExporterOptions = { url: zipkinHost + postPath, - serviceName: 'opencensus-tests' + serviceName: 'opencensus-tests', }; /** Default config for traces tests */ const defaultConfig: TracerConfig = { - samplingRate: 1 + samplingRate: 1, }; /** Zipkin tests */ @@ -55,9 +67,11 @@ describe('Zipkin Exporter', function() { tracer.registerSpanEventListener(exporter); tracer.start(defaultConfig); - tracer.startRootSpan({name: 'root-test'}, (rootSpan: Span) => { - const span = - rootSpan.startChildSpan({name: 'spanTest', kind: SpanKind.CLIENT}); + tracer.startRootSpan({ name: 'root-test' }, (rootSpan: Span) => { + const span = rootSpan.startChildSpan({ + name: 'spanTest', + kind: SpanKind.CLIENT, + }); span.end(); rootSpan.end(); assert.ok(exporter.buffer.getQueue().length > 0); @@ -81,78 +95,81 @@ describe('Zipkin Exporter', function() { if (!OPENCENSUS_NETWORK_TESTS) { /** Run a nock server to replace zipkin service */ scope = nock(zipkinHost) - .persist() - .post( - postPath, - (body: [TranslatedSpan]) => { - requestBody = body; - return true; - }) - .reply(202); + .persist() + .post(postPath, (body: [TranslatedSpan]) => { + requestBody = body; + return true; + }) + .reply(202); } return tracer.startRootSpan( - {name: 'root-test'}, async (rootSpan: Span) => { - const span1 = rootSpan.startChildSpan( - {name: 'spanTest', kind: SpanKind.CLIENT}); - const span2 = tracer.startChildSpan( - {name: 'spanTest', kind: SpanKind.CLIENT, childOf: span1}); - span2.end(); - span1.end(); - rootSpan.end(); - return exporter.publish([rootSpan]).then((result) => { - assert.strictEqual(result.statusCode, 202); + { name: 'root-test' }, + async (rootSpan: Span) => { + const span1 = rootSpan.startChildSpan({ + name: 'spanTest', + kind: SpanKind.CLIENT, + }); + const span2 = tracer.startChildSpan({ + name: 'spanTest', + kind: SpanKind.CLIENT, + childOf: span1, + }); + span2.end(); + span1.end(); + rootSpan.end(); + return exporter.publish([rootSpan]).then(result => { + assert.strictEqual(result.statusCode, 202); - if (!OPENCENSUS_NETWORK_TESTS) { - scope.done(); - assert.deepStrictEqual(requestBody, [ - { - 'annotations': [], - 'debug': true, - 'duration': - Math.round(rootSpan.duration * MICROS_PER_MILLI), - 'id': rootSpan.id, - 'kind': 'SERVER', - 'localEndpoint': {'serviceName': 'opencensus-tests'}, - 'name': 'root-test', - 'shared': true, - 'tags': {'census.status_code': '0'}, - 'timestamp': - rootSpan.startTime.getTime() * MICROS_PER_MILLI, - 'traceId': rootSpan.traceId - }, - { - 'annotations': [], - 'debug': true, - 'duration': Math.round(span1.duration * MICROS_PER_MILLI), - 'id': span1.id, - 'kind': 'CLIENT', - 'localEndpoint': {'serviceName': 'opencensus-tests'}, - 'name': 'spanTest', - 'parentId': rootSpan.id, - 'shared': false, - 'tags': {'census.status_code': '0'}, - 'timestamp': span1.startTime.getTime() * MICROS_PER_MILLI, - 'traceId': span1.traceId - }, - { - 'annotations': [], - 'debug': true, - 'duration': Math.round(span2.duration * MICROS_PER_MILLI), - 'id': span2.id, - 'kind': 'CLIENT', - 'localEndpoint': {'serviceName': 'opencensus-tests'}, - 'name': 'spanTest', - 'parentId': span1.id, - 'shared': false, - 'tags': {'census.status_code': '0'}, - 'timestamp': span2.startTime.getTime() * MICROS_PER_MILLI, - 'traceId': span2.traceId - } - ]); - } - }); + if (!OPENCENSUS_NETWORK_TESTS) { + scope.done(); + assert.deepStrictEqual(requestBody, [ + { + annotations: [], + debug: true, + duration: Math.round(rootSpan.duration * MICROS_PER_MILLI), + id: rootSpan.id, + kind: 'SERVER', + localEndpoint: { serviceName: 'opencensus-tests' }, + name: 'root-test', + shared: true, + tags: { 'census.status_code': '0' }, + timestamp: rootSpan.startTime.getTime() * MICROS_PER_MILLI, + traceId: rootSpan.traceId, + }, + { + annotations: [], + debug: true, + duration: Math.round(span1.duration * MICROS_PER_MILLI), + id: span1.id, + kind: 'CLIENT', + localEndpoint: { serviceName: 'opencensus-tests' }, + name: 'spanTest', + parentId: rootSpan.id, + shared: false, + tags: { 'census.status_code': '0' }, + timestamp: span1.startTime.getTime() * MICROS_PER_MILLI, + traceId: span1.traceId, + }, + { + annotations: [], + debug: true, + duration: Math.round(span2.duration * MICROS_PER_MILLI), + id: span2.id, + kind: 'CLIENT', + localEndpoint: { serviceName: 'opencensus-tests' }, + name: 'spanTest', + parentId: span1.id, + shared: false, + tags: { 'census.status_code': '0' }, + timestamp: span2.startTime.getTime() * MICROS_PER_MILLI, + traceId: span2.traceId, + }, + ]); + } }); + } + ); }); }); @@ -160,14 +177,16 @@ describe('Zipkin Exporter', function() { let rootSpan: Span; let span: Span; - before((done) => { + before(done => { const tracer = new CoreTracer(); tracer.start(defaultConfig); - return tracer.startRootSpan({name: 'root-test'}, (_rootSpan: Span) => { + return tracer.startRootSpan({ name: 'root-test' }, (_rootSpan: Span) => { rootSpan = _rootSpan; - span = - rootSpan.startChildSpan({name: 'spanTest', kind: SpanKind.CLIENT}); + span = rootSpan.startChildSpan({ + name: 'spanTest', + kind: SpanKind.CLIENT, + }); span.addAttribute('my-int-attribute', 100); span.addAttribute('my-str-attribute', 'value'); span.addAttribute('my-bool-attribute', true); @@ -189,17 +208,17 @@ describe('Zipkin Exporter', function() { const exporter = new ZipkinTraceExporter(zipkinOptions); const rootSpanTranslated = exporter.translateSpan(rootSpan); assert.deepStrictEqual(rootSpanTranslated, { - 'annotations': [], - 'debug': true, - 'duration': Math.round(rootSpan.duration * MICROS_PER_MILLI), - 'id': rootSpan.id, - 'kind': 'SERVER', - 'localEndpoint': {'serviceName': 'opencensus-tests'}, - 'name': 'root-test', - 'shared': true, - 'tags': {'census.status_code': '0'}, - 'timestamp': rootSpan.startTime.getTime() * MICROS_PER_MILLI, - 'traceId': rootSpan.traceId + annotations: [], + debug: true, + duration: Math.round(rootSpan.duration * MICROS_PER_MILLI), + id: rootSpan.id, + kind: 'SERVER', + localEndpoint: { serviceName: 'opencensus-tests' }, + name: 'root-test', + shared: true, + tags: { 'census.status_code': '0' }, + timestamp: rootSpan.startTime.getTime() * MICROS_PER_MILLI, + traceId: rootSpan.traceId, }); }); @@ -207,72 +226,78 @@ describe('Zipkin Exporter', function() { const exporter = new ZipkinTraceExporter(zipkinOptions); const chilsSpanTranslated = exporter.translateSpan(span); assert.deepStrictEqual(chilsSpanTranslated, { - 'annotations': [ - {'timestamp': 1550213104708000, 'value': 'processing'}, - {'timestamp': 1550213104708000, 'value': 'done'}, - {'timestamp': 1550213104708000, 'value': 'SENT'}, - {'timestamp': 1550213104708000, 'value': 'RECEIVED'}, - {'timestamp': 1550213104708000, 'value': 'UNSPECIFIED'} + annotations: [ + { timestamp: 1550213104708000, value: 'processing' }, + { timestamp: 1550213104708000, value: 'done' }, + { timestamp: 1550213104708000, value: 'SENT' }, + { timestamp: 1550213104708000, value: 'RECEIVED' }, + { timestamp: 1550213104708000, value: 'UNSPECIFIED' }, ], - 'debug': true, - 'duration': Math.round(span.duration * MICROS_PER_MILLI), - 'id': span.id, - 'kind': 'CLIENT', - 'localEndpoint': {'serviceName': 'opencensus-tests'}, - 'name': 'spanTest', - 'parentId': rootSpan.id, - 'shared': false, - 'tags': { + debug: true, + duration: Math.round(span.duration * MICROS_PER_MILLI), + id: span.id, + kind: 'CLIENT', + localEndpoint: { serviceName: 'opencensus-tests' }, + name: 'spanTest', + parentId: rootSpan.id, + shared: false, + tags: { 'census.status_code': '8', 'census.status_description': 'RESOURCE_EXHAUSTED', 'my-int-attribute': '100', 'my-str-attribute': 'value', - 'my-bool-attribute': 'true' + 'my-bool-attribute': 'true', }, - 'timestamp': span.startTime.getTime() * MICROS_PER_MILLI, - 'traceId': span.traceId + timestamp: span.startTime.getTime() * MICROS_PER_MILLI, + traceId: span.traceId, }); }); }); describe('publish() with a wrong Zipkin url', () => { - it('shouldn\'t send traces to Zipkin service and return an 404 error', - () => { - /** Creating new options with a wrong url */ - const options: ZipkinExporterOptions = { - url: zipkinHost + '/wrong', - serviceName: 'opencensus-tests' - }; + it("shouldn't send traces to Zipkin service and return an 404 error", () => { + /** Creating new options with a wrong url */ + const options: ZipkinExporterOptions = { + url: zipkinHost + '/wrong', + serviceName: 'opencensus-tests', + }; - let scope: nock.Scope; + let scope: nock.Scope; - /** - * Checking if tests will use a real network, otherwise run a nock - * server - */ - if (!OPENCENSUS_NETWORK_TESTS) { - /** Run a nock server to replace zipkin service */ - scope = nock(zipkinHost).persist().post('/wrong').reply(404); - } + /** + * Checking if tests will use a real network, otherwise run a nock + * server + */ + if (!OPENCENSUS_NETWORK_TESTS) { + /** Run a nock server to replace zipkin service */ + scope = nock(zipkinHost) + .persist() + .post('/wrong') + .reply(404); + } - const exporter = new ZipkinTraceExporter(options); - const tracer = new CoreTracer(); - tracer.start(defaultConfig); + const exporter = new ZipkinTraceExporter(options); + const tracer = new CoreTracer(); + tracer.start(defaultConfig); - return tracer.startRootSpan( - {name: 'root-test'}, async (rootSpan: Span) => { - const span = rootSpan.startChildSpan( - {name: 'spanTest', kind: SpanKind.CLIENT}); - span.end(); - rootSpan.end(); - return exporter.publish([rootSpan]).then((result) => { - assert.strictEqual(result.statusCode, 404); + return tracer.startRootSpan( + { name: 'root-test' }, + async (rootSpan: Span) => { + const span = rootSpan.startChildSpan({ + name: 'spanTest', + kind: SpanKind.CLIENT, + }); + span.end(); + rootSpan.end(); + return exporter.publish([rootSpan]).then(result => { + assert.strictEqual(result.statusCode, 404); - if (!OPENCENSUS_NETWORK_TESTS) { - scope.done(); - } - }); - }); - }); + if (!OPENCENSUS_NETWORK_TESTS) { + scope.done(); + } + }); + } + ); + }); }); }); diff --git a/packages/opencensus-exporter-zpages/package-lock.json b/packages/opencensus-exporter-zpages/package-lock.json index 84dd95217..f13854414 100644 --- a/packages/opencensus-exporter-zpages/package-lock.json +++ b/packages/opencensus-exporter-zpages/package-lock.json @@ -240,9 +240,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -303,11 +303,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, "axios": { "version": "0.19.0", "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.0.tgz", @@ -317,53 +312,6 @@ "is-buffer": "^2.0.2" } }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -526,16 +474,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -618,8 +556,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -1187,37 +1124,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -1248,21 +1185,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1359,23 +1281,43 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } } }, "invert-kv": { @@ -1630,15 +1572,10 @@ "handlebars": "^4.1.2" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2498,6 +2435,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "proxy-addr": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.3.tgz", @@ -2617,9 +2559,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2652,11 +2594,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2690,9 +2632,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2874,17 +2816,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -3115,29 +3057,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -3326,9 +3262,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-exporter-zpages/package.json b/packages/opencensus-exporter-zpages/package.json index 64ec9ff50..ad19f8e95 100644 --- a/packages/opencensus-exporter-zpages/package.json +++ b/packages/opencensus-exporter-zpages/package.json @@ -58,7 +58,7 @@ "@types/node": "^10.12.12", "axios": "^0.19.0", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "14.1.1", "rimraf": "^2.6.2", diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/rpcz.controller.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/rpcz.controller.ts index dd0b31954..d9a26590d 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/rpcz.controller.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/rpcz.controller.ts @@ -15,8 +15,8 @@ */ import * as express from 'express'; -import {StatsParams} from '../../zpages'; -import {RpczPageHandler} from './../page-handlers/rpcz.page-handler'; +import { StatsParams } from '../../zpages'; +import { RpczPageHandler } from './../page-handlers/rpcz.page-handler'; /** * An Express middleware that renders the RPCz view. diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/statsz.controller.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/statsz.controller.ts index 1551815cc..317544275 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/statsz.controller.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/statsz.controller.ts @@ -15,8 +15,8 @@ */ import * as express from 'express'; -import {StatsParams} from '../../zpages'; -import {StatszPageHandler} from './../page-handlers/statsz.page-handler'; +import { StatsParams } from '../../zpages'; +import { StatszPageHandler } from './../page-handlers/statsz.page-handler'; /** * An Express middleware that renders the Statsz view. diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/traceconfigz.controller.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/traceconfigz.controller.ts index a37ec24bb..ab3084522 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/traceconfigz.controller.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/traceconfigz.controller.ts @@ -15,7 +15,7 @@ */ import * as express from 'express'; -import {TraceConfigzPageHandler} from './../page-handlers/traceconfigz.page-handler'; +import { TraceConfigzPageHandler } from './../page-handlers/traceconfigz.page-handler'; /** * An Express middleware that renders the TraceConfigz view. diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/tracez.controller.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/tracez.controller.ts index 211de87df..727f25791 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/tracez.controller.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/controllers/tracez.controller.ts @@ -14,16 +14,17 @@ * limitations under the License. */ -import {Span} from '@opencensus/core'; +import { Span } from '@opencensus/core'; import * as express from 'express'; -import {TracezPageHandler} from './../page-handlers/tracez.page-handler'; +import { TracezPageHandler } from './../page-handlers/tracez.page-handler'; /** * Creates an Express middleware that renders the Tracez view. * @param traceMap A span data store. */ -export function createTracezHandler(traceMap: Map): - express.Handler { +export function createTracezHandler( + traceMap: Map +): express.Handler { return (req: express.Request, res: express.Response) => { const html = new TracezPageHandler(traceMap); res.send(html.emitHtml(req.query, req.query.json === '1')); diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/latency-bucket-boundaries.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/latency-bucket-boundaries.ts index 580a6d566..034354607 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/latency-bucket-boundaries.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/latency-bucket-boundaries.ts @@ -22,30 +22,41 @@ export class LatencyBucketBoundaries { // Using the opencensus java standard names /* tslint:disable:variable-name */ static readonly ZERO_MICROSx10 = new LatencyBucketBoundaries( - 0, LatencyBucketBoundaries.microsecondsToNanos(10)); + 0, + LatencyBucketBoundaries.microsecondsToNanos(10) + ); static readonly MICROSx10_MICROSx100 = new LatencyBucketBoundaries( - LatencyBucketBoundaries.microsecondsToNanos(10), - LatencyBucketBoundaries.microsecondsToNanos(100)); + LatencyBucketBoundaries.microsecondsToNanos(10), + LatencyBucketBoundaries.microsecondsToNanos(100) + ); static readonly MICROSx100_MILLIx1 = new LatencyBucketBoundaries( - LatencyBucketBoundaries.microsecondsToNanos(100), - LatencyBucketBoundaries.millisecondsToNanos(1)); + LatencyBucketBoundaries.microsecondsToNanos(100), + LatencyBucketBoundaries.millisecondsToNanos(1) + ); static readonly MILLIx1_MILLIx10 = new LatencyBucketBoundaries( - LatencyBucketBoundaries.millisecondsToNanos(1), - LatencyBucketBoundaries.millisecondsToNanos(10)); + LatencyBucketBoundaries.millisecondsToNanos(1), + LatencyBucketBoundaries.millisecondsToNanos(10) + ); static readonly MILLIx10_MILLIx100 = new LatencyBucketBoundaries( - LatencyBucketBoundaries.millisecondsToNanos(10), - LatencyBucketBoundaries.millisecondsToNanos(100)); + LatencyBucketBoundaries.millisecondsToNanos(10), + LatencyBucketBoundaries.millisecondsToNanos(100) + ); static readonly MILLIx100_SECONDx1 = new LatencyBucketBoundaries( - LatencyBucketBoundaries.millisecondsToNanos(100), - LatencyBucketBoundaries.secondsToNanos(1)); + LatencyBucketBoundaries.millisecondsToNanos(100), + LatencyBucketBoundaries.secondsToNanos(1) + ); static readonly SECONDx1_SECONDx10 = new LatencyBucketBoundaries( - LatencyBucketBoundaries.secondsToNanos(1), - LatencyBucketBoundaries.secondsToNanos(10)); + LatencyBucketBoundaries.secondsToNanos(1), + LatencyBucketBoundaries.secondsToNanos(10) + ); static readonly SECONDx10_SECONDx100 = new LatencyBucketBoundaries( - LatencyBucketBoundaries.secondsToNanos(10), - LatencyBucketBoundaries.secondsToNanos(100)); + LatencyBucketBoundaries.secondsToNanos(10), + LatencyBucketBoundaries.secondsToNanos(100) + ); static readonly SECONDx100_MAX = new LatencyBucketBoundaries( - LatencyBucketBoundaries.secondsToNanos(100), Number.MAX_VALUE); + LatencyBucketBoundaries.secondsToNanos(100), + Number.MAX_VALUE + ); /* tslint:enable */ /** Latency list */ @@ -58,7 +69,7 @@ export class LatencyBucketBoundaries { LatencyBucketBoundaries.MILLIx100_SECONDx1, LatencyBucketBoundaries.SECONDx1_SECONDx10, LatencyBucketBoundaries.SECONDx10_SECONDx100, - LatencyBucketBoundaries.SECONDx100_MAX + LatencyBucketBoundaries.SECONDx100_MAX, ]; constructor(latencyLowerNs: number, latencyUpperNs: number) { @@ -130,8 +141,9 @@ export class LatencyBucketBoundaries { * Gets the corresponding LatencyBucketBoundaries from a time in nanoseconds * @param timeNs time in nanoseconds */ - static getLatencyBucketBoundariesByTime(timeNs: number): - LatencyBucketBoundaries { + static getLatencyBucketBoundariesByTime( + timeNs: number + ): LatencyBucketBoundaries { for (const latency of LatencyBucketBoundaries.values) { if (latency.belongs(timeNs)) { return latency; @@ -164,6 +176,6 @@ export class LatencyBucketBoundaries { * @returns nanoseconds */ static secondsToNanos(seconds: number): number { - return seconds * 1e+9; + return seconds * 1e9; } } diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/rpcz.page-handler.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/rpcz.page-handler.ts index b16d2795f..5482171e8 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/rpcz.page-handler.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/rpcz.page-handler.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import {AggregationType} from '@opencensus/core'; +import { AggregationType } from '@opencensus/core'; import * as ejs from 'ejs'; -import {StatsParams} from '../../zpages'; -import {templatesDir} from './templates-dir'; +import { StatsParams } from '../../zpages'; +import { templatesDir } from './templates-dir'; const FIXED_SIZE = 3; @@ -41,8 +41,8 @@ export interface ZMeasure { * Information used to render the Rpcz UI. */ export interface RpczData { - measuresSent: {[key: string]: ZMeasure}; - measuresReceived: {[key: string]: ZMeasure}; + measuresSent: { [key: string]: ZMeasure }; + measuresReceived: { [key: string]: ZMeasure }; } enum DefaultViews { @@ -55,7 +55,7 @@ enum DefaultViews { SERVER_SENT_BYTES_PER_RPC = 'grpc.io/server/sent_bytes_per_rpc', SERVER_SERVER_LATENCY = 'grpc.io/server/server_latency', SERVER_COMPLETED_RPCS = 'grpc.io/server/completed_rpcs', - SERVER_STARTED_RPCS = 'grpc.io/server/started_rpcs' + SERVER_STARTED_RPCS = 'grpc.io/server/started_rpcs', } export class RpczPageHandler { @@ -70,14 +70,16 @@ export class RpczPageHandler { /** template HTML */ const rpczFile = ejs.fileLoader(`${templatesDir}/rpcz.ejs`).toString(); /** CSS styles file */ - const stylesFile = - ejs.fileLoader(`${templatesDir}/styles.min.css`).toString(); + const stylesFile = ejs + .fileLoader(`${templatesDir}/styles.min.css`) + .toString(); /** EJS render options */ - const options = {delimiter: '?'}; + const options = { delimiter: '?' }; const rpcViews = this.statsParams.registeredViews.filter( - view => view.name.indexOf('http') < 0); - const rpczData: RpczData = {measuresSent: {}, measuresReceived: {}}; + view => view.name.indexOf('http') < 0 + ); + const rpczData: RpczData = { measuresSent: {}, measuresReceived: {} }; for (const view of rpcViews) { const recordedData = this.statsParams.recordedData[view.name]; @@ -102,15 +104,15 @@ export class RpczPageHandler { let method = ''; let zMeasures; if (clientMethodIndex !== -1) { - method = snapshot.tagValues[clientMethodIndex] ? - snapshot.tagValues[clientMethodIndex]!.value : - ''; + method = snapshot.tagValues[clientMethodIndex] + ? snapshot.tagValues[clientMethodIndex]!.value + : ''; zMeasures = rpczData.measuresSent; } else if (serverMethodIndex !== -1) { // Switches to received data if it's a server - method = snapshot.tagValues[serverMethodIndex] ? - snapshot.tagValues[serverMethodIndex]!.value : - ''; + method = snapshot.tagValues[serverMethodIndex] + ? snapshot.tagValues[serverMethodIndex]!.value + : ''; zMeasures = rpczData.measuresReceived; } if (zMeasures && method) { @@ -119,76 +121,90 @@ export class RpczPageHandler { } if (snapshot.type === AggregationType.DISTRIBUTION) { // Fills the output columns for that method - if (view.name === DefaultViews.CLIENT_SENT_BYTES_PER_RPC || - view.name === DefaultViews.SERVER_SENT_BYTES_PER_RPC) { + if ( + view.name === DefaultViews.CLIENT_SENT_BYTES_PER_RPC || + view.name === DefaultViews.SERVER_SENT_BYTES_PER_RPC + ) { zMeasures[method].output.tot += snapshot.sum / 1024; zMeasures[method].output.min = - this.getRate( - zMeasures[method].output.tot, new Date(view.startTime)) * - 60; + this.getRate( + zMeasures[method].output.tot, + new Date(view.startTime) + ) * 60; zMeasures[method].output.hr = zMeasures[method].output.min * 60; } // Fills the input columns for that method - if (view.name === DefaultViews.CLIENT_RECEIVED_BYTES_PER_RPC || - view.name === DefaultViews.SERVER_RECEIVED_BYTES_PER_RPC) { + if ( + view.name === DefaultViews.CLIENT_RECEIVED_BYTES_PER_RPC || + view.name === DefaultViews.SERVER_RECEIVED_BYTES_PER_RPC + ) { zMeasures[method].input.tot += snapshot.sum / 1024; zMeasures[method].input.min = - this.getRate( - zMeasures[method].input.tot, new Date(view.startTime)) * - 60; + this.getRate( + zMeasures[method].input.tot, + new Date(view.startTime) + ) * 60; zMeasures[method].input.hr = zMeasures[method].input.min * 60; } } - if (snapshot.type === AggregationType.COUNT && - (view.name === DefaultViews.CLIENT_COMPLETED_RPCS || - view.name === DefaultViews.SERVER_COMPLETED_RPCS)) { + if ( + snapshot.type === AggregationType.COUNT && + (view.name === DefaultViews.CLIENT_COMPLETED_RPCS || + view.name === DefaultViews.SERVER_COMPLETED_RPCS) + ) { // Fills the count columns for that method zMeasures[method].count.tot += snapshot.value; zMeasures[method].count.min = - this.getRate( - zMeasures[method].count.tot, new Date(view.startTime)) * - 60; + this.getRate( + zMeasures[method].count.tot, + new Date(view.startTime) + ) * 60; zMeasures[method].count.hr = zMeasures[method].count.min * 60; // Fills the rate columns for that method zMeasures[method].rate.tot = this.getRate( - zMeasures[method].count.tot, new Date(view.startTime)); + zMeasures[method].count.tot, + new Date(view.startTime) + ); zMeasures[method].rate.min = zMeasures[method].rate.tot * 60; zMeasures[method].rate.hr = zMeasures[method].rate.min * 60; // Fills the error columns for that method const error = - (clientStatusIndex !== -1 && - snapshot.tagValues[clientStatusIndex] && - snapshot.tagValues[clientStatusIndex]!.value !== 'OK') || - (serverStatusIndex !== -1 && - snapshot.tagValues[serverStatusIndex] && - snapshot.tagValues[serverStatusIndex]!.value !== 'OK'); + (clientStatusIndex !== -1 && + snapshot.tagValues[clientStatusIndex] && + snapshot.tagValues[clientStatusIndex]!.value !== 'OK') || + (serverStatusIndex !== -1 && + snapshot.tagValues[serverStatusIndex] && + snapshot.tagValues[serverStatusIndex]!.value !== 'OK'); if (error) { zMeasures[method].errors.tot += snapshot.value; zMeasures[method].errors.min = - this.getRate( - zMeasures[method].errors.tot, new Date(view.startTime)) * - 60; + this.getRate( + zMeasures[method].errors.tot, + new Date(view.startTime) + ) * 60; zMeasures[method].errors.hr = zMeasures[method].errors.min * 60; } } // Fills the avgLatency columns for that method - if (snapshot.type === AggregationType.DISTRIBUTION && - (view.name === DefaultViews.CLIENT_ROUDTRIP_LATENCY || - view.name === DefaultViews.SERVER_SERVER_LATENCY)) { + if ( + snapshot.type === AggregationType.DISTRIBUTION && + (view.name === DefaultViews.CLIENT_ROUDTRIP_LATENCY || + view.name === DefaultViews.SERVER_SERVER_LATENCY) + ) { zMeasures[method].avgLatency.tot = snapshot.mean; zMeasures[method].avgLatency.min = - this.getRate( - zMeasures[method].avgLatency.tot, - new Date(view.startTime)) * - 60; + this.getRate( + zMeasures[method].avgLatency.tot, + new Date(view.startTime) + ) * 60; zMeasures[method].avgLatency.hr = - zMeasures[method].avgLatency.min * 60; + zMeasures[method].avgLatency.min * 60; } } } @@ -197,13 +213,15 @@ export class RpczPageHandler { return JSON.stringify(rpczData, null, 2); } else { return ejs.render( - rpczFile, { - styles: stylesFile, - zMeasuresSent: rpczData.measuresSent, - zMeasuresReceived: rpczData.measuresReceived, - FIXED_SIZE - }, - options); + rpczFile, + { + styles: stylesFile, + zMeasuresSent: rpczData.measuresSent, + zMeasuresReceived: rpczData.measuresReceived, + FIXED_SIZE, + }, + options + ); } } @@ -220,12 +238,12 @@ export class RpczPageHandler { private newEmptyZMeasure(): ZMeasure { return { method: '', - count: {min: 0, hr: 0, tot: 0}, - avgLatency: {min: 0, hr: 0, tot: 0}, - rate: {min: 0, hr: 0, tot: 0}, - input: {min: 0, hr: 0, tot: 0}, - output: {min: 0, hr: 0, tot: 0}, - errors: {min: 0, hr: 0, tot: 0} + count: { min: 0, hr: 0, tot: 0 }, + avgLatency: { min: 0, hr: 0, tot: 0 }, + rate: { min: 0, hr: 0, tot: 0 }, + input: { min: 0, hr: 0, tot: 0 }, + output: { min: 0, hr: 0, tot: 0 }, + errors: { min: 0, hr: 0, tot: 0 }, }; } diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/statsz.page-handler.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/statsz.page-handler.ts index 4a02502f5..f0d96a8f7 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/statsz.page-handler.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/statsz.page-handler.ts @@ -14,9 +14,15 @@ * limitations under the License. */ -import {AggregationData, AggregationType, TagKey, TagValue, View} from '@opencensus/core'; -import {StatsParams} from '../../zpages'; -import {templatesDir} from './templates-dir'; +import { + AggregationData, + AggregationType, + TagKey, + TagValue, + View, +} from '@opencensus/core'; +import { StatsParams } from '../../zpages'; +import { templatesDir } from './templates-dir'; const ejs = require('ejs'); import * as path from 'path'; @@ -24,16 +30,16 @@ export interface StatszParams { path: string; } -type FolderType = { - [key: string]: {path: string, isLastFolder: boolean, viewsCount: number} -}; +interface FolderType { + [key: string]: { path: string; isLastFolder: boolean; viewsCount: number }; +} // AggregationData in zPages format -export type ZPagesStatsData = { - tagKeys: TagKey[], - tagValues?: Array, - snapshot?: AggregationData -}; +export interface ZPagesStatsData { + tagKeys: TagKey[]; + tagValues?: Array; + snapshot?: AggregationData; +} /** * Information used to render the Statsz UI. @@ -59,7 +65,7 @@ export class StatszPageHandler { /** CSS styles file */ const stylesFile = this.loaderFile('styles.min.css'); /** EJS render options */ - const options = {delimiter: '?'}; + const options = { delimiter: '?' }; /** current path, empty is root folder */ let path: string[] = []; /** current folder level */ @@ -67,11 +73,11 @@ export class StatszPageHandler { /** keeps the folders that belong to the current folder */ const folders: FolderType = {}; /** selected view to show */ - let selectedView: View|undefined; + let selectedView: View | undefined; /** keeps HTML table content */ let tableContent: string; /** keeps the stats and view data to load UI */ - let statsViewData: StatsViewData|undefined; + let statsViewData: StatsViewData | undefined; // gets the path from user if (params.path) { @@ -120,7 +126,7 @@ export class StatszPageHandler { folders[folderName] = { path: currentViewPath, viewsCount: 1, - isLastFolder + isLastFolder, }; } } @@ -128,7 +134,7 @@ export class StatszPageHandler { if (selectedView) { const statsData = this.getStatsData(selectedView); const viewFile = this.loaderFile('statsz-view.ejs'); - let viewContentFile: string|undefined; + let viewContentFile: string | undefined; let statsContent: string; switch (selectedView.aggregation) { @@ -155,25 +161,30 @@ export class StatszPageHandler { break; } - statsViewData = {view: selectedView, statsData}; + statsViewData = { view: selectedView, statsData }; statsContent = ejs.render(viewContentFile, statsViewData, options); tableContent = ejs.render( - viewFile, {view: selectedView, stats_content: statsContent}, options); + viewFile, + { view: selectedView, stats_content: statsContent }, + options + ); } else { - tableContent = ejs.render(directoriesFile, {folders}, options); + tableContent = ejs.render(directoriesFile, { folders }, options); } if (json) { return JSON.stringify(statsViewData, null, 2); } else { return ejs.render( - statszFile, { - styles: stylesFile, - registeredMeasures: this.statsParams.registeredMeasures, - table_content: tableContent, - path - }, - options); + statszFile, + { + styles: stylesFile, + registeredMeasures: this.statsParams.registeredMeasures, + table_content: tableContent, + path, + }, + options + ); } } @@ -184,13 +195,13 @@ export class StatszPageHandler { private getStatsData(selectedView: View): ZPagesStatsData[] { const recordedData = this.statsParams.recordedData[selectedView.name]; if (!recordedData) { - return [{tagKeys: selectedView.getColumns()}]; + return [{ tagKeys: selectedView.getColumns() }]; } return recordedData.map(snapshot => { return { tagKeys: selectedView.getColumns(), tagValues: snapshot.tagValues, - snapshot + snapshot, }; }); } diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/templates-dir.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/templates-dir.ts index f7bdb4953..e35b74067 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/templates-dir.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/templates-dir.ts @@ -17,7 +17,7 @@ import * as path from 'path'; /** The directory to search for templates. */ -export const templatesDir = function getTemplatesDir() { +export const templatesDir = (function getTemplatesDir() { // When this file is compiled to JS, it will live in the 'build' dir which // is a peer of 'templates'. Tests don't compile, so the relative path is // different. @@ -25,4 +25,4 @@ export const templatesDir = function getTemplatesDir() { return path.join(__dirname, '../../../../templates'); } return path.join(__dirname, '../../../templates'); -}(); +})(); diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/traceconfigz.page-handler.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/traceconfigz.page-handler.ts index 69793219d..755c71753 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/traceconfigz.page-handler.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/traceconfigz.page-handler.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import {SamplerBuilder} from '@opencensus/core'; +import { SamplerBuilder } from '@opencensus/core'; import * as tracing from '@opencensus/nodejs'; import * as ejs from 'ejs'; -import {templatesDir} from './templates-dir'; +import { templatesDir } from './templates-dir'; export interface TraceConfigzParams { change: string; @@ -25,13 +25,13 @@ export interface TraceConfigzParams { } export interface TraceConfigzData { - defaultConfig: {samplingRate: number}; + defaultConfig: { samplingRate: number }; samplingProbability: number; } export class TraceConfigzPageHandler { /** Configuration defaults. Currently just the default sampling rate. */ - private defaultConfig?: {samplingRate: number;}; + private defaultConfig?: { samplingRate: number }; /** * Generate Zpages Trace Config HTML Page @@ -46,23 +46,23 @@ export class TraceConfigzPageHandler { if (!this.defaultConfig) { this.defaultConfig = { - samplingRate: TraceConfigzPageHandler.extractSamplingProbability() + samplingRate: TraceConfigzPageHandler.extractSamplingProbability(), }; } /** template HTML */ - const traceConfigzFile = - ejs.fileLoader(`${templatesDir}/traceconfigz.ejs`).toString(); + const traceConfigzFile = ejs + .fileLoader(`${templatesDir}/traceconfigz.ejs`) + .toString(); /** EJS render options */ - const options = {delimiter: '?'}; + const options = { delimiter: '?' }; /** Current sampling rate */ - const samplingProbability = - TraceConfigzPageHandler.extractSamplingProbability(); + const samplingProbability = TraceConfigzPageHandler.extractSamplingProbability(); /** Rendering the HTML table summary */ const renderParams: TraceConfigzData = { defaultConfig: this.defaultConfig, - samplingProbability + samplingProbability, }; if (json) { return JSON.stringify(renderParams, null, 2); @@ -78,15 +78,17 @@ export class TraceConfigzPageHandler { private saveChanges(query: Partial): void { /** restore the config to default */ if (query.change === 'restore_default') { - tracing.tracer.sampler = - SamplerBuilder.getSampler(this.defaultConfig!.samplingRate); + tracing.tracer.sampler = SamplerBuilder.getSampler( + this.defaultConfig!.samplingRate + ); return; } /** change the sampling probability value */ if (query.samplingprobability) { - tracing.tracer.sampler = - SamplerBuilder.getSampler(query.samplingprobability); + tracing.tracer.sampler = SamplerBuilder.getSampler( + query.samplingprobability + ); } } diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/tracez.page-handler.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/tracez.page-handler.ts index 04e36f02f..e1e7528d2 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/tracez.page-handler.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/page-handlers/tracez.page-handler.ts @@ -14,19 +14,20 @@ * limitations under the License. */ -import {Span} from '@opencensus/core'; +import { Span } from '@opencensus/core'; import * as ejs from 'ejs'; -import {LatencyBucketBoundaries} from '../latency-bucket-boundaries'; -import {templatesDir} from './templates-dir'; +import { LatencyBucketBoundaries } from '../latency-bucket-boundaries'; +import { templatesDir } from './templates-dir'; -export type TracezParams = { - tracename: string; type: string; -}; +export interface TracezParams { + tracename: string; + type: string; +} /** Index to latencies */ -export type Latency = { - [key: string]: number -}; +export interface Latency { + [key: string]: number; +} /** * Information needed to display selected traces. @@ -107,14 +108,14 @@ function serializeSpan(inputSpan: Span): SerializedSpan { traceId: inputSpan.traceId, id: inputSpan.id, parentSpanId: inputSpan.parentSpanId, - spans: [] + spans: [], }; span.spans = inputSpan.spans.map((childSpan: Span) => ({ - startTime: childSpan.startTime, - id: childSpan.id, - name: childSpan.name, - duration: childSpan.duration - })); + startTime: childSpan.startTime, + id: childSpan.id, + name: childSpan.name, + duration: childSpan.duration, + })); return span; } @@ -136,9 +137,9 @@ export class TracezPageHandler { MILLIx100_SECONDx1: 0, SECONDx1_SECONDx10: 0, SECONDx10_SECONDx100: 0, - SECONDx100_MAX: 0 + SECONDx100_MAX: 0, }, - ERRORS: 0 + ERRORS: 0, }; // Building span list @@ -146,11 +147,12 @@ export class TracezPageHandler { if (span.status && span.status.code !== 0) { spanCell.ERRORS += 1; } else if (span.ended) { - const durationNs = - LatencyBucketBoundaries.millisecondsToNanos(span.duration); - const latency = - LatencyBucketBoundaries.getLatencyBucketBoundariesByTime( - durationNs); + const durationNs = LatencyBucketBoundaries.millisecondsToNanos( + span.duration + ); + const latency = LatencyBucketBoundaries.getLatencyBucketBoundariesByTime( + durationNs + ); spanCell.latencies[latency.getName()] += 1; } else if (span.started) { spanCell.RUNNING += 1; @@ -168,15 +170,18 @@ export class TracezPageHandler { */ emitHtml(params: Partial, json: boolean): string { const tracezFile = ejs.fileLoader(`${templatesDir}/tracez.ejs`).toString(); - const stylesFile = - ejs.fileLoader(`${templatesDir}/styles.min.css`).toString(); - const summaryFile = - ejs.fileLoader(`${templatesDir}/summary.ejs`).toString(); - const spanCellFile = - ejs.fileLoader(`${templatesDir}/span-cell.ejs`).toString(); + const stylesFile = ejs + .fileLoader(`${templatesDir}/styles.min.css`) + .toString(); + const summaryFile = ejs + .fileLoader(`${templatesDir}/summary.ejs`) + .toString(); + const spanCellFile = ejs + .fileLoader(`${templatesDir}/span-cell.ejs`) + .toString(); const spansFile = ejs.fileLoader(`${templatesDir}/spans.ejs`).toString(); /** EJS render options */ - const options = {delimiter: '?'}; + const options = { delimiter: '?' }; /** Latency array */ const latencyBucketBoundaries = LatencyBucketBoundaries.values; /** Latency names list */ @@ -186,7 +191,7 @@ export class TracezPageHandler { /** Span cell data. */ const spanCells: SpanCell[] = []; /** Selected traces. Populated only if the `tracename` param exists. */ - let selectedTraces: SelectedTraces|null = null; + let selectedTraces: SelectedTraces | null = null; // Building a string list of latencyBucketBoundaries for (const latency of latencyBucketBoundaries) { @@ -215,11 +220,12 @@ export class TracezPageHandler { traceList.push(span); } } else if (span.ended && span.status.code === 0) { - const durationNs = - LatencyBucketBoundaries.millisecondsToNanos(span.duration); - const latency = - LatencyBucketBoundaries.getLatencyBucketBoundariesByTime( - durationNs); + const durationNs = LatencyBucketBoundaries.millisecondsToNanos( + span.duration + ); + const latency = LatencyBucketBoundaries.getLatencyBucketBoundariesByTime( + durationNs + ); if (latency.getName() === params.type) { traceList.push(span); } @@ -229,33 +235,39 @@ export class TracezPageHandler { selectedTraces = { name: params.tracename, traces: traceList.map(serializeSpan), - getCanonicalCode + getCanonicalCode, }; } /** Rendering the final HTML */ if (json) { - const jsonObj = {selectedTraces, spanCells} as TracezData; + const jsonObj = { selectedTraces, spanCells } as TracezData; return JSON.stringify(jsonObj, null, 2); } else { /** HTML table summary */ - const renderedSummary = - ejs.render(summaryFile, {latencyBucketNames}, options); + const renderedSummary = ejs.render( + summaryFile, + { latencyBucketNames }, + options + ); /** HTML selected trace list */ - const renderedSelectedTraces: string = - selectedTraces ? ejs.render(spansFile, selectedTraces, options) : ''; + const renderedSelectedTraces: string = selectedTraces + ? ejs.render(spansFile, selectedTraces, options) + : ''; /** RootSpan lines */ - const renderedSpanCells: string = - spanCells.map(spanCell => ejs.render(spanCellFile, spanCell, options)) - .join(''); + const renderedSpanCells: string = spanCells + .map(spanCell => ejs.render(spanCellFile, spanCell, options)) + .join(''); return ejs.render( - tracezFile, { - styles: stylesFile, - table_content: renderedSummary + renderedSpanCells, - title: 'TraceZ Summary', - selectedTraces: renderedSelectedTraces - }, - options); + tracezFile, + { + styles: stylesFile, + table_content: renderedSummary + renderedSpanCells, + title: 'TraceZ Summary', + selectedTraces: renderedSelectedTraces, + }, + options + ); } } } diff --git a/packages/opencensus-exporter-zpages/src/zpages-frontend/routes.ts b/packages/opencensus-exporter-zpages/src/zpages-frontend/routes.ts index 26a066cd8..a167b9703 100644 --- a/packages/opencensus-exporter-zpages/src/zpages-frontend/routes.ts +++ b/packages/opencensus-exporter-zpages/src/zpages-frontend/routes.ts @@ -14,13 +14,13 @@ * limitations under the License. */ -import {Span} from '@opencensus/core'; +import { Span } from '@opencensus/core'; import * as express from 'express'; -import {StatsParams} from '../zpages'; -import {createRpczHandler} from './controllers/rpcz.controller'; -import {createStatszHandler} from './controllers/statsz.controller'; -import {createTraceConfigzHandler} from './controllers/traceconfigz.controller'; -import {createTracezHandler} from './controllers/tracez.controller'; +import { StatsParams } from '../zpages'; +import { createRpczHandler } from './controllers/rpcz.controller'; +import { createStatszHandler } from './controllers/statsz.controller'; +import { createTraceConfigzHandler } from './controllers/traceconfigz.controller'; +import { createTracezHandler } from './controllers/tracez.controller'; /** * Create a set of routes that consults the given TraceMap instance for span @@ -30,7 +30,9 @@ import {createTracezHandler} from './controllers/tracez.controller'; * and recorded data from stats */ export function createRoutes( - traceMap: Map, statsParams: StatsParams): express.Router { + traceMap: Map, + statsParams: StatsParams +): express.Router { const router = express.Router(); // Tracez Page diff --git a/packages/opencensus-exporter-zpages/src/zpages.ts b/packages/opencensus-exporter-zpages/src/zpages.ts index 127e742a6..2c6b3dc94 100644 --- a/packages/opencensus-exporter-zpages/src/zpages.ts +++ b/packages/opencensus-exporter-zpages/src/zpages.ts @@ -14,11 +14,22 @@ * limitations under the License. */ -import {AggregationData, Exporter, ExporterConfig, Measure, Measurement, Span, StatsEventListener, TagKey, TagValue, View} from '@opencensus/core'; -import {logger, Logger} from '@opencensus/core'; +import { + AggregationData, + Exporter, + ExporterConfig, + Measure, + Measurement, + Span, + StatsEventListener, + TagKey, + TagValue, + View, +} from '@opencensus/core'; +import { logger, Logger } from '@opencensus/core'; import * as express from 'express'; import * as http from 'http'; -import {createRoutes} from './zpages-frontend/routes'; +import { createRoutes } from './zpages-frontend/routes'; /** Interface to Zpages options */ export interface ZpagesExporterOptions extends ExporterConfig { @@ -33,13 +44,13 @@ export interface ZpagesExporterOptions extends ExporterConfig { export interface StatsParams { registeredViews: View[]; registeredMeasures: Measure[]; - recordedData: {[key: string]: AggregationData[]}; + recordedData: { [key: string]: AggregationData[] }; } /** Class to ZpagesExporter */ export class ZpagesExporter implements Exporter, StatsEventListener { /** ZpagesExporter default options */ - static readonly defaultOptions = {port: 8080, startServer: true}; + static readonly defaultOptions = { port: 8080, startServer: true }; private app: express.Application; private server?: http.Server; @@ -49,7 +60,7 @@ export class ZpagesExporter implements Exporter, StatsEventListener { private statsParams: StatsParams = { registeredViews: [], registeredMeasures: [], - recordedData: {} + recordedData: {}, }; constructor(options: ZpagesExporterOptions) { @@ -57,9 +68,10 @@ export class ZpagesExporter implements Exporter, StatsEventListener { this.app = express(); this.port = options.port || ZpagesExporter.defaultOptions.port; this.logger = options.logger || logger.logger(); - const startServer = options.startServer != null ? - options.startServer : - ZpagesExporter.defaultOptions.startServer; + const startServer = + options.startServer != null + ? options.startServer + : ZpagesExporter.defaultOptions.startServer; /** register predefined span names, if any */ if (options.spanNames) { @@ -101,8 +113,11 @@ export class ZpagesExporter implements Exporter, StatsEventListener { this.statsParams.registeredViews.push(view); } // Adds the measure to registeredMeasures array if it doesn't contain yet - if (!this.statsParams.registeredMeasures.find( - m => m.name === view.measure.name)) { + if ( + !this.statsParams.registeredMeasures.find( + m => m.name === view.measure.name + ) + ) { this.statsParams.registeredMeasures.push(view.measure); } } @@ -114,16 +129,19 @@ export class ZpagesExporter implements Exporter, StatsEventListener { * @param tags The tags to which the value is applied */ onRecord( - views: View[], measurement: Measurement, - tags: Map): void { + views: View[], + measurement: Measurement, + tags: Map + ): void { const tagValues = [...tags.values()]; views.map(view => { const snapshot = view.getSnapshot(tagValues); // Check if there is no data for the current view if (!this.statsParams.recordedData[view.name]) { this.statsParams.recordedData[view.name] = [snapshot]; - } else if (!this.statsParams.recordedData[view.name].find( - s => s === snapshot)) { + } else if ( + !this.statsParams.recordedData[view.name].find(s => s === snapshot) + ) { // Push the snapshot if it hasn't recoreded before this.statsParams.recordedData[view.name].push(snapshot); } @@ -176,7 +194,7 @@ export class ZpagesExporter implements Exporter, StatsEventListener { */ private registerSpanNames(spanNames: string[]) { for (const name of spanNames) { - const span = {name} as Span; + const span = { name } as Span; this.traces.set(name, [span]); } } diff --git a/packages/opencensus-exporter-zpages/test/test-zpages.ts b/packages/opencensus-exporter-zpages/test/test-zpages.ts index f2d561ef5..9cccd1524 100644 --- a/packages/opencensus-exporter-zpages/test/test-zpages.ts +++ b/packages/opencensus-exporter-zpages/test/test-zpages.ts @@ -14,22 +14,44 @@ * limitations under the License. */ -import {AggregationType, CountData, DistributionData, globalStats, Measure, Measurement, MeasureUnit, Span, SpanKind, SumData, TagMap, TracerConfig} from '@opencensus/core'; +import { + AggregationType, + CountData, + DistributionData, + globalStats, + Measure, + Measurement, + MeasureUnit, + Span, + SpanKind, + SumData, + TagMap, + TracerConfig, +} from '@opencensus/core'; import * as assert from 'assert'; import axios from 'axios'; import * as http from 'http'; import * as qs from 'querystring'; -import {ZpagesExporter, ZpagesExporterOptions} from '../src/zpages'; -import {RpczData} from '../src/zpages-frontend/page-handlers/rpcz.page-handler'; -import {StatsViewData, StatszParams} from '../src/zpages-frontend/page-handlers/statsz.page-handler'; -import {TraceConfigzData, TraceConfigzParams} from '../src/zpages-frontend/page-handlers/traceconfigz.page-handler'; -import {TracezData, TracezParams} from '../src/zpages-frontend/page-handlers/tracez.page-handler'; +import { ZpagesExporter, ZpagesExporterOptions } from '../src/zpages'; +import { RpczData } from '../src/zpages-frontend/page-handlers/rpcz.page-handler'; +import { + StatsViewData, + StatszParams, +} from '../src/zpages-frontend/page-handlers/statsz.page-handler'; +import { + TraceConfigzData, + TraceConfigzParams, +} from '../src/zpages-frontend/page-handlers/traceconfigz.page-handler'; +import { + TracezData, + TracezParams, +} from '../src/zpages-frontend/page-handlers/tracez.page-handler'; /** Default options for zpages tests */ const options: ZpagesExporterOptions = { port: 8081, spanNames: ['predefined/span1', 'predefined/span2'], - startServer: false + startServer: false, }; /** Zpages Server URL, just to support tests, shouldn't be changed */ @@ -37,7 +59,7 @@ const zpagesServerUrl = 'http://localhost:' + options.port; /** Default config for traces tests */ const defaultConfig: TracerConfig = { - samplingRate: 1.0 + samplingRate: 1.0, }; /** @@ -48,11 +70,14 @@ const defaultConfig: TracerConfig = { class ZpagesJSONClient { constructor(private readonly origin: string) {} - private async getEndpoint(endpoint: string, query?: Partial

): - Promise { - query = Object.assign({json: '1'}, query); - const response = - await axios.get(`${this.origin}/${endpoint}?${qs.stringify(query)}`); + private async getEndpoint( + endpoint: string, + query?: Partial

+ ): Promise { + query = Object.assign({ json: '1' }, query); + const response = await axios.get( + `${this.origin}/${endpoint}?${qs.stringify(query)}` + ); return response.data as R; } @@ -68,10 +93,13 @@ class ZpagesJSONClient { * Gets the data model backing the traceconfigz UI. * @param query Optional query parameters. */ - async getTraceConfigz(query?: Partial): - Promise { + async getTraceConfigz( + query?: Partial + ): Promise { return this.getEndpoint( - 'tracez', query); + 'tracez', + query + ); } /** @@ -99,12 +127,12 @@ describe('Zpages Exporter', () => { describe('new ZpagesExporter()', () => { let zpages: ZpagesExporter; - before((done) => { + before(done => { zpages = new ZpagesExporter(options); zpages.startServer(done); }); - after((done) => { + after(done => { zpages.stopServer(done); }); @@ -123,7 +151,7 @@ describe('Zpages Exporter', () => { describe('when a span is started and ended', () => { let zpages: ZpagesExporter; - before((done) => { + before(done => { /** Creating here because tracing is a singleton */ const tracing = require('@opencensus/nodejs'); zpages = new ZpagesExporter(options); @@ -131,16 +159,21 @@ describe('Zpages Exporter', () => { tracing.start(defaultConfig); tracing.registerExporter(zpages); - tracing.tracer.startRootSpan({name: 'rootSpanTest'}, (rootSpan: Span) => { - const span = tracing.tracer.startChildSpan( - {name: 'spanNameTest', kind: SpanKind.CLIENT}); - span.end(); - rootSpan.end(); - }); + tracing.tracer.startRootSpan( + { name: 'rootSpanTest' }, + (rootSpan: Span) => { + const span = tracing.tracer.startChildSpan({ + name: 'spanNameTest', + kind: SpanKind.CLIENT, + }); + span.end(); + rootSpan.end(); + } + ); zpages.startServer(done); }); - after((done) => { + after(done => { zpages.stopServer(done); }); @@ -149,21 +182,23 @@ describe('Zpages Exporter', () => { const zpagesData = await zpagesClient.getTracez(); // Check that exactly one cell was created for the root span. assert.strictEqual( - zpagesData.spanCells.filter(cell => cell.name === 'rootSpanTest') - .length, - 1); + zpagesData.spanCells.filter(cell => cell.name === 'rootSpanTest') + .length, + 1 + ); // Check that exactly one cell was created for the child span. assert.strictEqual( - zpagesData.spanCells.filter(cell => cell.name === 'spanNameTest') - .length, - 1); + zpagesData.spanCells.filter(cell => cell.name === 'spanNameTest') + .length, + 1 + ); }); }); describe('when a span is started, but not ended', () => { let zpages: ZpagesExporter; - before((done) => { + before(done => { /** Creating here because tracing is a singleton */ const tracing = require('@opencensus/nodejs'); zpages = new ZpagesExporter(options); @@ -171,19 +206,21 @@ describe('Zpages Exporter', () => { tracing.start(defaultConfig); tracing.registerExporter(zpages); - tracing.tracer.startRootSpan({name: 'runningSpanTest'}, () => {}); + tracing.tracer.startRootSpan({ name: 'runningSpanTest' }, () => {}); zpages.startServer(done); }); - after((done) => { + after(done => { zpages.stopServer(done); }); it('should appear in the RUNNING category in the tracez UI', async () => { // Get the data backing the current tracez UI for the currently running // span. - const zpagesData = await zpagesClient.getTracez( - {tracename: 'runningSpanTest', type: 'RUNNING'}); + const zpagesData = await zpagesClient.getTracez({ + tracename: 'runningSpanTest', + type: 'RUNNING', + }); // selectedTraces should be populated. assert.ok(zpagesData.selectedTraces); // Its name should be that of the currently running span. @@ -195,37 +232,45 @@ describe('Zpages Exporter', () => { let zpages: ZpagesExporter; /** Starting the server */ - before((done) => { + before(done => { zpages = new ZpagesExporter(options); zpages.startServer(done); }); - it('should access tracez page', (done) => { - http.get(zpagesServerUrl + '/tracez', (res) => { - assert.strictEqual(res.statusCode, 200); - done(); - }).on('error', done); + it('should access tracez page', done => { + http + .get(zpagesServerUrl + '/tracez', res => { + assert.strictEqual(res.statusCode, 200); + done(); + }) + .on('error', done); }); - it('should access trace config page', (done) => { - http.get(zpagesServerUrl + '/traceconfigz', (res) => { - assert.strictEqual(res.statusCode, 200); - done(); - }).on('error', done); + it('should access trace config page', done => { + http + .get(zpagesServerUrl + '/traceconfigz', res => { + assert.strictEqual(res.statusCode, 200); + done(); + }) + .on('error', done); }); - it('should access statsz page', (done) => { - http.get(zpagesServerUrl + '/statsz', (res) => { - assert.strictEqual(res.statusCode, 200); - done(); - }).on('error', done); + it('should access statsz page', done => { + http + .get(zpagesServerUrl + '/statsz', res => { + assert.strictEqual(res.statusCode, 200); + done(); + }) + .on('error', done); }); - it('should access rpcz page', (done) => { - http.get(zpagesServerUrl + '/rpcz', (res) => { - assert.strictEqual(res.statusCode, 200); - done(); - }).on('error', done); + it('should access rpcz page', done => { + http + .get(zpagesServerUrl + '/rpcz', res => { + assert.strictEqual(res.statusCode, 200); + done(); + }) + .on('error', done); }); after(() => { @@ -235,8 +280,8 @@ describe('Zpages Exporter', () => { // STATS TESTS describe('when a view is accessed in statsz page', () => { - const tagKeys = [{name: 'testKey1'}, {name: 'testKey2'}]; - const tagValues = [{value: 'testValue1'}, {value: 'testValue2'}]; + const tagKeys = [{ name: 'testKey1' }, { name: 'testKey2' }]; + const tagValues = [{ value: 'testValue1' }, { value: 'testValue2' }]; const tagMap = new TagMap(); tagMap.set(tagKeys[0], tagValues[0]); tagMap.set(tagKeys[1], tagValues[1]); @@ -247,17 +292,20 @@ describe('Zpages Exporter', () => { let measurement: Measurement; let measurement2: Measurement; - beforeEach((done) => { + beforeEach(done => { zpages = new ZpagesExporter(options); globalStats.registerExporter(zpages); measure = globalStats.createMeasureDouble( - 'testMeasureDouble', MeasureUnit.UNIT, 'A test measure'); - measurement = {measure, value: 22}; - measurement2 = {measure, value: 11}; + 'testMeasureDouble', + MeasureUnit.UNIT, + 'A test measure' + ); + measurement = { measure, value: 22 }; + measurement2 = { measure, value: 11 }; zpages.startServer(done); }); - afterEach((done) => { + afterEach(done => { zpages.stopServer(done); globalStats.clear(); }); @@ -265,12 +313,16 @@ describe('Zpages Exporter', () => { describe('with COUNT aggregation type', () => { it('should get view information', async () => { const view = globalStats.createView( - 'test/CountView', measure, AggregationType.COUNT, tagKeys, - 'A count test'); + 'test/CountView', + measure, + AggregationType.COUNT, + tagKeys, + 'A count test' + ); globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - zpagesData = await zpagesClient.getStatsz({path: 'test/CountView'}); + zpagesData = await zpagesClient.getStatsz({ path: 'test/CountView' }); assert.strictEqual(zpagesData.view.name, 'test/CountView'); assert.strictEqual(zpagesData.view.description, 'A count test'); @@ -280,12 +332,16 @@ describe('Zpages Exporter', () => { it('should get stats for view', async () => { const view = globalStats.createView( - 'test/CountView', measure, AggregationType.COUNT, tagKeys, - 'A count test'); + 'test/CountView', + measure, + AggregationType.COUNT, + tagKeys, + 'A count test' + ); globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - zpagesData = await zpagesClient.getStatsz({path: 'test/CountView'}); + zpagesData = await zpagesClient.getStatsz({ path: 'test/CountView' }); const data = zpagesData.statsData[0]; const snapshot = data.snapshot as CountData; @@ -299,12 +355,16 @@ describe('Zpages Exporter', () => { it('should get view information', async () => { globalStats.registerExporter(zpages); const view = globalStats.createView( - 'test/SumView', measure, AggregationType.SUM, tagKeys, - 'A sum test'); + 'test/SumView', + measure, + AggregationType.SUM, + tagKeys, + 'A sum test' + ); globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - zpagesData = await zpagesClient.getStatsz({path: 'test/SumView'}); + zpagesData = await zpagesClient.getStatsz({ path: 'test/SumView' }); assert.strictEqual(zpagesData.view.name, 'test/SumView'); assert.strictEqual(zpagesData.view.description, 'A sum test'); @@ -315,12 +375,16 @@ describe('Zpages Exporter', () => { it('should get stats for view', async () => { globalStats.registerExporter(zpages); const view = globalStats.createView( - 'test/SumView', measure, AggregationType.SUM, tagKeys, - 'A sum test'); + 'test/SumView', + measure, + AggregationType.SUM, + tagKeys, + 'A sum test' + ); globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - zpagesData = await zpagesClient.getStatsz({path: 'test/SumView'}); + zpagesData = await zpagesClient.getStatsz({ path: 'test/SumView' }); const data = zpagesData.statsData[0]; const snapshot = data.snapshot as SumData; @@ -334,29 +398,43 @@ describe('Zpages Exporter', () => { it('should get view information', async () => { globalStats.registerExporter(zpages); const view = globalStats.createView( - 'test/LastValueView', measure, AggregationType.LAST_VALUE, tagKeys, - 'A last value test'); + 'test/LastValueView', + measure, + AggregationType.LAST_VALUE, + tagKeys, + 'A last value test' + ); globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - zpagesData = await zpagesClient.getStatsz({path: 'test/LastValueView'}); + zpagesData = await zpagesClient.getStatsz({ + path: 'test/LastValueView', + }); assert.strictEqual(zpagesData.view.name, 'test/LastValueView'); assert.strictEqual(zpagesData.view.description, 'A last value test'); assert.strictEqual(zpagesData.view.measure.name, 'testMeasureDouble'); assert.strictEqual( - zpagesData.view.aggregation, AggregationType.LAST_VALUE); + zpagesData.view.aggregation, + AggregationType.LAST_VALUE + ); }); it('should get stats for view', async () => { globalStats.registerExporter(zpages); const view = globalStats.createView( - 'test/LastValueView', measure, AggregationType.LAST_VALUE, tagKeys, - 'A last value test'); + 'test/LastValueView', + measure, + AggregationType.LAST_VALUE, + tagKeys, + 'A last value test' + ); globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - zpagesData = await zpagesClient.getStatsz({path: 'test/LastValueView'}); + zpagesData = await zpagesClient.getStatsz({ + path: 'test/LastValueView', + }); const data = zpagesData.statsData[0]; const snapshot = data.snapshot as SumData; @@ -371,32 +449,46 @@ describe('Zpages Exporter', () => { const boundaries = [10, 20, 30, 40]; globalStats.registerExporter(zpages); const view = globalStats.createView( - 'test/DistributionView', measure, AggregationType.DISTRIBUTION, - tagKeys, 'A distribution test', boundaries); + 'test/DistributionView', + measure, + AggregationType.DISTRIBUTION, + tagKeys, + 'A distribution test', + boundaries + ); globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - zpagesData = - await zpagesClient.getStatsz({path: 'test/DistributionView'}); + zpagesData = await zpagesClient.getStatsz({ + path: 'test/DistributionView', + }); assert.strictEqual(zpagesData.view.name, 'test/DistributionView'); assert.strictEqual(zpagesData.view.description, 'A distribution test'); assert.strictEqual(zpagesData.view.measure.name, 'testMeasureDouble'); assert.strictEqual( - zpagesData.view.aggregation, AggregationType.DISTRIBUTION); + zpagesData.view.aggregation, + AggregationType.DISTRIBUTION + ); }); it('should get stats for view', async () => { const boundaries = [10, 20, 30, 40]; globalStats.registerExporter(zpages); const view = globalStats.createView( - 'test/DistributionView', measure, AggregationType.DISTRIBUTION, - tagKeys, 'A distribution test', boundaries); + 'test/DistributionView', + measure, + AggregationType.DISTRIBUTION, + tagKeys, + 'A distribution test', + boundaries + ); globalStats.registerView(view); globalStats.record([measurement, measurement2], tagMap); - zpagesData = - await zpagesClient.getStatsz({path: 'test/DistributionView'}); + zpagesData = await zpagesClient.getStatsz({ + path: 'test/DistributionView', + }); const data = zpagesData.statsData[0]; const snapshot = data.snapshot as DistributionData; @@ -414,84 +506,108 @@ describe('Zpages Exporter', () => { let rpczData: RpczData; const boundaries = [10, 20, 30, 40]; - beforeEach((done) => { + beforeEach(done => { zpages = new ZpagesExporter(options); globalStats.registerExporter(zpages); zpages.startServer(done); }); - afterEach((done) => { + afterEach(done => { zpages.stopServer(done); globalStats.clear(); }); it('should get the sent stats', async () => { - const GRPC_CLIENT_METHOD = {name: 'grpc_client_method'}; - const GRPC_CLIENT_STATUS = {name: 'grpc_client_status'}; - const GRPC_CLIENT_METHOD_V = {value: 'ExampleMethod'}; - const GRPC_CLIENT_STATUS_V = {value: 'DEADLINE_EXCEEDED'}; + const GRPC_CLIENT_METHOD = { name: 'grpc_client_method' }; + const GRPC_CLIENT_STATUS = { name: 'grpc_client_status' }; + const GRPC_CLIENT_METHOD_V = { value: 'ExampleMethod' }; + const GRPC_CLIENT_STATUS_V = { value: 'DEADLINE_EXCEEDED' }; const tagMap = new TagMap(); tagMap.set(GRPC_CLIENT_METHOD, GRPC_CLIENT_METHOD_V); tagMap.set(GRPC_CLIENT_STATUS, GRPC_CLIENT_STATUS_V); const measure = globalStats.createMeasureDouble( - 'grpc.io/client/sent_bytes_per_rpc', MeasureUnit.BYTE, - 'Total bytes sent across all request messages per RPC'); + 'grpc.io/client/sent_bytes_per_rpc', + MeasureUnit.BYTE, + 'Total bytes sent across all request messages per RPC' + ); const measure2 = globalStats.createMeasureDouble( - 'grpc.io/client/received_bytes_per_rpc', MeasureUnit.BYTE, - 'Total bytes received across all request messages per RPC'); + 'grpc.io/client/received_bytes_per_rpc', + MeasureUnit.BYTE, + 'Total bytes received across all request messages per RPC' + ); const measure3 = globalStats.createMeasureDouble( - 'grpc.io/client/roundtrip_latency', MeasureUnit.MS, - 'Time between first byte of request sent to last byte of response received or terminal error'); + 'grpc.io/client/roundtrip_latency', + MeasureUnit.MS, + 'Time between first byte of request sent to last byte of response received or terminal error' + ); const measure4 = globalStats.createMeasureDouble( - 'grpc.io/client/started_rpcs', MeasureUnit.UNIT, - 'Number of started client RPCs.'); + 'grpc.io/client/started_rpcs', + MeasureUnit.UNIT, + 'Number of started client RPCs.' + ); const view1 = globalStats.createView( - 'grpc.io/client/sent_bytes_per_rpc', measure, - AggregationType.DISTRIBUTION, - [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], 'Sent bytes per RPC', - boundaries); + 'grpc.io/client/sent_bytes_per_rpc', + measure, + AggregationType.DISTRIBUTION, + [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], + 'Sent bytes per RPC', + boundaries + ); globalStats.registerView(view1); const view2 = globalStats.createView( - 'grpc.io/client/received_bytes_per_rpc', measure2, - AggregationType.DISTRIBUTION, - [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], 'Sent bytes per RPC', - boundaries); + 'grpc.io/client/received_bytes_per_rpc', + measure2, + AggregationType.DISTRIBUTION, + [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], + 'Sent bytes per RPC', + boundaries + ); globalStats.registerView(view2); const view3 = globalStats.createView( - 'grpc.io/client/roundtrip_latency', measure3, - AggregationType.DISTRIBUTION, - [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], 'Latency in msecs', - boundaries); + 'grpc.io/client/roundtrip_latency', + measure3, + AggregationType.DISTRIBUTION, + [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], + 'Latency in msecs', + boundaries + ); globalStats.registerView(view3); const view4 = globalStats.createView( - 'grpc.io/client/completed_rpcs', measure3, AggregationType.COUNT, - [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], - 'Number of completed client RPCs'); + 'grpc.io/client/completed_rpcs', + measure3, + AggregationType.COUNT, + [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], + 'Number of completed client RPCs' + ); globalStats.registerView(view4); const view5 = globalStats.createView( - 'grpc.io/client/started_rpcs', measure4, AggregationType.COUNT, - [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], - 'Number of started client RPCs'); + 'grpc.io/client/started_rpcs', + measure4, + AggregationType.COUNT, + [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], + 'Number of started client RPCs' + ); globalStats.registerView(view5); - const measurement = {measure, value: 22000}; - const measurement2 = {measure: measure2, value: 1100}; - const measurement3 = {measure: measure3, value: 1}; - const measurement4 = {measure: measure3, value: 2}; - const measurement5 = {measure: measure4, value: 2}; + const measurement = { measure, value: 22000 }; + const measurement2 = { measure: measure2, value: 1100 }; + const measurement3 = { measure: measure3, value: 1 }; + const measurement4 = { measure: measure3, value: 2 }; + const measurement5 = { measure: measure4, value: 2 }; globalStats.record( - [measurement, measurement2, measurement3, measurement4, measurement5], - tagMap); + [measurement, measurement2, measurement3, measurement4, measurement5], + tagMap + ); rpczData = await zpagesClient.getRpcz(); const measures = rpczData.measuresSent['ExampleMethod']; @@ -503,76 +619,97 @@ describe('Zpages Exporter', () => { }); it('should get the received stats', async () => { - const GRPC_SERVER_METHOD = {name: 'grpc_server_method'}; - const GRPC_SERVER_STATUS = {name: 'grpc_server_status'}; - const GRPC_SERVER_METHOD_V = {value: 'ExampleMethod'}; - const GRPC_SERVER_STATUS_V = {value: 'DEADLINE_EXCEEDED'}; + const GRPC_SERVER_METHOD = { name: 'grpc_server_method' }; + const GRPC_SERVER_STATUS = { name: 'grpc_server_status' }; + const GRPC_SERVER_METHOD_V = { value: 'ExampleMethod' }; + const GRPC_SERVER_STATUS_V = { value: 'DEADLINE_EXCEEDED' }; const tagMap = new TagMap(); tagMap.set(GRPC_SERVER_METHOD, GRPC_SERVER_METHOD_V); tagMap.set(GRPC_SERVER_STATUS, GRPC_SERVER_STATUS_V); const boundaries = [10, 20, 30, 40]; const measure5 = globalStats.createMeasureDouble( - 'grpc.io/server/received_bytes_per_rpc', MeasureUnit.BYTE, - 'Total bytes sent across all request messages per RPC'); + 'grpc.io/server/received_bytes_per_rpc', + MeasureUnit.BYTE, + 'Total bytes sent across all request messages per RPC' + ); const measure6 = globalStats.createMeasureDouble( - 'grpc.io/server/sent_bytes_per_rpc', MeasureUnit.BYTE, - 'Total bytes received across all request messages per RPC'); + 'grpc.io/server/sent_bytes_per_rpc', + MeasureUnit.BYTE, + 'Total bytes received across all request messages per RPC' + ); const measure7 = globalStats.createMeasureDouble( - 'grpc.io/server/server_latency', MeasureUnit.MS, - 'Time between first byte of request sent to last byte of response received or terminal error'); + 'grpc.io/server/server_latency', + MeasureUnit.MS, + 'Time between first byte of request sent to last byte of response received or terminal error' + ); const measure8 = globalStats.createMeasureDouble( - 'grpc.io/server/started_rpcs', MeasureUnit.UNIT, - 'Number of started client RPCs.'); + 'grpc.io/server/started_rpcs', + MeasureUnit.UNIT, + 'Number of started client RPCs.' + ); const view1 = globalStats.createView( - 'grpc.io/server/received_bytes_per_rpc', measure5, - AggregationType.DISTRIBUTION, - [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], 'Sent bytes per RPC', - boundaries); + 'grpc.io/server/received_bytes_per_rpc', + measure5, + AggregationType.DISTRIBUTION, + [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], + 'Sent bytes per RPC', + boundaries + ); globalStats.registerView(view1); const view2 = globalStats.createView( - 'grpc.io/server/sent_bytes_per_rpc', measure6, - AggregationType.DISTRIBUTION, - [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], 'Sent bytes per RPC', - boundaries); + 'grpc.io/server/sent_bytes_per_rpc', + measure6, + AggregationType.DISTRIBUTION, + [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], + 'Sent bytes per RPC', + boundaries + ); globalStats.registerView(view2); const view3 = globalStats.createView( - 'grpc.io/server/server_latency', measure7, - AggregationType.DISTRIBUTION, - [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], 'Latency in msecs', - boundaries); + 'grpc.io/server/server_latency', + measure7, + AggregationType.DISTRIBUTION, + [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], + 'Latency in msecs', + boundaries + ); globalStats.registerView(view3); const view4 = globalStats.createView( - 'grpc.io/server/completed_rpcs', measure7, AggregationType.COUNT, - [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], - 'Number of completed client RPCs'); + 'grpc.io/server/completed_rpcs', + measure7, + AggregationType.COUNT, + [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], + 'Number of completed client RPCs' + ); globalStats.registerView(view4); const view5 = globalStats.createView( - 'grpc.io/server/started_rpcs', measure8, AggregationType.COUNT, - [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], - 'Number of started client RPCs'); + 'grpc.io/server/started_rpcs', + measure8, + AggregationType.COUNT, + [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], + 'Number of started client RPCs' + ); globalStats.registerView(view5); - const measurement6 = {measure: measure5, value: 2200}; - const measurement7 = {measure: measure6, value: 1100}; - const measurement8 = {measure: measure7, value: 1}; - const measurement9 = {measure: measure7, value: 2}; - const measurement10 = {measure: measure8, value: 2}; + const measurement6 = { measure: measure5, value: 2200 }; + const measurement7 = { measure: measure6, value: 1100 }; + const measurement8 = { measure: measure7, value: 1 }; + const measurement9 = { measure: measure7, value: 2 }; + const measurement10 = { measure: measure8, value: 2 }; globalStats.record( - [ - measurement6, measurement7, measurement8, measurement9, - measurement10 - ], - tagMap); + [measurement6, measurement7, measurement8, measurement9, measurement10], + tagMap + ); rpczData = await zpagesClient.getRpcz(); const measures = rpczData.measuresReceived['ExampleMethod']; diff --git a/packages/opencensus-instrumentation-grpc/package-lock.json b/packages/opencensus-instrumentation-grpc/package-lock.json index 4bacc9f57..1be2e7522 100644 --- a/packages/opencensus-instrumentation-grpc/package-lock.json +++ b/packages/opencensus-instrumentation-grpc/package-lock.json @@ -259,9 +259,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "2.1.1", @@ -326,45 +326,6 @@ "optjs": "~3.2.2" } }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -563,16 +524,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -650,8 +601,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -1500,37 +1450,37 @@ } }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -1561,14 +1511,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1662,22 +1604,22 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { @@ -1686,6 +1628,16 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, "is-fullwidth-code-point": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", @@ -1711,19 +1663,27 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } } } }, @@ -1953,15 +1913,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -3040,6 +2995,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "protobufjs": { "version": "6.8.8", "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.8.8.tgz", @@ -3133,9 +3093,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -3168,11 +3128,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -3206,9 +3166,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -3574,29 +3534,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -3762,9 +3716,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-instrumentation-grpc/package.json b/packages/opencensus-instrumentation-grpc/package.json index 25d6fce22..739d8650a 100644 --- a/packages/opencensus-instrumentation-grpc/package.json +++ b/packages/opencensus-instrumentation-grpc/package.json @@ -55,7 +55,7 @@ "@types/node": "^10.12.12", "@types/shimmer": "^1.0.1", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "^14.0.0", "protobufjs": "^6.8.8", diff --git a/packages/opencensus-instrumentation-grpc/src/grpc-stats/client-stats.ts b/packages/opencensus-instrumentation-grpc/src/grpc-stats/client-stats.ts index 159c5adb0..a847c64e5 100644 --- a/packages/opencensus-instrumentation-grpc/src/grpc-stats/client-stats.ts +++ b/packages/opencensus-instrumentation-grpc/src/grpc-stats/client-stats.ts @@ -14,46 +14,64 @@ * limitations under the License. */ -import {AggregationType, globalStats, Measure, MeasureUnit, View} from '@opencensus/core'; -import {DEFAULT_BYTES_DISTRIBUTION, DEFAULT_MESSAGE_COUNT_DISTRIBUTION, DEFAULT_MILLI_SECONDS_DISTRIBUTION} from './common-distributions'; +import { + AggregationType, + globalStats, + Measure, + MeasureUnit, + View, +} from '@opencensus/core'; +import { + DEFAULT_BYTES_DISTRIBUTION, + DEFAULT_MESSAGE_COUNT_DISTRIBUTION, + DEFAULT_MILLI_SECONDS_DISTRIBUTION, +} from './common-distributions'; /** {@link Measure} for number of messages sent in the RPC. */ -export const GRPC_CLIENT_SENT_MESSAGES_PER_RPC: Measure = - globalStats.createMeasureInt64( - 'grpc.io/client/sent_messages_per_rpc', MeasureUnit.UNIT, - 'Number of messages sent in the RPC (always 1 for non-streaming RPCs).'); +export const GRPC_CLIENT_SENT_MESSAGES_PER_RPC: Measure = globalStats.createMeasureInt64( + 'grpc.io/client/sent_messages_per_rpc', + MeasureUnit.UNIT, + 'Number of messages sent in the RPC (always 1 for non-streaming RPCs).' +); /** * {@link Measure} for total bytes sent across all request messages per RPC. */ -export const GRPC_CLIENT_SENT_BYTES_PER_RPC: Measure = - globalStats.createMeasureInt64( - 'grpc.io/client/sent_bytes_per_rpc', MeasureUnit.BYTE, - 'Total bytes sent across all request messages per RPC.'); +export const GRPC_CLIENT_SENT_BYTES_PER_RPC: Measure = globalStats.createMeasureInt64( + 'grpc.io/client/sent_bytes_per_rpc', + MeasureUnit.BYTE, + 'Total bytes sent across all request messages per RPC.' +); /** {@link Measure} for number of response messages received per RPC. */ -export const GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC: Measure = - globalStats.createMeasureInt64( - 'grpc.io/client/received_messages_per_rpc', MeasureUnit.UNIT, - 'Number of response messages received per RPC (always 1 for non-streaming RPCs).'); +export const GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC: Measure = globalStats.createMeasureInt64( + 'grpc.io/client/received_messages_per_rpc', + MeasureUnit.UNIT, + 'Number of response messages received per RPC (always 1 for non-streaming RPCs).' +); /** * {@link Measure} for total bytes received across all response messages per RPC */ -export const GRPC_CLIENT_RECEIVED_BYTES_PER_RPC: Measure = - globalStats.createMeasureInt64( - 'grpc.io/client/received_bytes_per_rpc', MeasureUnit.BYTE, - 'Total bytes received across all response messages per RPC.'); +export const GRPC_CLIENT_RECEIVED_BYTES_PER_RPC: Measure = globalStats.createMeasureInt64( + 'grpc.io/client/received_bytes_per_rpc', + MeasureUnit.BYTE, + 'Total bytes received across all response messages per RPC.' +); /** {@link Measure} for gRPC client roundtrip latency in milliseconds. */ export const GRPC_CLIENT_ROUNDTRIP_LATENCY: Measure = globalStats.createMeasureDouble( - 'grpc.io/client/roundtrip_latency', MeasureUnit.MS, - 'Time between first byte of request sent to last byte of response received, or terminal error.'); + 'grpc.io/client/roundtrip_latency', + MeasureUnit.MS, + 'Time between first byte of request sent to last byte of response received, or terminal error.' +); /** {@link Measure} for gRPC server latency in milliseconds. */ export const GRPC_CLIENT_SERVER_LATENCY: Measure = globalStats.createMeasureDouble( - 'grpc.io/client/server_latency', MeasureUnit.MS, - 'Propagated from the server and should have the same value as "grpc.io/server/latency'); + 'grpc.io/client/server_latency', + MeasureUnit.MS, + 'Propagated from the server and should have the same value as "grpc.io/server/latency' +); /** * Tag key that represents a client gRPC method. @@ -62,7 +80,7 @@ export const GRPC_CLIENT_SERVER_LATENCY: Measure = globalStats.createMeasureDoub * available in all the recorded metrics. */ export const GRPC_CLIENT_METHOD = { - name: 'grpc_client_method' + name: 'grpc_client_method', }; /** @@ -73,44 +91,58 @@ export const GRPC_CLIENT_METHOD = { * is only available around metrics recorded at the end of the outgoing request. */ export const GRPC_CLIENT_STATUS = { - name: 'grpc_client_status' + name: 'grpc_client_status', }; /** {@link View} for client received messages per RPC. */ const GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC_VIEW = globalStats.createView( - 'grpc.io/client/received_messages_per_rpc', - GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC, AggregationType.DISTRIBUTION, - [GRPC_CLIENT_METHOD], - 'Distribution of received messages count per RPC, by method.', - DEFAULT_MESSAGE_COUNT_DISTRIBUTION); + 'grpc.io/client/received_messages_per_rpc', + GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC, + AggregationType.DISTRIBUTION, + [GRPC_CLIENT_METHOD], + 'Distribution of received messages count per RPC, by method.', + DEFAULT_MESSAGE_COUNT_DISTRIBUTION +); /** {@link View} for client received bytes per RPC. */ const GRPC_CLIENT_RECEIVED_BYTES_PER_RPC_VIEW = globalStats.createView( - 'grpc.io/client/received_bytes_per_rpc', GRPC_CLIENT_RECEIVED_BYTES_PER_RPC, - AggregationType.DISTRIBUTION, [GRPC_CLIENT_METHOD], - 'Distribution of bytes received per RPC, by method.', - DEFAULT_BYTES_DISTRIBUTION); + 'grpc.io/client/received_bytes_per_rpc', + GRPC_CLIENT_RECEIVED_BYTES_PER_RPC, + AggregationType.DISTRIBUTION, + [GRPC_CLIENT_METHOD], + 'Distribution of bytes received per RPC, by method.', + DEFAULT_BYTES_DISTRIBUTION +); /** {@link View} for client sent messages per RPC. */ const GRPC_CLIENT_SENT_MESSAGES_PER_RPC_VIEW = globalStats.createView( - 'grpc.io/client/sent_messages_per_rpc', GRPC_CLIENT_SENT_MESSAGES_PER_RPC, - AggregationType.DISTRIBUTION, [GRPC_CLIENT_METHOD], - 'Distribution of sent messages count per RPC, by method.', - DEFAULT_MESSAGE_COUNT_DISTRIBUTION); + 'grpc.io/client/sent_messages_per_rpc', + GRPC_CLIENT_SENT_MESSAGES_PER_RPC, + AggregationType.DISTRIBUTION, + [GRPC_CLIENT_METHOD], + 'Distribution of sent messages count per RPC, by method.', + DEFAULT_MESSAGE_COUNT_DISTRIBUTION +); /** {@link View} for client sent bytes per RPC. */ const GRPC_CLIENT_SENT_BYTES_PER_RPC_VIEW = globalStats.createView( - 'grpc.io/client/sent_bytes_per_rpc', GRPC_CLIENT_SENT_BYTES_PER_RPC, - AggregationType.DISTRIBUTION, [GRPC_CLIENT_METHOD], - 'Distribution of bytes sent per RPC, by method.', - DEFAULT_BYTES_DISTRIBUTION); + 'grpc.io/client/sent_bytes_per_rpc', + GRPC_CLIENT_SENT_BYTES_PER_RPC, + AggregationType.DISTRIBUTION, + [GRPC_CLIENT_METHOD], + 'Distribution of bytes sent per RPC, by method.', + DEFAULT_BYTES_DISTRIBUTION +); /** {@link View} for client roundtrip latency in milliseconds. */ const GRPC_CLIENT_ROUNDTRIP_LATENCY_VIEW = globalStats.createView( - 'grpc.io/client/roundtrip_latency', GRPC_CLIENT_ROUNDTRIP_LATENCY, - AggregationType.DISTRIBUTION, [GRPC_CLIENT_METHOD], - 'Distribution of round-trip latency, by method.', - DEFAULT_MILLI_SECONDS_DISTRIBUTION); + 'grpc.io/client/roundtrip_latency', + GRPC_CLIENT_ROUNDTRIP_LATENCY, + AggregationType.DISTRIBUTION, + [GRPC_CLIENT_METHOD], + 'Distribution of round-trip latency, by method.', + DEFAULT_MILLI_SECONDS_DISTRIBUTION +); /** * {@link View} for completed client RPCs. @@ -121,13 +153,19 @@ const GRPC_CLIENT_ROUNDTRIP_LATENCY_VIEW = globalStats.createView( * unnecessary to use a separate "count" measure. */ const GRPC_CLIENT_COMPLETED_RPC_VIEW = globalStats.createView( - 'grpc.io/client/completed_rpcs', GRPC_CLIENT_ROUNDTRIP_LATENCY, - AggregationType.COUNT, [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], - 'Count of RPCs by method and status.', DEFAULT_MESSAGE_COUNT_DISTRIBUTION); + 'grpc.io/client/completed_rpcs', + GRPC_CLIENT_ROUNDTRIP_LATENCY, + AggregationType.COUNT, + [GRPC_CLIENT_METHOD, GRPC_CLIENT_STATUS], + 'Count of RPCs by method and status.', + DEFAULT_MESSAGE_COUNT_DISTRIBUTION +); export const GRPC_BASIC_CLIENT_VIEWS: View[] = [ GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC_VIEW, GRPC_CLIENT_RECEIVED_BYTES_PER_RPC_VIEW, - GRPC_CLIENT_SENT_MESSAGES_PER_RPC_VIEW, GRPC_CLIENT_SENT_BYTES_PER_RPC_VIEW, - GRPC_CLIENT_ROUNDTRIP_LATENCY_VIEW, GRPC_CLIENT_COMPLETED_RPC_VIEW + GRPC_CLIENT_SENT_MESSAGES_PER_RPC_VIEW, + GRPC_CLIENT_SENT_BYTES_PER_RPC_VIEW, + GRPC_CLIENT_ROUNDTRIP_LATENCY_VIEW, + GRPC_CLIENT_COMPLETED_RPC_VIEW, ]; diff --git a/packages/opencensus-instrumentation-grpc/src/grpc-stats/common-distributions.ts b/packages/opencensus-instrumentation-grpc/src/grpc-stats/common-distributions.ts index 55d269b5c..bb9936735 100644 --- a/packages/opencensus-instrumentation-grpc/src/grpc-stats/common-distributions.ts +++ b/packages/opencensus-instrumentation-grpc/src/grpc-stats/common-distributions.ts @@ -18,24 +18,89 @@ * Common histogram bucket boundaries for bytes received/sets Views. */ export const DEFAULT_BYTES_DISTRIBUTION: number[] = [ - 0, 1024, 2048, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, - 67108864, 268435456, 1073741824, 4294967296 + 0, + 1024, + 2048, + 4096, + 16384, + 65536, + 262144, + 1048576, + 4194304, + 16777216, + 67108864, + 268435456, + 1073741824, + 4294967296, ]; /** * Common histogram bucket boundaries for latency and elapsed-time Views. */ export const DEFAULT_MILLI_SECONDS_DISTRIBUTION: number[] = [ - 0, 0.01, 0.05, 0.1, 0.3, 0.6, 0.8, 1, 2, 3, 4, - 5, 6, 8, 10, 13, 16, 20, 25, 30, 40, 50, - 65, 80, 100, 130, 160, 200, 250, 300, 400, 500, 650, - 800, 1000, 2000, 5000, 10000, 20000, 50000, 100000 + 0, + 0.01, + 0.05, + 0.1, + 0.3, + 0.6, + 0.8, + 1, + 2, + 3, + 4, + 5, + 6, + 8, + 10, + 13, + 16, + 20, + 25, + 30, + 40, + 50, + 65, + 80, + 100, + 130, + 160, + 200, + 250, + 300, + 400, + 500, + 650, + 800, + 1000, + 2000, + 5000, + 10000, + 20000, + 50000, + 100000, ]; /** * Common histogram bucket boundaries for request/response count Views. */ export const DEFAULT_MESSAGE_COUNT_DISTRIBUTION: number[] = [ - 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, - 32768, 65536 + 0, + 1, + 2, + 4, + 8, + 16, + 32, + 64, + 128, + 256, + 512, + 1024, + 2048, + 4096, + 8192, + 16384, + 32768, + 65536, ]; diff --git a/packages/opencensus-instrumentation-grpc/src/grpc-stats/server-stats.ts b/packages/opencensus-instrumentation-grpc/src/grpc-stats/server-stats.ts index 32aad5d53..3dbf27ae2 100644 --- a/packages/opencensus-instrumentation-grpc/src/grpc-stats/server-stats.ts +++ b/packages/opencensus-instrumentation-grpc/src/grpc-stats/server-stats.ts @@ -14,41 +14,56 @@ * limitations under the License. */ -import {AggregationType, globalStats, Measure, MeasureUnit, View} from '@opencensus/core'; - -import {DEFAULT_BYTES_DISTRIBUTION, DEFAULT_MESSAGE_COUNT_DISTRIBUTION, DEFAULT_MILLI_SECONDS_DISTRIBUTION} from './common-distributions'; +import { + AggregationType, + globalStats, + Measure, + MeasureUnit, + View, +} from '@opencensus/core'; + +import { + DEFAULT_BYTES_DISTRIBUTION, + DEFAULT_MESSAGE_COUNT_DISTRIBUTION, + DEFAULT_MILLI_SECONDS_DISTRIBUTION, +} from './common-distributions'; /** {@link Measure} for number of messages received in each RPC. */ -export const GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC: Measure = - globalStats.createMeasureInt64( - 'grpc.io/server/received_messages_per_rpc', MeasureUnit.UNIT, - 'Number of messages received in each RPC. Has value 1 for non-streaming RPCs.'); +export const GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC: Measure = globalStats.createMeasureInt64( + 'grpc.io/server/received_messages_per_rpc', + MeasureUnit.UNIT, + 'Number of messages received in each RPC. Has value 1 for non-streaming RPCs.' +); /** {@link Measure} for gRPC server latency in milliseconds. */ export const GRPC_SERVER_SERVER_LATENCY: Measure = globalStats.createMeasureDouble( - 'grpc.io/server/server_latency', MeasureUnit.MS, - 'Time between first byte of request received to last byte of response sent, or terminal error.'); - + 'grpc.io/server/server_latency', + MeasureUnit.MS, + 'Time between first byte of request received to last byte of response sent, or terminal error.' +); /** {@link Measure} for number of messages sent in each RPC. */ -export const GRPC_SERVER_SENT_MESSAGES_PER_RPC: Measure = - globalStats.createMeasureInt64( - 'grpc.io/server/sent_messages_per_rpc', MeasureUnit.UNIT, - 'Number of messages sent in each RPC. Has value 1 for non-streaming RPCs.'); +export const GRPC_SERVER_SENT_MESSAGES_PER_RPC: Measure = globalStats.createMeasureInt64( + 'grpc.io/server/sent_messages_per_rpc', + MeasureUnit.UNIT, + 'Number of messages sent in each RPC. Has value 1 for non-streaming RPCs.' +); /** {@link Measure} for total bytes received across all messages per RPC. */ -export const GRPC_SERVER_RECEIVED_BYTES_PER_RPC: Measure = - globalStats.createMeasureDouble( - 'grpc.io/server/received_bytes_per_rpc', MeasureUnit.BYTE, - 'Total bytes received across all messages per RPC.'); +export const GRPC_SERVER_RECEIVED_BYTES_PER_RPC: Measure = globalStats.createMeasureDouble( + 'grpc.io/server/received_bytes_per_rpc', + MeasureUnit.BYTE, + 'Total bytes received across all messages per RPC.' +); /** * {@link Measure} for total bytes sent across all response messages per RPC. */ -export const GRPC_SERVER_SENT_BYTES_PER_RPC: Measure = - globalStats.createMeasureDouble( - 'grpc.io/server/sent_bytes_per_rpc', MeasureUnit.BYTE, - 'Total bytes sent in across all response messages per RPC'); +export const GRPC_SERVER_SENT_BYTES_PER_RPC: Measure = globalStats.createMeasureDouble( + 'grpc.io/server/sent_bytes_per_rpc', + MeasureUnit.BYTE, + 'Total bytes sent in across all response messages per RPC' +); /** * Tag key that represents a server gRPC method. @@ -57,7 +72,7 @@ export const GRPC_SERVER_SENT_BYTES_PER_RPC: Measure = * available in the context for the entire RPC call handling. */ export const GRPC_SERVER_METHOD = { - name: 'grpc_server_method' + name: 'grpc_server_method', }; /** @@ -68,44 +83,58 @@ export const GRPC_SERVER_METHOD = { * is only available around metrics recorded at the end of the incoming request. */ export const GRPC_SERVER_STATUS = { - name: 'grpc_server_status' + name: 'grpc_server_status', }; /** {@link View} for server received messages per RPC. */ const GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC_VIEW = globalStats.createView( - 'grpc.io/server/received_messages_per_rpc', - GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC, AggregationType.DISTRIBUTION, - [GRPC_SERVER_METHOD], - 'Distribution of messages received count per RPC, by method.', - DEFAULT_MESSAGE_COUNT_DISTRIBUTION); + 'grpc.io/server/received_messages_per_rpc', + GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC, + AggregationType.DISTRIBUTION, + [GRPC_SERVER_METHOD], + 'Distribution of messages received count per RPC, by method.', + DEFAULT_MESSAGE_COUNT_DISTRIBUTION +); /** {@link View} for server received bytes per RPC. */ const GRPC_SERVER_RECEIVED_BYTES_PER_RPC_VIEW = globalStats.createView( - 'grpc.io/server/received_bytes_per_rpc', GRPC_SERVER_RECEIVED_BYTES_PER_RPC, - AggregationType.DISTRIBUTION, [GRPC_SERVER_METHOD], - 'Distribution of received bytes per RPC, by method.', - DEFAULT_BYTES_DISTRIBUTION); + 'grpc.io/server/received_bytes_per_rpc', + GRPC_SERVER_RECEIVED_BYTES_PER_RPC, + AggregationType.DISTRIBUTION, + [GRPC_SERVER_METHOD], + 'Distribution of received bytes per RPC, by method.', + DEFAULT_BYTES_DISTRIBUTION +); /** {@link View} for server sent messages per RPC. */ const GRPC_SERVER_SENT_MESSAGES_PER_RPC_VIEW = globalStats.createView( - 'grpc.io/server/sent_messages_per_rpc', GRPC_SERVER_SENT_MESSAGES_PER_RPC, - AggregationType.DISTRIBUTION, [GRPC_SERVER_METHOD], - 'Distribution of messages received count per RPC, by method.', - DEFAULT_MESSAGE_COUNT_DISTRIBUTION); + 'grpc.io/server/sent_messages_per_rpc', + GRPC_SERVER_SENT_MESSAGES_PER_RPC, + AggregationType.DISTRIBUTION, + [GRPC_SERVER_METHOD], + 'Distribution of messages received count per RPC, by method.', + DEFAULT_MESSAGE_COUNT_DISTRIBUTION +); /** {@link View} for server sent bytes per RPC. */ const GRPC_SERVER_SENT_BYTES_PER_RPC_VIEW = globalStats.createView( - 'grpc.io/server/sent_bytes_per_rpc', GRPC_SERVER_SENT_BYTES_PER_RPC, - AggregationType.DISTRIBUTION, [GRPC_SERVER_METHOD], - 'Distribution of total sent bytes per RPC, by method.', - DEFAULT_BYTES_DISTRIBUTION); + 'grpc.io/server/sent_bytes_per_rpc', + GRPC_SERVER_SENT_BYTES_PER_RPC, + AggregationType.DISTRIBUTION, + [GRPC_SERVER_METHOD], + 'Distribution of total sent bytes per RPC, by method.', + DEFAULT_BYTES_DISTRIBUTION +); /** {@link View} for server server latency in milliseconds. */ const GRPC_SERVER_SERVER_LATENCY_VIEW = globalStats.createView( - 'grpc.io/server/server_latency', GRPC_SERVER_SERVER_LATENCY, - AggregationType.DISTRIBUTION, [GRPC_SERVER_METHOD], - 'Distribution of server latency in milliseconds, by method.', - DEFAULT_MILLI_SECONDS_DISTRIBUTION); + 'grpc.io/server/server_latency', + GRPC_SERVER_SERVER_LATENCY, + AggregationType.DISTRIBUTION, + [GRPC_SERVER_METHOD], + 'Distribution of server latency in milliseconds, by method.', + DEFAULT_MILLI_SECONDS_DISTRIBUTION +); /** * {@link View} for completed server RPCs. @@ -116,9 +145,13 @@ const GRPC_SERVER_SERVER_LATENCY_VIEW = globalStats.createView( * use a separate "count" measure. */ const GRPC_SERVER_COMPLETED_RPC_VIEW = globalStats.createView( - 'grpc.io/server/completed_rpcs', GRPC_SERVER_SERVER_LATENCY, - AggregationType.COUNT, [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], - 'Count of RPCs by method and status.', DEFAULT_MESSAGE_COUNT_DISTRIBUTION); + 'grpc.io/server/completed_rpcs', + GRPC_SERVER_SERVER_LATENCY, + AggregationType.COUNT, + [GRPC_SERVER_METHOD, GRPC_SERVER_STATUS], + 'Count of RPCs by method and status.', + DEFAULT_MESSAGE_COUNT_DISTRIBUTION +); export const GRPC_BASIC_SERVER_VIEWS: View[] = [ GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC_VIEW, diff --git a/packages/opencensus-instrumentation-grpc/src/grpc-stats/stats-common.ts b/packages/opencensus-instrumentation-grpc/src/grpc-stats/stats-common.ts index 12c6e9025..12bad7e69 100644 --- a/packages/opencensus-instrumentation-grpc/src/grpc-stats/stats-common.ts +++ b/packages/opencensus-instrumentation-grpc/src/grpc-stats/stats-common.ts @@ -14,9 +14,9 @@ * limitations under the License. */ -import {Stats} from '@opencensus/core'; -import {GRPC_BASIC_CLIENT_VIEWS} from './client-stats'; -import {GRPC_BASIC_SERVER_VIEWS} from './server-stats'; +import { Stats } from '@opencensus/core'; +import { GRPC_BASIC_CLIENT_VIEWS } from './client-stats'; +import { GRPC_BASIC_SERVER_VIEWS } from './server-stats'; /** Method to register all GRPC Views. */ export function registerAllGrpcViews(globalStats: Stats) { diff --git a/packages/opencensus-instrumentation-grpc/src/grpc.ts b/packages/opencensus-instrumentation-grpc/src/grpc.ts index e5c905fae..4a0f8d000 100644 --- a/packages/opencensus-instrumentation-grpc/src/grpc.ts +++ b/packages/opencensus-instrumentation-grpc/src/grpc.ts @@ -14,9 +14,25 @@ * limitations under the License. */ -import {BasePlugin, CanonicalCode, deserializeBinary, MessageEventType, PluginInternalFiles, serializeBinary, Span, SpanContext, SpanKind, TagMap, TagTtl, TraceOptions} from '@opencensus/core'; -import {deserializeSpanContext, serializeSpanContext} from '@opencensus/propagation-binaryformat'; -import {EventEmitter} from 'events'; +import { + BasePlugin, + CanonicalCode, + deserializeBinary, + MessageEventType, + PluginInternalFiles, + serializeBinary, + Span, + SpanContext, + SpanKind, + TagMap, + TagTtl, + TraceOptions, +} from '@opencensus/core'; +import { + deserializeSpanContext, + serializeSpanContext, +} from '@opencensus/propagation-binaryformat'; +import { EventEmitter } from 'events'; import * as grpcTypes from 'grpc'; import * as lodash from 'lodash'; import * as shimmer from 'shimmer'; @@ -40,30 +56,34 @@ export type GrpcModule = typeof grpcTypes; type MakeClientConstructor = typeof grpcTypes.makeGenericClientConstructor; type RegisterMethod = typeof grpcTypes.Server.prototype.register; -type Status = { - code: number, details: string; metadata: grpcTypes.Metadata; -}; +interface Status { + code: number; + details: string; + metadata: grpcTypes.Metadata; +} -type ServerCall = typeof grpcTypes.ServerUnaryCall| - typeof grpcTypes.ServerReadableStream| - typeof grpcTypes.ServerWriteableStream| - typeof grpcTypes.ServerDuplexStream; +type ServerCall = + | typeof grpcTypes.ServerUnaryCall + | typeof grpcTypes.ServerReadableStream + | typeof grpcTypes.ServerWriteableStream + | typeof grpcTypes.ServerDuplexStream; -type ServerCallWithMeta = ServerCall&{ +type ServerCallWithMeta = ServerCall & { metadata: grpcTypes.Metadata; status: Status; // tslint:disable-next-line:no-any - request?: any -} -&EventEmitter; + request?: any; +} & EventEmitter; -export type SendUnaryDataCallback = - (error: grpcTypes.ServiceError|null, - // tslint:disable-next-line:no-any - value?: any, trailer?: grpcTypes.Metadata, flags?: grpcTypes.writeFlags) => - void; +export type SendUnaryDataCallback = ( + error: grpcTypes.ServiceError | null, + // tslint:disable-next-line:no-any + value?: any, + trailer?: grpcTypes.Metadata, + flags?: grpcTypes.writeFlags +) => void; -type GrpcClientFunc = typeof Function&{ +type GrpcClientFunc = typeof Function & { path: string; requestStream: boolean; responseStream: boolean; @@ -77,13 +97,13 @@ let Metadata: any; let GrpcClientModule: any; const UNLIMITED_PROPAGATION_MD = { - tagTtl: TagTtl.UNLIMITED_PROPAGATION + tagTtl: TagTtl.UNLIMITED_PROPAGATION, }; /** gRPC instrumentation plugin for Opencensus */ export class GrpcPlugin extends BasePlugin { /** Span grpc attributes */ - static readonly ATTRIBUTE_GRPC_KIND = 'grpc.kind'; // SERVER or CLIENT + static readonly ATTRIBUTE_GRPC_KIND = 'grpc.kind'; // SERVER or CLIENT static readonly ATTRIBUTE_GRPC_METHOD = 'grpc.method'; static readonly ATTRIBUTE_GRPC_STATUS_CODE = 'grpc.status_code'; static readonly ATTRIBUTE_GRPC_ERROR_NAME = 'grpc.error_name'; @@ -91,10 +111,10 @@ export class GrpcPlugin extends BasePlugin { protected readonly internalFileList: PluginInternalFiles = { '0.13 - 1.6': { - 'client': 'src/node/src/client.js', - 'metadata': 'src/node/src/metadata.js' + client: 'src/node/src/client.js', + metadata: 'src/node/src/metadata.js', }, - '^1.7': {'client': 'src/client.js', 'metadata': 'src/metadata.js'} + '^1.7': { client: 'src/client.js', metadata: 'src/metadata.js' }, }; /** Constructs a new GrpcPlugin instance. */ @@ -107,15 +127,20 @@ export class GrpcPlugin extends BasePlugin { this.logger.debug('applying patch to %s@%s', this.moduleName, this.version); shimmer.wrap( - this.moduleExports.Server.prototype, 'register' as never, - this.getPatchServer()); + this.moduleExports.Server.prototype, + 'register' as never, + this.getPatchServer() + ); if (this.internalFilesExports) { GrpcClientModule = this.internalFilesExports['client']; Metadata = this.internalFilesExports['metadata']; shimmer.wrap( - GrpcClientModule, 'makeClientConstructor', this.getPatchClient()); + GrpcClientModule, + 'makeClientConstructor', + this.getPatchClient() + ); } return this.moduleExports; @@ -140,62 +165,84 @@ export class GrpcPlugin extends BasePlugin { const plugin = this; plugin.logger.debug('patched server'); return function register( - // tslint:disable-next-line:no-any - this: grpcTypes.Server&{handlers: any}, name: string, - handler: grpcTypes.handleCall, - serialize: grpcTypes.serialize, - deserialize: grpcTypes.deserialize, type: string) { + // tslint:disable-next-line:no-any + this: grpcTypes.Server & { handlers: any }, + name: string, + handler: grpcTypes.handleCall, + serialize: grpcTypes.serialize, + deserialize: grpcTypes.deserialize, + type: string + ) { const result = originalRegister.apply(this, arguments); const handlerSet = this.handlers[name]; // Patch the methods that are invoked when a gRPC service call is // made. The function 'func' is the user-implemented handling function. shimmer.wrap( - handlerSet, 'func', - (originalFunc: grpcTypes.handleCall) => { - return function func( - this: typeof handlerSet, call: ServerCallWithMeta, - callback: SendUnaryDataCallback) { - const self = this; - - const traceOptions: TraceOptions = { - name: `grpc.${name.replace('/', '')}`, - kind: SpanKind.SERVER - }; - - const spanContext = GrpcPlugin.getSpanContext(call.metadata); - if (spanContext) { - traceOptions.spanContext = spanContext; - } - plugin.logger.debug( - 'path func: %s', JSON.stringify(traceOptions)); - - return plugin.tracer.startRootSpan(traceOptions, rootSpan => { - if (!rootSpan) { - return originalFunc.call(self, call, callback); - } - - rootSpan.addAttribute(GrpcPlugin.ATTRIBUTE_GRPC_METHOD, name); - if (traceOptions.kind) { - rootSpan.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_KIND, traceOptions.kind); - } - - switch (type) { - case 'unary': - case 'client_stream': - return plugin.clientStreamAndUnaryHandler( - plugin, rootSpan, call, callback, originalFunc, self); - case 'server_stream': - case 'bidi': - return plugin.serverStreamAndBidiHandler( - plugin, rootSpan, call, originalFunc, self); - default: - break; - } - }); + handlerSet, + 'func', + (originalFunc: grpcTypes.handleCall) => { + return function func( + this: typeof handlerSet, + call: ServerCallWithMeta, + callback: SendUnaryDataCallback + ) { + const self = this; + + const traceOptions: TraceOptions = { + name: `grpc.${name.replace('/', '')}`, + kind: SpanKind.SERVER, }; - }); + + const spanContext = GrpcPlugin.getSpanContext(call.metadata); + if (spanContext) { + traceOptions.spanContext = spanContext; + } + plugin.logger.debug( + 'path func: %s', + JSON.stringify(traceOptions) + ); + + return plugin.tracer.startRootSpan(traceOptions, rootSpan => { + if (!rootSpan) { + return originalFunc.call(self, call, callback); + } + + rootSpan.addAttribute(GrpcPlugin.ATTRIBUTE_GRPC_METHOD, name); + if (traceOptions.kind) { + rootSpan.addAttribute( + GrpcPlugin.ATTRIBUTE_GRPC_KIND, + traceOptions.kind + ); + } + + switch (type) { + case 'unary': + case 'client_stream': + return plugin.clientStreamAndUnaryHandler( + plugin, + rootSpan, + call, + callback, + originalFunc, + self + ); + case 'server_stream': + case 'bidi': + return plugin.serverStreamAndBidiHandler( + plugin, + rootSpan, + call, + originalFunc, + self + ); + default: + break; + } + }); + }; + } + ); return result; }; }; @@ -205,41 +252,62 @@ export class GrpcPlugin extends BasePlugin { * Handler Unary and Client Stream Calls */ private clientStreamAndUnaryHandler( - plugin: GrpcPlugin, rootSpan: Span, call: ServerCallWithMeta, - callback: SendUnaryDataCallback, - original: grpcTypes.handleCall, self: {}) { + plugin: GrpcPlugin, + rootSpan: Span, + call: ServerCallWithMeta, + callback: SendUnaryDataCallback, + original: grpcTypes.handleCall, + self: {} + ) { const startTime = Date.now(); function patchedCallback( - err: grpcTypes.ServiceError, - // tslint:disable-next-line:no-any - value: any, trailer: grpcTypes.Metadata, flags: grpcTypes.writeFlags) { + err: grpcTypes.ServiceError, + // tslint:disable-next-line:no-any + value: any, + trailer: grpcTypes.Metadata, + flags: grpcTypes.writeFlags + ) { if (err) { if (err.code) { rootSpan.setStatus( - GrpcPlugin.convertGrpcStatusToSpanStatus(err.code), err.message); + GrpcPlugin.convertGrpcStatusToSpanStatus(err.code), + err.message + ); rootSpan.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, err.code.toString()); + GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, + err.code.toString() + ); } rootSpan.addAttribute(GrpcPlugin.ATTRIBUTE_GRPC_ERROR_NAME, err.name); rootSpan.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_ERROR_MESSAGE, err.message); + GrpcPlugin.ATTRIBUTE_GRPC_ERROR_MESSAGE, + err.message + ); } else { rootSpan.setStatus(CanonicalCode.OK); rootSpan.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, - grpcTypes.status.OK.toString()); + GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, + grpcTypes.status.OK.toString() + ); } rootSpan.addMessageEvent(MessageEventType.RECEIVED, 1); // record stats const parentTagCtx = - GrpcPlugin.getTagContext(call.metadata) || new TagMap(); + GrpcPlugin.getTagContext(call.metadata) || new TagMap(); parentTagCtx.set( - serverStats.GRPC_SERVER_METHOD, {value: rootSpan.name}, - UNLIMITED_PROPAGATION_MD); + serverStats.GRPC_SERVER_METHOD, + { value: rootSpan.name }, + UNLIMITED_PROPAGATION_MD + ); const req = call.hasOwnProperty('request') ? call.request : {}; GrpcPlugin.recordStats( - rootSpan.kind, parentTagCtx, value, req, Date.now() - startTime); + rootSpan.kind, + parentTagCtx, + value, + req, + Date.now() - startTime + ); rootSpan.end(); return callback(err, value, trailer, flags); @@ -253,8 +321,12 @@ export class GrpcPlugin extends BasePlugin { * Handler Server Stream and Bidirectional Stream Calls */ private serverStreamAndBidiHandler( - plugin: GrpcPlugin, rootSpan: Span, call: ServerCallWithMeta, - original: grpcTypes.handleCall, self: {}) { + plugin: GrpcPlugin, + rootSpan: Span, + call: ServerCallWithMeta, + original: grpcTypes.handleCall, + self: {} + ) { let spanEnded = false; const endSpan = () => { if (!spanEnded) { @@ -266,9 +338,12 @@ export class GrpcPlugin extends BasePlugin { plugin.tracer.wrapEmitter(call); call.on('finish', () => { rootSpan.setStatus( - GrpcPlugin.convertGrpcStatusToSpanStatus(call.status.code)); + GrpcPlugin.convertGrpcStatusToSpanStatus(call.status.code) + ); rootSpan.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, call.status.code.toString()); + GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, + call.status.code.toString() + ); // if there is an error, span is ended on error event, otherwise here if (call.status.code === 0) { endSpan(); @@ -278,7 +353,9 @@ export class GrpcPlugin extends BasePlugin { call.on('error', (err: grpcTypes.ServiceError) => { rootSpan.addAttribute(GrpcPlugin.ATTRIBUTE_GRPC_ERROR_NAME, err.name); rootSpan.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_ERROR_MESSAGE, err.message); + GrpcPlugin.ATTRIBUTE_GRPC_ERROR_MESSAGE, + err.message + ); endSpan(); }); @@ -295,19 +372,22 @@ export class GrpcPlugin extends BasePlugin { return (original: MakeClientConstructor) => { plugin.logger.debug('patchClient'); return function makeClientConstructor( - this: typeof grpcTypes.Client, - methods: grpcTypes.ServiceDefinition, - serviceName: string, options: grpcTypes.GenericClientOptions) { + this: typeof grpcTypes.Client, + methods: grpcTypes.ServiceDefinition, + serviceName: string, + options: grpcTypes.GenericClientOptions + ) { const client = original.apply(this, arguments); shimmer.massWrap( - client.prototype, Object.keys(methods) as never[], - plugin.getPatchedClientMethods()); + client.prototype, + Object.keys(methods) as never[], + plugin.getPatchedClientMethods() + ); return client; }; }; } - /** * This function starts a span (child or root) immediately before the * client method is invoked, and ends it either in a callback or stream @@ -318,9 +398,7 @@ export class GrpcPlugin extends BasePlugin { // tslint:disable-next-line:no-any return (original: GrpcClientFunc) => { plugin.logger.debug('patchAllClientsMethods'); - return function clientMethodTrace( - this: grpcTypes.Client, - ) { + return function clientMethodTrace(this: grpcTypes.Client) { const traceOptions = { name: `grpc.${original.path.replace('/', '')}`, kind: SpanKind.CLIENT, @@ -333,13 +411,17 @@ export class GrpcPlugin extends BasePlugin { // span. if (!plugin.tracer.currentRootSpan) { return plugin.tracer.startRootSpan( - traceOptions, - plugin.makeGrpcClientRemoteCall(original, args, this, plugin)); + traceOptions, + plugin.makeGrpcClientRemoteCall(original, args, this, plugin) + ); } else { - const span = plugin.tracer.startChildSpan( - {name: traceOptions.name, kind: traceOptions.kind}); - return (plugin.makeGrpcClientRemoteCall( - original, args, this, plugin))(span); + const span = plugin.tracer.startChildSpan({ + name: traceOptions.name, + kind: traceOptions.kind, + }); + return plugin.makeGrpcClientRemoteCall(original, args, this, plugin)( + span + ); } }; }; @@ -349,9 +431,12 @@ export class GrpcPlugin extends BasePlugin { * This method handels the client remote call */ private makeGrpcClientRemoteCall( - // tslint:disable-next-line:no-any - original: GrpcClientFunc, args: any[], self: grpcTypes.Client, - plugin: GrpcPlugin) { + original: GrpcClientFunc, + // tslint:disable-next-line:no-any + args: any[], + self: grpcTypes.Client, + plugin: GrpcPlugin + ) { const startTime = Date.now(); const originalArgs = args; /** @@ -359,41 +444,57 @@ export class GrpcPlugin extends BasePlugin { * when the callback is invoked. */ function patchedCallback( - span: Span, callback: SendUnaryDataCallback, - metadata: grpcTypes.Metadata) { + span: Span, + callback: SendUnaryDataCallback, + metadata: grpcTypes.Metadata + ) { // tslint:disable-next-line:no-any const wrappedFn = (err: grpcTypes.ServiceError, res: any) => { if (err) { if (err.code) { span.setStatus( - GrpcPlugin.convertGrpcStatusToSpanStatus(err.code), - err.message); + GrpcPlugin.convertGrpcStatusToSpanStatus(err.code), + err.message + ); span.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, err.code.toString()); + GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, + err.code.toString() + ); } span.addAttribute(GrpcPlugin.ATTRIBUTE_GRPC_ERROR_NAME, err.name); span.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_ERROR_MESSAGE, err.message); + GrpcPlugin.ATTRIBUTE_GRPC_ERROR_MESSAGE, + err.message + ); } else { span.setStatus(CanonicalCode.OK); span.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, - grpcTypes.status.OK.toString()); + GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, + grpcTypes.status.OK.toString() + ); } span.addMessageEvent(MessageEventType.SENT, 1); // record stats: new RPCs on client-side inherit the tag context from // the current Context. - const parentTagCtx = - plugin.stats ? plugin.stats.getCurrentTagContext() : new TagMap(); + const parentTagCtx = plugin.stats + ? plugin.stats.getCurrentTagContext() + : new TagMap(); if (parentTagCtx.tags.size > 0) { GrpcPlugin.setTagContext(metadata, parentTagCtx); } parentTagCtx.set( - clientStats.GRPC_CLIENT_METHOD, {value: span.name}, - UNLIMITED_PROPAGATION_MD); + clientStats.GRPC_CLIENT_METHOD, + { value: span.name }, + UNLIMITED_PROPAGATION_MD + ); GrpcPlugin.recordStats( - span.kind, parentTagCtx, originalArgs, res, Date.now() - startTime); + span.kind, + parentTagCtx, + originalArgs, + res, + Date.now() - startTime + ); span.end(); callback(err, res); @@ -409,12 +510,15 @@ export class GrpcPlugin extends BasePlugin { const metadata = this.getMetadata(original, args); // if unary or clientStream if (!original.responseStream) { - const callbackFuncIndex = findIndex(args, (arg) => { + const callbackFuncIndex = findIndex(args, arg => { return typeof arg === 'function'; }); if (callbackFuncIndex !== -1) { - args[callbackFuncIndex] = - patchedCallback(span, args[callbackFuncIndex], metadata); + args[callbackFuncIndex] = patchedCallback( + span, + args[callbackFuncIndex], + metadata + ); } } @@ -435,7 +539,9 @@ export class GrpcPlugin extends BasePlugin { // span.status = plugin.traceStatus(err.code); span.addAttribute(GrpcPlugin.ATTRIBUTE_GRPC_ERROR_NAME, err.name); span.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_ERROR_MESSAGE, err.message); + GrpcPlugin.ATTRIBUTE_GRPC_ERROR_MESSAGE, + err.message + ); if (!spanEnded) { span.end(); spanEnded = true; @@ -445,7 +551,9 @@ export class GrpcPlugin extends BasePlugin { call.on('status', (status: Status) => { span.setStatus(GrpcPlugin.convertGrpcStatusToSpanStatus(status.code)); span.addAttribute( - GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, status.code.toString()); + GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE, + status.code.toString() + ); if (!spanEnded) { span.end(); @@ -463,9 +571,12 @@ export class GrpcPlugin extends BasePlugin { * Code snippet inspired by: * https://github.com/GoogleCloudPlatform/cloud-trace-nodejs/blob/src/plugins/plugin-grpc.ts#L96) */ - // tslint:disable-next-line:no-any - private getMetadata(original: GrpcClientFunc, args: any[]): - grpcTypes.Metadata { + + private getMetadata( + original: GrpcClientFunc, + // tslint:disable-next-line:no-any + args: any[] + ): grpcTypes.Metadata { let metadata: grpcTypes.Metadata; // This finds an instance of Metadata among the arguments. @@ -474,8 +585,12 @@ export class GrpcPlugin extends BasePlugin { // but this is an extremely rare case. // tslint:disable-next-line:no-any let metadataIndex = findIndex(args, (arg: any) => { - return arg && typeof arg === 'object' && arg._internal_repr && - typeof arg.getMap === 'function'; + return ( + arg && + typeof arg === 'object' && + arg._internal_repr && + typeof arg.getMap === 'function' + ); }); if (metadataIndex === -1) { metadata = new Metadata(); @@ -517,7 +632,7 @@ export class GrpcPlugin extends BasePlugin { * @param metadata The Metadata object from which span context should be * retrieved. */ - static getSpanContext(metadata: grpcTypes.Metadata): SpanContext|null { + static getSpanContext(metadata: grpcTypes.Metadata): SpanContext | null { const metadataValue = metadata.getMap()[GRPC_TRACE_KEY] as Buffer; // Entry doesn't exist. if (!metadataValue) { @@ -537,8 +652,10 @@ export class GrpcPlugin extends BasePlugin { * added. * @param spanContext The span context. */ - static setSpanContext(metadata: grpcTypes.Metadata, spanContext: SpanContext): - void { + static setSpanContext( + metadata: grpcTypes.Metadata, + spanContext: SpanContext + ): void { const serializedSpanContext = serializeSpanContext(spanContext); if (serializedSpanContext) { metadata.set(GRPC_TRACE_KEY, serializedSpanContext); @@ -550,7 +667,7 @@ export class GrpcPlugin extends BasePlugin { * null otherwise. * @param metadata The Metadata object from which TagMap should be retrieved. */ - static getTagContext(metadata: grpcTypes.Metadata): TagMap|null { + static getTagContext(metadata: grpcTypes.Metadata): TagMap | null { const metadataValue = metadata.getMap()[GRPC_TAGS_KEY] as Buffer; // Entry doesn't exist. if (!metadataValue) return null; @@ -578,7 +695,12 @@ export class GrpcPlugin extends BasePlugin { /** Method to record stats for client and server. */ static recordStats( - kind: SpanKind, tags: TagMap, argsOrValue: {}, reqOrRes: {}, ms: number) { + kind: SpanKind, + tags: TagMap, + argsOrValue: {}, + reqOrRes: {}, + ms: number + ) { if (!plugin.stats) { return; } @@ -589,51 +711,54 @@ export class GrpcPlugin extends BasePlugin { case SpanKind.CLIENT: measureList.push({ measure: clientStats.GRPC_CLIENT_SENT_BYTES_PER_RPC, - value: sizeof(argsOrValue) + value: sizeof(argsOrValue), }); measureList.push({ measure: clientStats.GRPC_CLIENT_RECEIVED_BYTES_PER_RPC, - value: sizeof(reqOrRes) + value: sizeof(reqOrRes), }); measureList.push({ measure: clientStats.GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC, - value: 1 + value: 1, }); measureList.push({ measure: clientStats.GRPC_CLIENT_SENT_MESSAGES_PER_RPC, - value: 1 + value: 1, + }); + measureList.push({ + measure: clientStats.GRPC_CLIENT_ROUNDTRIP_LATENCY, + value: ms, }); - measureList.push( - {measure: clientStats.GRPC_CLIENT_ROUNDTRIP_LATENCY, value: ms}); break; case SpanKind.SERVER: measureList.push({ measure: serverStats.GRPC_SERVER_RECEIVED_BYTES_PER_RPC, - value: sizeof(reqOrRes) + value: sizeof(reqOrRes), }); measureList.push({ measure: serverStats.GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC, - value: 1 + value: 1, }); measureList.push({ measure: serverStats.GRPC_SERVER_SENT_BYTES_PER_RPC, - value: sizeof(argsOrValue) + value: sizeof(argsOrValue), }); measureList.push({ measure: serverStats.GRPC_SERVER_SENT_MESSAGES_PER_RPC, - value: 1 + value: 1, + }); + measureList.push({ + measure: serverStats.GRPC_SERVER_SERVER_LATENCY, + value: ms, }); - measureList.push( - {measure: serverStats.GRPC_SERVER_SERVER_LATENCY, value: ms}); break; default: break; } plugin.stats.record(measureList, tags); - } catch (ignore) { - } + } catch (ignore) {} } } const plugin = new GrpcPlugin(); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-instrumentation-grpc/src/index.ts b/packages/opencensus-instrumentation-grpc/src/index.ts index e4f948141..8ef6c4ff9 100644 --- a/packages/opencensus-instrumentation-grpc/src/index.ts +++ b/packages/opencensus-instrumentation-grpc/src/index.ts @@ -15,4 +15,8 @@ */ export * from './grpc'; -export {registerAllGrpcViews, registerClientGrpcBasicViews, registerServerGrpcBasicViews} from './grpc-stats/stats-common'; +export { + registerAllGrpcViews, + registerClientGrpcBasicViews, + registerServerGrpcBasicViews, +} from './grpc-stats/stats-common'; diff --git a/packages/opencensus-instrumentation-grpc/test/test-grpc.ts b/packages/opencensus-instrumentation-grpc/test/test-grpc.ts index 5caf95c58..fdbcdecc9 100644 --- a/packages/opencensus-instrumentation-grpc/test/test-grpc.ts +++ b/packages/opencensus-instrumentation-grpc/test/test-grpc.ts @@ -14,15 +14,34 @@ * limitations under the License. */ -import {CoreTracer, globalStats, Measurement, Span, SpanEventListener, SpanKind, StatsEventListener, TagKey, TagMap, TagValue, View} from '@opencensus/core'; -import {logger} from '@opencensus/core'; +import { + CoreTracer, + globalStats, + Measurement, + Span, + SpanEventListener, + SpanKind, + StatsEventListener, + TagKey, + TagMap, + TagValue, + View, +} from '@opencensus/core'; +import { logger } from '@opencensus/core'; import * as assert from 'assert'; import * as grpcModule from 'grpc'; import * as path from 'path'; -import {GRPC_TAGS_KEY, GRPC_TRACE_KEY, GrpcModule, GrpcPlugin, plugin, SendUnaryDataCallback} from '../src/'; +import { + GRPC_TAGS_KEY, + GRPC_TRACE_KEY, + GrpcModule, + GrpcPlugin, + plugin, + SendUnaryDataCallback, +} from '../src/'; import * as clientStats from '../src/grpc-stats/client-stats'; import * as serverStats from '../src/grpc-stats/server-stats'; -import {registerAllGrpcViews} from '../src/grpc-stats/stats-common'; +import { registerAllGrpcViews } from '../src/grpc-stats/stats-common'; const PROTO_PATH = __dirname + '/fixtures/grpc-instrumentation-test.proto'; const grpcPort = 50051; @@ -38,7 +57,10 @@ class TestExporter implements StatsEventListener { } onRecord( - views: View[], measurement: Measurement, tagMap: Map) { + views: View[], + measurement: Measurement, + tagMap: Map + ) { this.recordedMeasurements.push(measurement); } @@ -63,7 +85,6 @@ const replicate = (request: TestRequestResponse) => { function startServer(grpc: GrpcModule, proto: any) { const server = new grpc.Server(); - function getError(msg: string, code: number): grpcModule.ServiceError { const err: grpcModule.ServiceError = new Error(msg); err.name = msg; @@ -79,19 +100,21 @@ function startServer(grpc: GrpcModule, proto: any) { // This method returns the request unaryMethod( - // tslint:disable-next-line:no-any - call: grpcModule.ServerUnaryCall, - callback: SendUnaryDataCallback) { - (call.request.num <= MAX_ERROR_STATUS) ? - callback(getError('Unary Method Error', call.request.num)) : - callback(null, {num: call.request.num}); + // tslint:disable-next-line:no-any + call: grpcModule.ServerUnaryCall, + callback: SendUnaryDataCallback + ) { + call.request.num <= MAX_ERROR_STATUS + ? callback(getError('Unary Method Error', call.request.num)) + : callback(null, { num: call.request.num }); }, // This method sum the requests clientStreamMethod( - // tslint:disable-next-line:no-any - call: grpcModule.ServerReadableStream, - callback: SendUnaryDataCallback) { + // tslint:disable-next-line:no-any + call: grpcModule.ServerReadableStream, + callback: SendUnaryDataCallback + ) { let sum = 0; let hasError = false; let code = grpcModule.status.OK; @@ -103,8 +126,9 @@ function startServer(grpc: GrpcModule, proto: any) { } }); call.on('end', () => { - hasError ? callback(getError('Client Stream Method Error', code)) : - callback(null, {num: sum}); + hasError + ? callback(getError('Client Stream Method Error', code)) + : callback(null, { num: sum }); }); }, @@ -116,9 +140,11 @@ function startServer(grpc: GrpcModule, proto: any) { if (call.request.num <= MAX_ERROR_STATUS) { call.emit( - 'error', getError('Server Stream Method Error', call.request.num)); + 'error', + getError('Server Stream Method Error', call.request.num) + ); } else { - result.map((element) => { + result.map(element => { call.write(element); }); } @@ -138,7 +164,7 @@ function startServer(grpc: GrpcModule, proto: any) { call.on('end', () => { call.end(); }); - } + }, }); server.bind('localhost:' + grpcPort, grpc.ServerCredentials.createInsecure()); server.start(); @@ -148,11 +174,12 @@ function startServer(grpc: GrpcModule, proto: any) { // tslint:disable-next-line:no-any function createClient(grpc: GrpcModule, proto: any) { return new proto.GrpcTester( - 'localhost:' + grpcPort, grpc.credentials.createInsecure()); + 'localhost:' + grpcPort, + grpc.credentials.createInsecure() + ); } - -type TestGrpcClient = grpcModule.Client&{ +type TestGrpcClient = grpcModule.Client & { // tslint:disable-next-line:no-any unaryMethod: any; // tslint:disable-next-line:no-any @@ -163,91 +190,98 @@ type TestGrpcClient = grpcModule.Client&{ bidiStreamMethod: any; }; -type TestRequestResponse = { +interface TestRequestResponse { num: number; -}; +} const grpcClient = { - - unaryMethod: (client: TestGrpcClient, request: TestRequestResponse): - Promise => { - return new Promise((resolve, reject) => { - return client.unaryMethod( - request, - (err: grpcModule.ServiceError, response: TestRequestResponse) => { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - }); - }, - - - clientStreamMethod: (client: TestGrpcClient, request: TestRequestResponse[]): - Promise => { - return new Promise((resolve, reject) => { - const writeStream = client.clientStreamMethod( - (err: grpcModule.ServiceError, response: TestRequestResponse) => { - if (err) { - reject(err); - } else { - resolve(response); - } - }); - - request.forEach(element => { - writeStream.write(element); - }); - writeStream.end(); - }); - }, - - serverStreamMethod: (client: TestGrpcClient, request: TestRequestResponse): - Promise => { - return new Promise((resolve, reject) => { - const result: TestRequestResponse[] = []; - const readStream = client.serverStreamMethod(request); - - readStream.on('data', (data: TestRequestResponse) => { - result.push(data); - }); - readStream.on('error', (err: grpcModule.ServiceError) => { + unaryMethod: ( + client: TestGrpcClient, + request: TestRequestResponse + ): Promise => { + return new Promise((resolve, reject) => { + return client.unaryMethod( + request, + (err: grpcModule.ServiceError, response: TestRequestResponse) => { + if (err) { reject(err); - }); - readStream.on('end', () => { - resolve(result); - }); - }); - }, - - - bidiStreamMethod: (client: TestGrpcClient, request: TestRequestResponse[]): - Promise => { - return new Promise((resolve, reject) => { - const result: TestRequestResponse[] = []; - const bidiStream = client.bidiStreamMethod([]); + } else { + resolve(response); + } + } + ); + }); + }, + + clientStreamMethod: ( + client: TestGrpcClient, + request: TestRequestResponse[] + ): Promise => { + return new Promise((resolve, reject) => { + const writeStream = client.clientStreamMethod( + (err: grpcModule.ServiceError, response: TestRequestResponse) => { + if (err) { + reject(err); + } else { + resolve(response); + } + } + ); - bidiStream.on('data', (data: TestRequestResponse) => { - result.push(data); - }); + request.forEach(element => { + writeStream.write(element); + }); + writeStream.end(); + }); + }, + + serverStreamMethod: ( + client: TestGrpcClient, + request: TestRequestResponse + ): Promise => { + return new Promise((resolve, reject) => { + const result: TestRequestResponse[] = []; + const readStream = client.serverStreamMethod(request); + + readStream.on('data', (data: TestRequestResponse) => { + result.push(data); + }); + readStream.on('error', (err: grpcModule.ServiceError) => { + reject(err); + }); + readStream.on('end', () => { + resolve(result); + }); + }); + }, + + bidiStreamMethod: ( + client: TestGrpcClient, + request: TestRequestResponse[] + ): Promise => { + return new Promise((resolve, reject) => { + const result: TestRequestResponse[] = []; + const bidiStream = client.bidiStreamMethod([]); + + bidiStream.on('data', (data: TestRequestResponse) => { + result.push(data); + }); - request.forEach(element => { - bidiStream.write(element); - }); + request.forEach(element => { + bidiStream.write(element); + }); - bidiStream.on('error', (err: grpcModule.ServiceError) => { - reject(err); - }); + bidiStream.on('error', (err: grpcModule.ServiceError) => { + reject(err); + }); - bidiStream.on('end', () => { - resolve(result); - }); + bidiStream.on('end', () => { + resolve(result); + }); - bidiStream.end(); - }); - } + bidiStream.end(); + }); + }, }; class RootSpanVerifier implements SpanEventListener { @@ -264,13 +298,12 @@ class RootSpanVerifier implements SpanEventListener { } } - describe('GrpcPlugin() ', function() { let server: grpcModule.Server; let client: TestGrpcClient; const tracer = new CoreTracer(); const rootSpanVerifier = new RootSpanVerifier(); - tracer.start({samplingRate: 1, logger: log}); + tracer.start({ samplingRate: 1, logger: log }); const testExporter = new TestExporter(); it('should return a plugin', () => { @@ -298,13 +331,11 @@ describe('GrpcPlugin() ', function() { server.forceShutdown(); }); - const requestList: TestRequestResponse[] = [{num: 100}, {num: 50}]; + const requestList: TestRequestResponse[] = [{ num: 100 }, { num: 50 }]; const resultSum = { - num: requestList.reduce( - (sum, x) => { - return sum + x.num; - }, - 0) + num: requestList.reduce((sum, x) => { + return sum + x.num; + }, 0), }; const methodList = [ { @@ -312,106 +343,126 @@ describe('GrpcPlugin() ', function() { methodName: 'UnaryMethod', method: grpcClient.unaryMethod, request: requestList[0], - result: requestList[0] + result: requestList[0], }, { description: 'clientStream call', methodName: 'ClientStreamMethod', method: grpcClient.clientStreamMethod, request: requestList, - result: resultSum + result: resultSum, }, { description: 'serverStream call', methodName: 'ServerStreamMethod', method: grpcClient.serverStreamMethod, request: resultSum, - result: replicate(resultSum) + result: replicate(resultSum), }, { description: 'bidiStream call', methodName: 'BidiStreamMethod', method: grpcClient.bidiStreamMethod, request: requestList, - result: requestList - } + result: requestList, + }, ]; // Compare two arrays using an equal function f // tslint:disable-next-line:no-any const arrayIsEqual = (f: any) => ([x, ...xs]) => ([y, ...ys]): any => - x === undefined && y === undefined ? - true : - Boolean(f(x)(y)) && arrayIsEqual(f)(xs)(ys); + x === undefined && y === undefined + ? true + : Boolean(f(x)(y)) && arrayIsEqual(f)(xs)(ys); // Return true if two requests has the same num value const requestEqual = (x: TestRequestResponse) => (y: TestRequestResponse) => - x.num !== undefined && x.num === y.num; + x.num !== undefined && x.num === y.num; // Check if its equal requests or array of requests - const checkEqual = (x: TestRequestResponse|TestRequestResponse[]) => - (y: TestRequestResponse|TestRequestResponse[]) => - (x instanceof Array) && (y instanceof Array) ? - (arrayIsEqual(requestEqual)(x)(y)) : - !(x instanceof Array) && !(y instanceof Array) ? (requestEqual(x)(y)) : - false; + const checkEqual = (x: TestRequestResponse | TestRequestResponse[]) => ( + y: TestRequestResponse | TestRequestResponse[] + ) => + x instanceof Array && y instanceof Array + ? arrayIsEqual(requestEqual)(x)(y) + : !(x instanceof Array) && !(y instanceof Array) + ? requestEqual(x)(y) + : false; function assertSpan( - span: Span, spanName: string, kind: SpanKind, status: grpcModule.status) { + span: Span, + spanName: string, + kind: SpanKind, + status: grpcModule.status + ) { assert.strictEqual(span.name, spanName); assert.strictEqual(span.kind, kind); assert.strictEqual( - span.status.code, GrpcPlugin.convertGrpcStatusToSpanStatus(status)); + span.status.code, + GrpcPlugin.convertGrpcStatusToSpanStatus(status) + ); assert.strictEqual(span.attributes[GrpcPlugin.ATTRIBUTE_GRPC_KIND], kind); assert.strictEqual( - span.attributes[GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE], `${status}`); + span.attributes[GrpcPlugin.ATTRIBUTE_GRPC_STATUS_CODE], + `${status}` + ); assert.ok(span.attributes[GrpcPlugin.ATTRIBUTE_GRPC_METHOD]); if (status !== grpcModule.status.OK) { assert.ok(span.attributes[GrpcPlugin.ATTRIBUTE_GRPC_ERROR_NAME]); assert.ok(span.attributes[GrpcPlugin.ATTRIBUTE_GRPC_ERROR_MESSAGE]); } else { - assert.equal(span.status.message, undefined); + assert.strictEqual(span.status.message, undefined); } } function assertStats(testExporter: TestExporter, sentBytes: number) { - assert.equal(testExporter.registeredViews.length, 12); - assert.equal(testExporter.recordedMeasurements.length, 10); + assert.strictEqual(testExporter.registeredViews.length, 12); + assert.strictEqual(testExporter.recordedMeasurements.length, 10); assert.strictEqual( - testExporter.recordedMeasurements[0].measure, - serverStats.GRPC_SERVER_RECEIVED_BYTES_PER_RPC); - assert.equal(testExporter.recordedMeasurements[0].value, 14); - assert.deepStrictEqual( - testExporter.recordedMeasurements[1], - {measure: serverStats.GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC, value: 1}); + testExporter.recordedMeasurements[0].measure, + serverStats.GRPC_SERVER_RECEIVED_BYTES_PER_RPC + ); + assert.strictEqual(testExporter.recordedMeasurements[0].value, 14); + assert.deepStrictEqual(testExporter.recordedMeasurements[1], { + measure: serverStats.GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC, + value: 1, + }); assert.strictEqual( - testExporter.recordedMeasurements[2].measure, - serverStats.GRPC_SERVER_SENT_BYTES_PER_RPC); - assert.equal(testExporter.recordedMeasurements[2].value, 14); - assert.deepStrictEqual( - testExporter.recordedMeasurements[3], - {measure: serverStats.GRPC_SERVER_SENT_MESSAGES_PER_RPC, value: 1}); + testExporter.recordedMeasurements[2].measure, + serverStats.GRPC_SERVER_SENT_BYTES_PER_RPC + ); + assert.strictEqual(testExporter.recordedMeasurements[2].value, 14); + assert.deepStrictEqual(testExporter.recordedMeasurements[3], { + measure: serverStats.GRPC_SERVER_SENT_MESSAGES_PER_RPC, + value: 1, + }); assert.strictEqual( - testExporter.recordedMeasurements[4].measure, - serverStats.GRPC_SERVER_SERVER_LATENCY); + testExporter.recordedMeasurements[4].measure, + serverStats.GRPC_SERVER_SERVER_LATENCY + ); assert.strictEqual( - testExporter.recordedMeasurements[5].measure, - clientStats.GRPC_CLIENT_SENT_BYTES_PER_RPC); - assert.equal(testExporter.recordedMeasurements[5].value, sentBytes); + testExporter.recordedMeasurements[5].measure, + clientStats.GRPC_CLIENT_SENT_BYTES_PER_RPC + ); + assert.strictEqual(testExporter.recordedMeasurements[5].value, sentBytes); assert.strictEqual( - testExporter.recordedMeasurements[6].measure, - clientStats.GRPC_CLIENT_RECEIVED_BYTES_PER_RPC); - assert.equal(testExporter.recordedMeasurements[6].value, 14); - assert.deepStrictEqual( - testExporter.recordedMeasurements[7], - {measure: clientStats.GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC, value: 1}); - assert.deepStrictEqual( - testExporter.recordedMeasurements[8], - {measure: clientStats.GRPC_CLIENT_SENT_MESSAGES_PER_RPC, value: 1}); + testExporter.recordedMeasurements[6].measure, + clientStats.GRPC_CLIENT_RECEIVED_BYTES_PER_RPC + ); + assert.strictEqual(testExporter.recordedMeasurements[6].value, 14); + assert.deepStrictEqual(testExporter.recordedMeasurements[7], { + measure: clientStats.GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC, + value: 1, + }); + assert.deepStrictEqual(testExporter.recordedMeasurements[8], { + measure: clientStats.GRPC_CLIENT_SENT_MESSAGES_PER_RPC, + value: 1, + }); assert.strictEqual( - testExporter.recordedMeasurements[9].measure, - clientStats.GRPC_CLIENT_ROUNDTRIP_LATENCY); + testExporter.recordedMeasurements[9].measure, + clientStats.GRPC_CLIENT_ROUNDTRIP_LATENCY + ); assert.ok(testExporter.recordedMeasurements[9].value > 0); } @@ -420,171 +471,183 @@ describe('GrpcPlugin() ', function() { assert.strictEqual(targetSpan.traceId, sourceSpan.traceId); assert.strictEqual(targetSpan.parentSpanId, sourceSpan.id); assert.strictEqual( - targetSpan.spanContext.options, sourceSpan.spanContext.options); + targetSpan.spanContext.options, + sourceSpan.spanContext.options + ); assert.notStrictEqual(targetSpan.id, sourceSpan.id); } - methodList.map((method) => { - describe( - `Test automatic tracing for grpc remote method ${method.description}`, - () => { - it(`should create a rootSpan for client and for server - ${ - method.description}`, - async () => { - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); - const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; - const args = [client, method.request]; - await method.method.apply(this, args) - .then( - (result: TestRequestResponse|TestRequestResponse[]) => { - assert.ok(checkEqual(result)(method.result)); - assert.strictEqual( - rootSpanVerifier.endedRootSpans.length, 2); - - const serverRoot = rootSpanVerifier.endedRootSpans[0]; - const clientRoot = rootSpanVerifier.endedRootSpans[1]; - assertSpan( - serverRoot, spanName, SpanKind.SERVER, - grpcModule.status.OK); - assertSpan( - clientRoot, spanName, SpanKind.CLIENT, - grpcModule.status.OK); - if (method.method === grpcClient.unaryMethod) { - assertStats(testExporter, 107); - } - assertPropagation(clientRoot, serverRoot); - }); - }); - - it(`should create a rootSpan for client and for server with tag context- ${ - method.description}`, - () => { - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); - const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; - const args = [client, method.request]; - - const tags = new TagMap(); - tags.set({name: 'testKey1'}, {value: 'value1'}); - tags.set({name: 'testKey2'}, {value: 'value2'}); - return globalStats.withTagContext(tags, async () => { - await method.method.apply(this, args) - .then( - (result: TestRequestResponse| - TestRequestResponse[]) => { - assert.ok(checkEqual(result)(method.result)); - assert.strictEqual( - rootSpanVerifier.endedRootSpans.length, 2); - - const serverRoot = - rootSpanVerifier.endedRootSpans[0]; - const clientRoot = - rootSpanVerifier.endedRootSpans[1]; - assertSpan( - serverRoot, spanName, SpanKind.SERVER, - grpcModule.status.OK); - assertSpan( - clientRoot, spanName, SpanKind.CLIENT, - grpcModule.status.OK); - if (method.method === grpcClient.unaryMethod) { - assertStats(testExporter, 170); - } - assertPropagation(clientRoot, serverRoot); - assert.deepStrictEqual( - globalStats.getCurrentTagContext(), tags); - }); - }); - }); - - it(`should create a childSpan for client and rootSpan for server - ${ - method.description}`, - () => { - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); - const options = {name: 'TestRootSpan'}; - const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; - let serverRoot: Span; - return tracer.startRootSpan(options, async (root: Span) => { - assert.strictEqual(root.name, options.name); - const args = [client, method.request]; - await method.method.apply(this, args) - .then( - (result: TestRequestResponse| - TestRequestResponse[]) => { - assert.ok(checkEqual(result)(method.result)); - assert.strictEqual( - rootSpanVerifier.endedRootSpans.length, 1); - - serverRoot = rootSpanVerifier.endedRootSpans[0]; - assertSpan( - serverRoot, spanName, SpanKind.SERVER, - grpcModule.status.OK); - }); - root.end(); - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 2); - const clientChild = - rootSpanVerifier.endedRootSpans[1].spans[0]; - assertSpan( - clientChild, spanName, SpanKind.CLIENT, - grpcModule.status.OK); - // propagation - assertPropagation(clientChild, serverRoot); - }); - }); - - it(`should create a childSpan for client and rootSpan for server with tag context - ${ - method.description}`, - () => { - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); - const options = {name: 'TestRootSpan'}; - const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; - let serverRoot: Span; - const tags = new TagMap(); - tags.set({name: 'testKey1'}, {value: 'value1'}); - tags.set({name: 'testKey2'}, {value: 'value2'}); - return globalStats.withTagContext(tags, async () => { - return tracer.startRootSpan(options, async (root: Span) => { - assert.strictEqual(root.name, options.name); - const args = [client, method.request]; - await method.method.apply(this, args) - .then( - (result: TestRequestResponse| - TestRequestResponse[]) => { - assert.ok(checkEqual(result)(method.result)); - assert.strictEqual( - rootSpanVerifier.endedRootSpans.length, 1); - - serverRoot = rootSpanVerifier.endedRootSpans[0]; - assertSpan( - serverRoot, spanName, SpanKind.SERVER, - grpcModule.status.OK); - }); - root.end(); - assert.strictEqual( - rootSpanVerifier.endedRootSpans.length, 2); - const clientChild = - rootSpanVerifier.endedRootSpans[1].spans[0]; - assertSpan( - clientChild, spanName, SpanKind.CLIENT, - grpcModule.status.OK); - // propagation - assertPropagation(clientChild, serverRoot); - assert.deepStrictEqual( - globalStats.getCurrentTagContext(), tags); - }); - }); - }); + methodList.map(method => { + describe(`Test automatic tracing for grpc remote method ${ + method.description + }`, () => { + it(`should create a rootSpan for client and for server - ${ + method.description + }`, async () => { + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); + const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; + const args = [client, method.request]; + await method.method + .apply(this, args) + .then((result: TestRequestResponse | TestRequestResponse[]) => { + assert.ok(checkEqual(result)(method.result)); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 2); + + const serverRoot = rootSpanVerifier.endedRootSpans[0]; + const clientRoot = rootSpanVerifier.endedRootSpans[1]; + assertSpan( + serverRoot, + spanName, + SpanKind.SERVER, + grpcModule.status.OK + ); + assertSpan( + clientRoot, + spanName, + SpanKind.CLIENT, + grpcModule.status.OK + ); + if (method.method === grpcClient.unaryMethod) { + assertStats(testExporter, 107); + } + assertPropagation(clientRoot, serverRoot); + }); + }); + + it(`should create a rootSpan for client and for server with tag context- ${ + method.description + }`, () => { + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); + const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; + const args = [client, method.request]; + + const tags = new TagMap(); + tags.set({ name: 'testKey1' }, { value: 'value1' }); + tags.set({ name: 'testKey2' }, { value: 'value2' }); + return globalStats.withTagContext(tags, async () => { + await method.method + .apply(this, args) + .then((result: TestRequestResponse | TestRequestResponse[]) => { + assert.ok(checkEqual(result)(method.result)); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 2); + + const serverRoot = rootSpanVerifier.endedRootSpans[0]; + const clientRoot = rootSpanVerifier.endedRootSpans[1]; + assertSpan( + serverRoot, + spanName, + SpanKind.SERVER, + grpcModule.status.OK + ); + assertSpan( + clientRoot, + spanName, + SpanKind.CLIENT, + grpcModule.status.OK + ); + if (method.method === grpcClient.unaryMethod) { + assertStats(testExporter, 170); + } + assertPropagation(clientRoot, serverRoot); + assert.deepStrictEqual(globalStats.getCurrentTagContext(), tags); + }); }); - }); + }); + it(`should create a childSpan for client and rootSpan for server - ${ + method.description + }`, () => { + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); + const options = { name: 'TestRootSpan' }; + const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; + let serverRoot: Span; + return tracer.startRootSpan(options, async (root: Span) => { + assert.strictEqual(root.name, options.name); + const args = [client, method.request]; + await method.method + .apply(this, args) + .then((result: TestRequestResponse | TestRequestResponse[]) => { + assert.ok(checkEqual(result)(method.result)); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 1); + + serverRoot = rootSpanVerifier.endedRootSpans[0]; + assertSpan( + serverRoot, + spanName, + SpanKind.SERVER, + grpcModule.status.OK + ); + }); + root.end(); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 2); + const clientChild = rootSpanVerifier.endedRootSpans[1].spans[0]; + assertSpan( + clientChild, + spanName, + SpanKind.CLIENT, + grpcModule.status.OK + ); + // propagation + assertPropagation(clientChild, serverRoot); + }); + }); + + it(`should create a childSpan for client and rootSpan for server with tag context - ${ + method.description + }`, () => { + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); + const options = { name: 'TestRootSpan' }; + const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; + let serverRoot: Span; + const tags = new TagMap(); + tags.set({ name: 'testKey1' }, { value: 'value1' }); + tags.set({ name: 'testKey2' }, { value: 'value2' }); + return globalStats.withTagContext(tags, async () => { + return tracer.startRootSpan(options, async (root: Span) => { + assert.strictEqual(root.name, options.name); + const args = [client, method.request]; + await method.method + .apply(this, args) + .then((result: TestRequestResponse | TestRequestResponse[]) => { + assert.ok(checkEqual(result)(method.result)); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 1); + + serverRoot = rootSpanVerifier.endedRootSpans[0]; + assertSpan( + serverRoot, + spanName, + SpanKind.SERVER, + grpcModule.status.OK + ); + }); + root.end(); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 2); + const clientChild = rootSpanVerifier.endedRootSpans[1].spans[0]; + assertSpan( + clientChild, + spanName, + SpanKind.CLIENT, + grpcModule.status.OK + ); + // propagation + assertPropagation(clientChild, serverRoot); + assert.deepStrictEqual(globalStats.getCurrentTagContext(), tags); + }); + }); + }); + }); + }); // Returns a request with an error code (value <= 16 (Max Grpc Status Code)) // inserted - const insertError = (request: TestRequestResponse|TestRequestResponse[]) => - (code: number) => (request instanceof Array) ? - request.splice(0, 0, {num: code}) && request.slice(0, request.length) : - {num: code}; - - - methodList.map((method) => { + const insertError = ( + request: TestRequestResponse | TestRequestResponse[] + ) => (code: number) => + request instanceof Array + ? request.splice(0, 0, { num: code }) && request.slice(0, request.length) + : { num: code }; + + methodList.map(method => { describe(`Test error raising for grpc remote ${method.description}`, () => { // Iterate over all error status code Object.keys(grpcModule.status).map((key: string) => { @@ -592,60 +655,58 @@ describe('GrpcPlugin() ', function() { const errorCode = Number(grpcModule.status[key as any]); if (errorCode > grpcModule.status.OK) { it(`should raise an error for client/server rootSpans - ${ - method.description} - status = ${key}`, - async () => { - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); - const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; - const errRequest = (method.request instanceof Array) ? - method.request.slice(0, method.request.length) : - method.request; - const args = [client, insertError(errRequest)(errorCode)]; - await method.method.apply(this, args) - .catch((err: grpcModule.ServiceError) => { - assert.strictEqual( - rootSpanVerifier.endedRootSpans.length, 2); - - const serverRoot = rootSpanVerifier.endedRootSpans[0]; - const clientRoot = rootSpanVerifier.endedRootSpans[1]; - assertSpan( - serverRoot, spanName, SpanKind.SERVER, errorCode); - assertSpan( - clientRoot, spanName, SpanKind.CLIENT, errorCode); - assertPropagation(clientRoot, serverRoot); - }); - }); + method.description + } - status = ${key}`, async () => { + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); + const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; + const errRequest = + method.request instanceof Array + ? method.request.slice(0, method.request.length) + : method.request; + const args = [client, insertError(errRequest)(errorCode)]; + await method.method + .apply(this, args) + .catch((err: grpcModule.ServiceError) => { + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 2); + + const serverRoot = rootSpanVerifier.endedRootSpans[0]; + const clientRoot = rootSpanVerifier.endedRootSpans[1]; + assertSpan(serverRoot, spanName, SpanKind.SERVER, errorCode); + assertSpan(clientRoot, spanName, SpanKind.CLIENT, errorCode); + assertPropagation(clientRoot, serverRoot); + }); + }); it(`should raise an error for client childSpan/server rootSpan - ${ - method.description} - status = ${key}`, - () => { - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); - const options = {name: 'TestRootSpan'}; - const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; - let serverRoot: Span; - return tracer.startRootSpan(options, async (root: Span) => { - assert.strictEqual(root.name, options.name); - const errRequest = (method.request instanceof Array) ? - method.request.slice(0, method.request.length) : - method.request; - const args = [client, insertError(errRequest)(errorCode)]; - await method.method.apply(this, args) - .catch((err: grpcModule.ServiceError) => { - assert.strictEqual( - rootSpanVerifier.endedRootSpans.length, 1); - - serverRoot = rootSpanVerifier.endedRootSpans[0]; - assertSpan( - serverRoot, spanName, SpanKind.SERVER, errorCode); - }); - root.end(); - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 2); - const clientChild = - rootSpanVerifier.endedRootSpans[1].spans[0]; - assertSpan(clientChild, spanName, SpanKind.CLIENT, errorCode); - // propagation - assertPropagation(clientChild, serverRoot); - }); - }); + method.description + } - status = ${key}`, () => { + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); + const options = { name: 'TestRootSpan' }; + const spanName = `grpc.pkg_test.GrpcTester/${method.methodName}`; + let serverRoot: Span; + return tracer.startRootSpan(options, async (root: Span) => { + assert.strictEqual(root.name, options.name); + const errRequest = + method.request instanceof Array + ? method.request.slice(0, method.request.length) + : method.request; + const args = [client, insertError(errRequest)(errorCode)]; + await method.method + .apply(this, args) + .catch((err: grpcModule.ServiceError) => { + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 1); + + serverRoot = rootSpanVerifier.endedRootSpans[0]; + assertSpan(serverRoot, spanName, SpanKind.SERVER, errorCode); + }); + root.end(); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 2); + const clientChild = rootSpanVerifier.endedRootSpans[1].spans[0]; + assertSpan(clientChild, spanName, SpanKind.CLIENT, errorCode); + // propagation + assertPropagation(clientChild, serverRoot); + }); + }); } }); }); @@ -655,7 +716,7 @@ describe('GrpcPlugin() ', function() { const spanContext = { traceId: '3ad17e665f514aabb896341f670179ed', spanId: '3aaeb440a89d9e82', - options: 0x1 + options: 0x1, }; it('should set span context', () => { @@ -669,19 +730,45 @@ describe('GrpcPlugin() ', function() { const metadata = new grpcModule.Metadata(); it('should return null when span context is not set', () => { const actualSpanContext = GrpcPlugin.getSpanContext(metadata); - assert.equal(actualSpanContext, null); + assert.strictEqual(actualSpanContext, null); }); it('should return valid span context', () => { const buffer = Buffer.from([ - 0x00, 0x00, 0xdf, 0x6a, 0x20, 0x38, 0xfa, 0x78, 0xc4, 0xcd, - 0x42, 0x20, 0x91, 0x26, 0x24, 0x9c, 0x31, 0xc7, 0x01, 0xc2, - 0xb7, 0xce, 0x7a, 0x57, 0x2a, 0x37, 0xc6, 0x02, 0x01 + 0x00, + 0x00, + 0xdf, + 0x6a, + 0x20, + 0x38, + 0xfa, + 0x78, + 0xc4, + 0xcd, + 0x42, + 0x20, + 0x91, + 0x26, + 0x24, + 0x9c, + 0x31, + 0xc7, + 0x01, + 0xc2, + 0xb7, + 0xce, + 0x7a, + 0x57, + 0x2a, + 0x37, + 0xc6, + 0x02, + 0x01, ]); const expectedSpanContext = { traceId: 'df6a2038fa78c4cd42209126249c31c7', spanId: 'c2b7ce7a572a37c6', - options: 1 + options: 1, }; metadata.set(GRPC_TRACE_KEY, buffer); const actualSpanContext = GrpcPlugin.getSpanContext(metadata); @@ -690,9 +777,35 @@ describe('GrpcPlugin() ', function() { it('should return null for unsupported version', () => { const buffer = Buffer.from([ - 0x66, 0x64, 0xdf, 0x6a, 0x20, 0x38, 0xfa, 0x78, 0xc4, 0xcd, - 0x42, 0x20, 0x91, 0x26, 0x24, 0x9c, 0x31, 0xc7, 0x01, 0xc2, - 0xb7, 0xce, 0x7a, 0x57, 0x2a, 0x37, 0xc6, 0x02, 0x01 + 0x66, + 0x64, + 0xdf, + 0x6a, + 0x20, + 0x38, + 0xfa, + 0x78, + 0xc4, + 0xcd, + 0x42, + 0x20, + 0x91, + 0x26, + 0x24, + 0x9c, + 0x31, + 0xc7, + 0x01, + 0xc2, + 0xb7, + 0xce, + 0x7a, + 0x57, + 0x2a, + 0x37, + 0xc6, + 0x02, + 0x01, ]); metadata.set(GRPC_TRACE_KEY, buffer); const actualSpanContext = GrpcPlugin.getSpanContext(metadata); @@ -701,9 +814,35 @@ describe('GrpcPlugin() ', function() { it('should return null when unexpected trace ID offset', () => { const buffer = Buffer.from([ - 0x00, 0x04, 0xdf, 0x6a, 0x20, 0x38, 0xfa, 0x78, 0xc4, 0xcd, - 0x42, 0x20, 0x91, 0x26, 0x24, 0x9c, 0x31, 0xc7, 0x01, 0xc2, - 0xb7, 0xce, 0x7a, 0x57, 0x2a, 0x37, 0xc6, 0x02, 0x01 + 0x00, + 0x04, + 0xdf, + 0x6a, + 0x20, + 0x38, + 0xfa, + 0x78, + 0xc4, + 0xcd, + 0x42, + 0x20, + 0x91, + 0x26, + 0x24, + 0x9c, + 0x31, + 0xc7, + 0x01, + 0xc2, + 0xb7, + 0xce, + 0x7a, + 0x57, + 0x2a, + 0x37, + 0xc6, + 0x02, + 0x01, ]); metadata.set(GRPC_TRACE_KEY, buffer); const actualSpanContext = GrpcPlugin.getSpanContext(metadata); @@ -712,9 +851,35 @@ describe('GrpcPlugin() ', function() { it('should return null when unexpected span ID offset', () => { const buffer = Buffer.from([ - 0x00, 0x00, 0xdf, 0x6a, 0x20, 0x38, 0xfa, 0x78, 0xc4, 0xcd, - 0x42, 0x20, 0x91, 0x26, 0x24, 0x9c, 0x31, 0xc7, 0x03, 0xc2, - 0xb7, 0xce, 0x7a, 0x57, 0x2a, 0x37, 0xc6, 0x02, 0x01 + 0x00, + 0x00, + 0xdf, + 0x6a, + 0x20, + 0x38, + 0xfa, + 0x78, + 0xc4, + 0xcd, + 0x42, + 0x20, + 0x91, + 0x26, + 0x24, + 0x9c, + 0x31, + 0xc7, + 0x03, + 0xc2, + 0xb7, + 0xce, + 0x7a, + 0x57, + 0x2a, + 0x37, + 0xc6, + 0x02, + 0x01, ]); metadata.set(GRPC_TRACE_KEY, buffer); const actualSpanContext = GrpcPlugin.getSpanContext(metadata); @@ -723,9 +888,35 @@ describe('GrpcPlugin() ', function() { it('should return null when unexpected options offset', () => { const buffer = Buffer.from([ - 0x00, 0x00, 0xdf, 0x6a, 0x20, 0x38, 0xfa, 0x78, 0xc4, 0xcd, - 0x42, 0x20, 0x91, 0x26, 0x24, 0x9c, 0x31, 0xc7, 0x03, 0xc2, - 0xb7, 0xce, 0x7a, 0x57, 0x2a, 0x37, 0xc6, 0x00, 0x01 + 0x00, + 0x00, + 0xdf, + 0x6a, + 0x20, + 0x38, + 0xfa, + 0x78, + 0xc4, + 0xcd, + 0x42, + 0x20, + 0x91, + 0x26, + 0x24, + 0x9c, + 0x31, + 0xc7, + 0x03, + 0xc2, + 0xb7, + 0xce, + 0x7a, + 0x57, + 0x2a, + 0x37, + 0xc6, + 0x00, + 0x01, ]); metadata.set(GRPC_TRACE_KEY, buffer); const actualSpanContext = GrpcPlugin.getSpanContext(metadata); @@ -733,8 +924,17 @@ describe('GrpcPlugin() ', function() { }); it('should return null when invalid input i.e. truncated', () => { - const buffer = - Buffer.from([0x00, 0x00, 0xdf, 0x6a, 0x20, 0x38, 0xfa, 0x78, 0xc4]); + const buffer = Buffer.from([ + 0x00, + 0x00, + 0xdf, + 0x6a, + 0x20, + 0x38, + 0xfa, + 0x78, + 0xc4, + ]); metadata.set(GRPC_TRACE_KEY, buffer); const actualSpanContext = GrpcPlugin.getSpanContext(metadata); assert.deepStrictEqual(actualSpanContext, null); @@ -745,13 +945,13 @@ describe('GrpcPlugin() ', function() { const metadata = new grpcModule.Metadata(); const multipleTagMap = new TagMap(); - multipleTagMap.set({name: 'k1'}, {value: 'v1'}); - multipleTagMap.set({name: 'k2'}, {value: 'v2'}); + multipleTagMap.set({ name: 'k1' }, { value: 'v1' }); + multipleTagMap.set({ name: 'k2' }, { value: 'v2' }); it('should set TagMap', () => { GrpcPlugin.setTagContext(metadata, multipleTagMap); const actualTagMap = GrpcPlugin.getTagContext(metadata); - assert.equal(actualTagMap!.tags.size, 2); + assert.strictEqual(actualTagMap!.tags.size, 2); assert.deepStrictEqual(actualTagMap!.tags, multipleTagMap.tags); }); }); @@ -760,26 +960,47 @@ describe('GrpcPlugin() ', function() { const metadata = new grpcModule.Metadata(); it('should return null when TagMap is not set', () => { const actualTagMap = GrpcPlugin.getTagContext(metadata); - assert.equal(actualTagMap, null); + assert.strictEqual(actualTagMap, null); }); it('should return valid TagMap', () => { const buffer = Buffer.from([ - 0x00, 0x00, 0x02, 0x6b, 0x31, 0x02, 0x76, 0x31, 0x00, 0x02, 0x6b, 0x32, - 0x02, 0x76, 0x32 + 0x00, + 0x00, + 0x02, + 0x6b, + 0x31, + 0x02, + 0x76, + 0x31, + 0x00, + 0x02, + 0x6b, + 0x32, + 0x02, + 0x76, + 0x32, ]); const expectedTags = new TagMap(); - expectedTags.set({name: 'k1'}, {value: 'v1'}); - expectedTags.set({name: 'k2'}, {value: 'v2'}); + expectedTags.set({ name: 'k1' }, { value: 'v1' }); + expectedTags.set({ name: 'k2' }, { value: 'v2' }); metadata.set(GRPC_TAGS_KEY, buffer); const actualTagMap = GrpcPlugin.getTagContext(metadata); - assert.equal(actualTagMap!.tags.size, 2); + assert.strictEqual(actualTagMap!.tags.size, 2); assert.deepStrictEqual(actualTagMap!.tags, expectedTags.tags); }); it('should return null when unexpected tagKey', () => { - const buffer = - Buffer.from([0x01, 0x00, 0x02, 0x6b, 0x31, 0x02, 0x76, 0x31]); + const buffer = Buffer.from([ + 0x01, + 0x00, + 0x02, + 0x6b, + 0x31, + 0x02, + 0x76, + 0x31, + ]); metadata.set(GRPC_TAGS_KEY, buffer); const actualTagMap = GrpcPlugin.getTagContext(metadata); assert.deepStrictEqual(actualTagMap, null); diff --git a/packages/opencensus-instrumentation-http/package-lock.json b/packages/opencensus-instrumentation-http/package-lock.json index 17c824fc4..f32b0d0e2 100644 --- a/packages/opencensus-instrumentation-http/package-lock.json +++ b/packages/opencensus-instrumentation-http/package-lock.json @@ -179,9 +179,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -242,58 +242,6 @@ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -447,16 +395,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -539,8 +477,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -975,37 +912,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -1036,21 +973,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1139,29 +1061,42 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } } } }, @@ -1381,15 +1316,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2293,6 +2223,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "propagate": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/propagate/-/propagate-1.0.0.tgz", @@ -2369,9 +2304,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2404,11 +2339,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2442,9 +2377,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2587,17 +2522,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2833,29 +2768,25 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" }, "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - }, "semver": { "version": "5.7.0", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", @@ -3030,9 +2961,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-instrumentation-http/package.json b/packages/opencensus-instrumentation-http/package.json index f379e5d05..95f126f8b 100644 --- a/packages/opencensus-instrumentation-http/package.json +++ b/packages/opencensus-instrumentation-http/package.json @@ -55,7 +55,7 @@ "@types/semver": "^6.0.0", "@types/shimmer": "^1.0.1", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nock": "^10.0.0", "nyc": "^14.0.0", diff --git a/packages/opencensus-instrumentation-http/src/http-stats.ts b/packages/opencensus-instrumentation-http/src/http-stats.ts index 22a070c46..8fee88d3a 100644 --- a/packages/opencensus-instrumentation-http/src/http-stats.ts +++ b/packages/opencensus-instrumentation-http/src/http-stats.ts @@ -14,15 +14,24 @@ * limitations under the License. */ -import {AggregationType, globalStats, Measure, MeasureUnit, Stats, View} from '@opencensus/core'; +import { + AggregationType, + globalStats, + Measure, + MeasureUnit, + Stats, + View, +} from '@opencensus/core'; /** * {@link Measure} for the client-side total bytes sent in request body (not * including headers). This is uncompressed bytes. */ export const HTTP_CLIENT_SENT_BYTES: Measure = globalStats.createMeasureInt64( - 'opencensus.io/http/client/sent_bytes', MeasureUnit.BYTE, - 'Client-side total bytes sent in request body (uncompressed)'); + 'opencensus.io/http/client/sent_bytes', + MeasureUnit.BYTE, + 'Client-side total bytes sent in request body (uncompressed)' +); /** * {@link Measure} for the client-side total bytes received in response @@ -31,27 +40,31 @@ export const HTTP_CLIENT_SENT_BYTES: Measure = globalStats.createMeasureInt64( * the Content-Length header. This is uncompressed bytes. Responses with no * body should record 0 for this value. */ -export const HTTP_CLIENT_RECEIVED_BYTES: Measure = - globalStats.createMeasureInt64( - 'opencensus.io/http/client/received_bytes', MeasureUnit.BYTE, - 'Client-side total bytes received in response bodies (uncompressed)'); +export const HTTP_CLIENT_RECEIVED_BYTES: Measure = globalStats.createMeasureInt64( + 'opencensus.io/http/client/received_bytes', + MeasureUnit.BYTE, + 'Client-side total bytes received in response bodies (uncompressed)' +); /** * {@link Measure} for the client-side time between first byte of request * headers sent to last byte of response received, or terminal error. */ export const HTTP_CLIENT_ROUNDTRIP_LATENCY: Measure = globalStats.createMeasureDouble( - 'opencensus.io/http/client/roundtrip_latency', MeasureUnit.MS, - 'Client-side time between first byte of request headers sent to last byte of response received, or terminal error'); + 'opencensus.io/http/client/roundtrip_latency', + MeasureUnit.MS, + 'Client-side time between first byte of request headers sent to last byte of response received, or terminal error' +); /** * {@link Measure} for the server-side total bytes received in request body * (not including headers). This is uncompressed bytes. */ -export const HTTP_SERVER_RECEIVED_BYTES: Measure = - globalStats.createMeasureInt64( - 'opencensus.io/http/server/received_bytes', MeasureUnit.BYTE, - 'Server-side total bytes received in request body (uncompressed)'); +export const HTTP_SERVER_RECEIVED_BYTES: Measure = globalStats.createMeasureInt64( + 'opencensus.io/http/server/received_bytes', + MeasureUnit.BYTE, + 'Server-side total bytes received in request body (uncompressed)' +); /** * {@link Measure} for the server-side total bytes sent in response bodies @@ -61,25 +74,29 @@ export const HTTP_SERVER_RECEIVED_BYTES: Measure = * body should record 0 for this value. */ export const HTTP_SERVER_SENT_BYTES: Measure = globalStats.createMeasureInt64( - 'opencensus.io/http/server/sent_bytes', MeasureUnit.BYTE, - 'Server-side total bytes sent in response bodies (uncompressed)'); + 'opencensus.io/http/server/sent_bytes', + MeasureUnit.BYTE, + 'Server-side total bytes sent in response bodies (uncompressed)' +); /** * {@link Measure} for the server-side time between first byte of request * headers received to last byte of response sent, or terminal error. */ export const HTTP_SERVER_LATENCY: Measure = globalStats.createMeasureDouble( - 'opencensus.io/http/server/server_latency', MeasureUnit.MS, - 'Server-side time between first byte of request headers received to last byte of response sent, or terminal error'); + 'opencensus.io/http/server/server_latency', + MeasureUnit.MS, + 'Server-side time between first byte of request headers received to last byte of response sent, or terminal error' +); /** {@link TagKey} for the value of the client-side HTTP host header. */ export const HTTP_CLIENT_HOST = { - name: 'http_client_host' + name: 'http_client_host', }; /** {@link TagKey} for the value of the server-side HTTP host header. */ export const HTTP_SERVER_HOST = { - name: 'http_server_host' + name: 'http_server_host', }; /** @@ -88,7 +105,7 @@ export const HTTP_SERVER_HOST = { * use "error" as the {@code TagValue}. */ export const HTTP_CLIENT_STATUS = { - name: 'http_client_status' + name: 'http_client_status', }; /** @@ -97,7 +114,7 @@ export const HTTP_CLIENT_STATUS = { * use "error" as the {@code TagValue}. */ export const HTTP_SERVER_STATUS = { - name: 'http_server_status' + name: 'http_server_status', }; /** @@ -105,7 +122,7 @@ export const HTTP_SERVER_STATUS = { * the request. */ export const HTTP_CLIENT_PATH = { - name: 'http_client_path' + name: 'http_client_path', }; /** @@ -113,7 +130,7 @@ export const HTTP_CLIENT_PATH = { * the request. */ export const HTTP_SERVER_PATH = { - name: 'http_server_path' + name: 'http_server_path', }; /** @@ -121,7 +138,7 @@ export const HTTP_SERVER_PATH = { * (GET, POST, etc.). */ export const HTTP_CLIENT_METHOD = { - name: 'http_client_method' + name: 'http_client_method', }; /** @@ -129,7 +146,7 @@ export const HTTP_CLIENT_METHOD = { * (GET, POST, etc.). */ export const HTTP_SERVER_METHOD = { - name: 'http_server_method' + name: 'http_server_method', }; /** @@ -137,87 +154,156 @@ export const HTTP_SERVER_METHOD = { * URL, of a handler that processed the request. */ export const HTTP_SERVER_ROUTE = { - name: 'http_server_route' + name: 'http_server_route', }; const SIZE_DISTRIBUTION: number[] = [ - 1024, 2048, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, - 268435456, 1073741824, 4294967296 + 1024, + 2048, + 4096, + 16384, + 65536, + 262144, + 1048576, + 4194304, + 16777216, + 67108864, + 268435456, + 1073741824, + 4294967296, ]; const LATENCY_DISTRIBUTION: number[] = [ - 1, 2, 3, 4, 5, 6, 8, 10, 13, 16, 20, 25, - 30, 40, 50, 65, 80, 100, 130, 160, 200, 250, 300, 400, - 500, 650, 800, 1000, 2000, 5000, 10000, 20000, 50000, 100000 + 1, + 2, + 3, + 4, + 5, + 6, + 8, + 10, + 13, + 16, + 20, + 25, + 30, + 40, + 50, + 65, + 80, + 100, + 130, + 160, + 200, + 250, + 300, + 400, + 500, + 650, + 800, + 1000, + 2000, + 5000, + 10000, + 20000, + 50000, + 100000, ]; /** {@link View} for count of client-side HTTP requests completed. */ const HTTP_CLIENT_COMPLETED_COUNT_VIEW = globalStats.createView( - 'opencensus.io/http/client/completed_count', HTTP_CLIENT_ROUNDTRIP_LATENCY, - AggregationType.COUNT, [HTTP_CLIENT_METHOD, HTTP_CLIENT_STATUS], - 'Count of client-side HTTP requests completed'); + 'opencensus.io/http/client/completed_count', + HTTP_CLIENT_ROUNDTRIP_LATENCY, + AggregationType.COUNT, + [HTTP_CLIENT_METHOD, HTTP_CLIENT_STATUS], + 'Count of client-side HTTP requests completed' +); /** {@link View} for size distribution of client-side HTTP request body. */ const HTTP_CLIENT_SENT_BYTES_VIEW = globalStats.createView( - 'opencensus.io/http/client/sent_bytes', HTTP_CLIENT_SENT_BYTES, - AggregationType.DISTRIBUTION, [HTTP_CLIENT_METHOD, HTTP_CLIENT_STATUS], - 'Size distribution of client-side HTTP request body', SIZE_DISTRIBUTION); + 'opencensus.io/http/client/sent_bytes', + HTTP_CLIENT_SENT_BYTES, + AggregationType.DISTRIBUTION, + [HTTP_CLIENT_METHOD, HTTP_CLIENT_STATUS], + 'Size distribution of client-side HTTP request body', + SIZE_DISTRIBUTION +); /** {@link View} for size distribution of client-side HTTP response body. */ const HTTP_CLIENT_RECEIVED_BYTES_VIEW = globalStats.createView( - 'opencensus.io/http/client/received_bytes', HTTP_CLIENT_RECEIVED_BYTES, - AggregationType.DISTRIBUTION, [HTTP_CLIENT_METHOD, HTTP_CLIENT_STATUS], - 'Size distribution of client-side HTTP response body', SIZE_DISTRIBUTION); + 'opencensus.io/http/client/received_bytes', + HTTP_CLIENT_RECEIVED_BYTES, + AggregationType.DISTRIBUTION, + [HTTP_CLIENT_METHOD, HTTP_CLIENT_STATUS], + 'Size distribution of client-side HTTP response body', + SIZE_DISTRIBUTION +); /** * {@link View} for roundtrip latency distribution of client-side HTTP requests. */ const HTTP_CLIENT_ROUNDTRIP_LATENCY_VIEW = globalStats.createView( - 'opencensus.io/http/client/roundtrip_latency', - HTTP_CLIENT_ROUNDTRIP_LATENCY, AggregationType.DISTRIBUTION, - [HTTP_CLIENT_METHOD, HTTP_CLIENT_STATUS], - 'Roundtrip latency distribution of client-side HTTP requests', - LATENCY_DISTRIBUTION); + 'opencensus.io/http/client/roundtrip_latency', + HTTP_CLIENT_ROUNDTRIP_LATENCY, + AggregationType.DISTRIBUTION, + [HTTP_CLIENT_METHOD, HTTP_CLIENT_STATUS], + 'Roundtrip latency distribution of client-side HTTP requests', + LATENCY_DISTRIBUTION +); /** {@link View} for count of server-side HTTP requests serving completed. */ const HTTP_SERVER_COMPLETED_COUNT_VIEW = globalStats.createView( - 'opencensus.io/http/server/completed_count', HTTP_SERVER_LATENCY, - AggregationType.COUNT, - [HTTP_SERVER_METHOD, HTTP_SERVER_ROUTE, HTTP_SERVER_STATUS], - 'Count of HTTP server-side requests serving completed'); + 'opencensus.io/http/server/completed_count', + HTTP_SERVER_LATENCY, + AggregationType.COUNT, + [HTTP_SERVER_METHOD, HTTP_SERVER_ROUTE, HTTP_SERVER_STATUS], + 'Count of HTTP server-side requests serving completed' +); /** {@link View} for size distribution of server-side HTTP request body. */ const HTTP_SERVER_RECEIVED_BYTES_VIEW = globalStats.createView( - 'opencensus.io/http/server/received_bytes', HTTP_SERVER_RECEIVED_BYTES, - AggregationType.DISTRIBUTION, - [HTTP_SERVER_METHOD, HTTP_SERVER_ROUTE, HTTP_SERVER_STATUS], - 'Size distribution of server-side HTTP request body', SIZE_DISTRIBUTION); + 'opencensus.io/http/server/received_bytes', + HTTP_SERVER_RECEIVED_BYTES, + AggregationType.DISTRIBUTION, + [HTTP_SERVER_METHOD, HTTP_SERVER_ROUTE, HTTP_SERVER_STATUS], + 'Size distribution of server-side HTTP request body', + SIZE_DISTRIBUTION +); /** {@link View} for size distribution of server-side HTTP response body. */ const HTTP_SERVER_SENT_BYTES_VIEW = globalStats.createView( - 'opencensus.io/http/server/sent_bytes', HTTP_SERVER_SENT_BYTES, - AggregationType.DISTRIBUTION, - [HTTP_SERVER_METHOD, HTTP_SERVER_ROUTE, HTTP_SERVER_STATUS], - 'Size distribution of server-side HTTP response body', SIZE_DISTRIBUTION); + 'opencensus.io/http/server/sent_bytes', + HTTP_SERVER_SENT_BYTES, + AggregationType.DISTRIBUTION, + [HTTP_SERVER_METHOD, HTTP_SERVER_ROUTE, HTTP_SERVER_STATUS], + 'Size distribution of server-side HTTP response body', + SIZE_DISTRIBUTION +); /** * {@link View} for latency distribution of server-side HTTP requests serving. */ const HTTP_SERVER_LATENCY_VIEW = globalStats.createView( - 'opencensus.io/http/server/server_latency', HTTP_SERVER_LATENCY, - AggregationType.DISTRIBUTION, - [HTTP_SERVER_METHOD, HTTP_SERVER_ROUTE, HTTP_SERVER_STATUS], - 'Latency distribution of server-side HTTP requests serving', - LATENCY_DISTRIBUTION); + 'opencensus.io/http/server/server_latency', + HTTP_SERVER_LATENCY, + AggregationType.DISTRIBUTION, + [HTTP_SERVER_METHOD, HTTP_SERVER_ROUTE, HTTP_SERVER_STATUS], + 'Latency distribution of server-side HTTP requests serving', + LATENCY_DISTRIBUTION +); const HTTP_BASIC_SERVER_VIEWS: View[] = [ - HTTP_SERVER_COMPLETED_COUNT_VIEW, HTTP_SERVER_RECEIVED_BYTES_VIEW, - HTTP_SERVER_SENT_BYTES_VIEW, HTTP_SERVER_LATENCY_VIEW + HTTP_SERVER_COMPLETED_COUNT_VIEW, + HTTP_SERVER_RECEIVED_BYTES_VIEW, + HTTP_SERVER_SENT_BYTES_VIEW, + HTTP_SERVER_LATENCY_VIEW, ]; const HTTP_BASIC_CLIENT_VIEWS: View[] = [ - HTTP_CLIENT_COMPLETED_COUNT_VIEW, HTTP_CLIENT_SENT_BYTES_VIEW, - HTTP_CLIENT_RECEIVED_BYTES_VIEW, HTTP_CLIENT_ROUNDTRIP_LATENCY_VIEW + HTTP_CLIENT_COMPLETED_COUNT_VIEW, + HTTP_CLIENT_SENT_BYTES_VIEW, + HTTP_CLIENT_RECEIVED_BYTES_VIEW, + HTTP_CLIENT_ROUNDTRIP_LATENCY_VIEW, ]; /** Register all default views. */ diff --git a/packages/opencensus-instrumentation-http/src/http.ts b/packages/opencensus-instrumentation-http/src/http.ts index d945f38e1..9b374f454 100644 --- a/packages/opencensus-instrumentation-http/src/http.ts +++ b/packages/opencensus-instrumentation-http/src/http.ts @@ -14,24 +14,45 @@ * limitations under the License. */ -import {BasePlugin, CanonicalCode, Func, HeaderGetter, HeaderSetter, MessageEventType, Span, SpanKind, TagMap, TagTtl, TraceOptions} from '@opencensus/core'; -import {ClientRequest, ClientResponse, IncomingMessage, request, RequestOptions, ServerResponse} from 'http'; +import { + BasePlugin, + CanonicalCode, + Func, + HeaderGetter, + HeaderSetter, + MessageEventType, + Span, + SpanKind, + TagMap, + TagTtl, + TraceOptions, +} from '@opencensus/core'; +import { + ClientRequest, + IncomingMessage, + request, + RequestOptions, + ServerResponse, +} from 'http'; import * as semver from 'semver'; import * as shimmer from 'shimmer'; import * as url from 'url'; import * as stats from './http-stats'; -import {HttpPluginConfig, IgnoreMatcher} from './types'; +import { HttpPluginConfig, IgnoreMatcher } from './types'; export type HttpGetCallback = (res: IncomingMessage) => void; export type RequestFunction = typeof request; function isOpenCensusRequest(options: RequestOptions) { - return options && options.headers && - !!options.headers['x-opencensus-outgoing-request']; + return ( + options && + options.headers && + !!options.headers['x-opencensus-outgoing-request'] + ); } const UNLIMITED_PROPAGATION_MD = { - tagTtl: TagTtl.UNLIMITED_PROPAGATION + tagTtl: TagTtl.UNLIMITED_PROPAGATION, }; const TAG_VALUE_MAX_LENGTH = 255; @@ -64,7 +85,10 @@ export class HttpPlugin extends BasePlugin { this.logger.debug('applying patch to %s@%s', this.moduleName, this.version); shimmer.wrap( - this.moduleExports, 'request', this.getPatchOutgoingRequestFunction()); + this.moduleExports, + 'request', + this.getPatchOutgoingRequestFunction() + ); // In Node 8, http.get calls a private request method, therefore we patch it // here too. @@ -81,7 +105,9 @@ export class HttpPlugin extends BasePlugin { // https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback // https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/plugins/plugin-http.ts#L198 return function getTrace( - options: RequestOptions|string, callback: HttpGetCallback) { + options: RequestOptions | string, + callback: HttpGetCallback + ) { const req = request(options, callback); req.end(); return req; @@ -89,15 +115,21 @@ export class HttpPlugin extends BasePlugin { }); } - if (this.moduleExports && this.moduleExports.Server && - this.moduleExports.Server.prototype) { + if ( + this.moduleExports && + this.moduleExports.Server && + this.moduleExports.Server.prototype + ) { shimmer.wrap( - this.moduleExports.Server.prototype, 'emit', - this.getPatchIncomingRequestFunction()); + this.moduleExports.Server.prototype, + 'emit', + this.getPatchIncomingRequestFunction() + ); } else { this.logger.error( - 'Could not apply patch to %s.emit. Interface is not as expected.', - this.moduleName); + 'Could not apply patch to %s.emit. Interface is not as expected.', + this.moduleName + ); } return this.moduleExports; @@ -109,8 +141,11 @@ export class HttpPlugin extends BasePlugin { if (semver.satisfies(this.version, '>=8.0.0')) { shimmer.unwrap(this.moduleExports, 'get'); } - if (this.moduleExports && this.moduleExports.Server && - this.moduleExports.Server.prototype) { + if ( + this.moduleExports && + this.moduleExports.Server && + this.moduleExports.Server.prototype + ) { shimmer.unwrap(this.moduleExports.Server.prototype, 'emit'); } } @@ -122,7 +157,10 @@ export class HttpPlugin extends BasePlugin { * @param list List of ignore patterns */ protected isIgnored( - url: string, request: T, list?: Array>): boolean { + url: string, + request: T, + list?: Array> + ): boolean { if (!list) { // No ignored urls - trace everything return false; @@ -144,7 +182,10 @@ export class HttpPlugin extends BasePlugin { * @param pattern Match pattern */ protected isSatisfyPattern( - url: string, request: T, pattern: IgnoreMatcher): boolean { + url: string, + request: T, + pattern: IgnoreMatcher + ): boolean { if (typeof pattern === 'string') { return pattern === url; } else if (pattern instanceof RegExp) { @@ -177,8 +218,9 @@ export class HttpPlugin extends BasePlugin { const method = request.method || 'GET'; plugin.logger.debug('%s plugin incomingRequest', plugin.moduleName); - if (plugin.isIgnored( - path, request, plugin.options.ignoreIncomingPaths)) { + if ( + plugin.isIgnored(path, request, plugin.options.ignoreIncomingPaths) + ) { return original.apply(this, arguments); } @@ -187,10 +229,13 @@ export class HttpPlugin extends BasePlugin { const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; - const traceOptions: TraceOptions = {name: path, kind: SpanKind.SERVER}; + const traceOptions: TraceOptions = { + name: path, + kind: SpanKind.SERVER, + }; if (propagation) { const spanContext = propagation.extract(getter); if (spanContext) { @@ -214,54 +259,70 @@ export class HttpPlugin extends BasePlugin { const requestUrl = request.url ? url.parse(request.url) : null; const host = headers.host || 'localhost'; - const userAgent = - (headers['user-agent'] || headers['User-Agent']) as string; + const userAgent = (headers['user-agent'] || + headers['User-Agent']) as string; const tags = new TagMap(); rootSpan.addAttribute( - HttpPlugin.ATTRIBUTE_HTTP_HOST, - host.replace( - /^(.*)(\:[0-9]{1,5})/, - '$1', - )); + HttpPlugin.ATTRIBUTE_HTTP_HOST, + host.replace(/^(.*)(\:[0-9]{1,5})/, '$1') + ); rootSpan.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_METHOD, method); if (requestUrl) { rootSpan.addAttribute( - HttpPlugin.ATTRIBUTE_HTTP_PATH, requestUrl.pathname || ''); + HttpPlugin.ATTRIBUTE_HTTP_PATH, + requestUrl.pathname || '' + ); rootSpan.addAttribute( - HttpPlugin.ATTRIBUTE_HTTP_ROUTE, requestUrl.path || ''); + HttpPlugin.ATTRIBUTE_HTTP_ROUTE, + requestUrl.path || '' + ); tags.set( - stats.HTTP_SERVER_ROUTE, { - value: (requestUrl.path || - '').substring(0, TAG_VALUE_MAX_LENGTH) - }, - UNLIMITED_PROPAGATION_MD); + stats.HTTP_SERVER_ROUTE, + { + value: (requestUrl.path || '').substring( + 0, + TAG_VALUE_MAX_LENGTH + ), + }, + UNLIMITED_PROPAGATION_MD + ); } if (userAgent) { rootSpan.addAttribute( - HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, userAgent); + HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, + userAgent + ); } rootSpan.addAttribute( - HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE, - response.statusCode.toString()); + HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE, + response.statusCode.toString() + ); rootSpan.setStatus( - HttpPlugin.parseResponseStatus(response.statusCode)); + HttpPlugin.parseResponseStatus(response.statusCode) + ); rootSpan.addMessageEvent(MessageEventType.RECEIVED, 1); if (plugin.options.applyCustomAttributesOnSpan) { plugin.options.applyCustomAttributesOnSpan( - rootSpan, request, response); + rootSpan, + request, + response + ); } tags.set( - stats.HTTP_SERVER_METHOD, {value: method}, - UNLIMITED_PROPAGATION_MD); + stats.HTTP_SERVER_METHOD, + { value: method }, + UNLIMITED_PROPAGATION_MD + ); tags.set( - stats.HTTP_SERVER_STATUS, - {value: response.statusCode.toString()}, - UNLIMITED_PROPAGATION_MD); + stats.HTTP_SERVER_STATUS, + { value: response.statusCode.toString() }, + UNLIMITED_PROPAGATION_MD + ); HttpPlugin.recordStats(rootSpan.kind, tags, Date.now() - startTime); rootSpan.end(); @@ -282,7 +343,9 @@ export class HttpPlugin extends BasePlugin { return (original: Func): Func => { const plugin = this; return function outgoingRequest( - options: RequestOptions|string, callback): ClientRequest { + options: RequestOptions | string, + callback + ): ClientRequest { if (!options) { return original.apply(this, [options, callback]); } @@ -291,7 +354,7 @@ export class HttpPlugin extends BasePlugin { let pathname; let method; let origin = ''; - if (typeof (options) === 'string') { + if (typeof options === 'string') { const parsedUrl = url.parse(options); options = parsedUrl; pathname = parsedUrl.pathname || ''; @@ -300,7 +363,8 @@ export class HttpPlugin extends BasePlugin { // Do not trace ourselves if (isOpenCensusRequest(options)) { plugin.logger.debug( - 'header with "x-opencensus-outgoing-request" - do not trace'); + 'header with "x-opencensus-outgoing-request" - do not trace' + ); return original.apply(this, [options, callback]); } @@ -311,16 +375,21 @@ export class HttpPlugin extends BasePlugin { } method = options.method || 'GET'; origin = `${options.protocol || 'http:'}//${options.host}`; - } catch (ignore) { - } + } catch (ignore) {} } - const request: ClientRequest = - original.apply(this, [options, callback]); - - if (plugin.isIgnored( - origin + pathname, request, - plugin.options.ignoreOutgoingUrls)) { + const request: ClientRequest = original.apply(this, [ + options, + callback, + ]); + + if ( + plugin.isIgnored( + origin + pathname, + request, + plugin.options.ignoreOutgoingUrls + ) + ) { return request; } @@ -339,14 +408,18 @@ export class HttpPlugin extends BasePlugin { if (!plugin.tracer.currentRootSpan) { plugin.logger.debug('outgoingRequest starting a root span'); return plugin.tracer.startRootSpan( - traceOptions, - plugin.getMakeRequestTraceFunction(request, options, plugin)); + traceOptions, + plugin.getMakeRequestTraceFunction(request, options, plugin) + ); } else { plugin.logger.debug('outgoingRequest starting a child span'); - const span = plugin.tracer.startChildSpan( - {name: traceOptions.name, kind: traceOptions.kind}); - return (plugin.getMakeRequestTraceFunction(request, options, plugin))( - span); + const span = plugin.tracer.startChildSpan({ + name: traceOptions.name, + kind: traceOptions.kind, + }); + return plugin.getMakeRequestTraceFunction(request, options, plugin)( + span + ); } }; }; @@ -359,8 +432,10 @@ export class HttpPlugin extends BasePlugin { * @param options The arguments to the original function. */ private getMakeRequestTraceFunction( - request: ClientRequest, options: RequestOptions, - plugin: HttpPlugin): Func { + request: ClientRequest, + options: RequestOptions, + plugin: HttpPlugin + ): Func { return (span: Span): ClientRequest => { const startTime = Date.now(); plugin.logger.debug('makeRequestTrace'); @@ -381,7 +456,7 @@ export class HttpPlugin extends BasePlugin { } else { request.setHeader(name, value); } - } + }, }; const propagation = plugin.tracer.propagation; @@ -397,18 +472,19 @@ export class HttpPlugin extends BasePlugin { propagation.inject(setter, span.spanContext); } - request.on('response', (response: ClientResponse) => { + request.on('response', (response: IncomingMessage) => { plugin.tracer.wrapEmitter(response); plugin.logger.debug('outgoingRequest on response()'); response.on('end', () => { plugin.logger.debug('outgoingRequest on end()'); const method = response.method ? response.method : 'GET'; const headers = options.headers; - const userAgent = - headers ? (headers['user-agent'] || headers['User-Agent']) : null; + const userAgent = headers + ? headers['user-agent'] || headers['User-Agent'] + : null; const tags = new TagMap(); - tags.set(stats.HTTP_CLIENT_METHOD, {value: method}); + tags.set(stats.HTTP_CLIENT_METHOD, { value: method }); const host = options.hostname || options.host || 'localhost'; span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_HOST, host); @@ -420,16 +496,19 @@ export class HttpPlugin extends BasePlugin { if (userAgent) { span.addAttribute( - HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, userAgent.toString()); + HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, + userAgent.toString() + ); } if (response.statusCode) { span.addAttribute( - HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE, - response.statusCode.toString()); + HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE, + response.statusCode.toString() + ); span.setStatus(HttpPlugin.parseResponseStatus(response.statusCode)); - tags.set( - stats.HTTP_CLIENT_STATUS, - {value: response.statusCode.toString()}); + tags.set(stats.HTTP_CLIENT_STATUS, { + value: response.statusCode.toString(), + }); } span.addMessageEvent(MessageEventType.SENT, 1); @@ -444,7 +523,9 @@ export class HttpPlugin extends BasePlugin { response.on('error', error => { span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_ERROR_NAME, error.name); span.addAttribute( - HttpPlugin.ATTRIBUTE_HTTP_ERROR_MESSAGE, error.message); + HttpPlugin.ATTRIBUTE_HTTP_ERROR_MESSAGE, + error.message + ); span.setStatus(CanonicalCode.UNKNOWN, error.message); span.end(); }); @@ -453,7 +534,9 @@ export class HttpPlugin extends BasePlugin { request.on('error', error => { span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_ERROR_NAME, error.name); span.addAttribute( - HttpPlugin.ATTRIBUTE_HTTP_ERROR_MESSAGE, error.message); + HttpPlugin.ATTRIBUTE_HTTP_ERROR_MESSAGE, + error.message + ); span.setStatus(CanonicalCode.UNKNOWN, error.message); span.end(); }); @@ -474,21 +557,21 @@ export class HttpPlugin extends BasePlugin { return CanonicalCode.OK; } else { switch (statusCode) { - case (400): + case 400: return CanonicalCode.INVALID_ARGUMENT; - case (504): + case 504: return CanonicalCode.DEADLINE_EXCEEDED; - case (404): + case 404: return CanonicalCode.NOT_FOUND; - case (403): + case 403: return CanonicalCode.PERMISSION_DENIED; - case (401): + case 401: return CanonicalCode.UNAUTHENTICATED; - case (429): + case 429: return CanonicalCode.RESOURCE_EXHAUSTED; - case (501): + case 501: return CanonicalCode.UNIMPLEMENTED; - case (503): + case 503: return CanonicalCode.UNAVAILABLE; default: return CanonicalCode.UNKNOWN; @@ -504,30 +587,32 @@ export class HttpPlugin extends BasePlugin { const measureList = []; switch (kind) { case SpanKind.CLIENT: - measureList.push( - {measure: stats.HTTP_CLIENT_ROUNDTRIP_LATENCY, value: ms}); + measureList.push({ + measure: stats.HTTP_CLIENT_ROUNDTRIP_LATENCY, + value: ms, + }); break; case SpanKind.SERVER: - measureList.push({measure: stats.HTTP_SERVER_LATENCY, value: ms}); + measureList.push({ measure: stats.HTTP_SERVER_LATENCY, value: ms }); break; default: break; } plugin.stats.record(measureList, tags); - } catch (ignore) { - } + } catch (ignore) {} } /** * Returns whether the Expect header is on the given options object. * @param options Options for http.request. */ - hasExpectHeader(options: RequestOptions|url.URL): boolean { + hasExpectHeader(options: RequestOptions | url.URL): boolean { return !!( - (options as RequestOptions).headers && - (options as RequestOptions).headers!.Expect); + (options as RequestOptions).headers && + (options as RequestOptions).headers!.Expect + ); } } const plugin = new HttpPlugin('http'); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-instrumentation-http/src/index.ts b/packages/opencensus-instrumentation-http/src/index.ts index b74935f03..5acd93475 100644 --- a/packages/opencensus-instrumentation-http/src/index.ts +++ b/packages/opencensus-instrumentation-http/src/index.ts @@ -15,4 +15,8 @@ */ export * from './http'; -export {registerAllClientViews, registerAllServerViews, registerAllViews} from './http-stats'; +export { + registerAllClientViews, + registerAllServerViews, + registerAllViews, +} from './http-stats'; diff --git a/packages/opencensus-instrumentation-http/src/types.ts b/packages/opencensus-instrumentation-http/src/types.ts index eb07df847..94987765a 100644 --- a/packages/opencensus-instrumentation-http/src/types.ts +++ b/packages/opencensus-instrumentation-http/src/types.ts @@ -14,19 +14,24 @@ * limitations under the License. */ -import {CustomAttributeFunction, Span} from '@opencensus/core'; -import {ClientRequest, IncomingMessage, ServerResponse} from 'http'; +import { CustomAttributeFunction, Span } from '@opencensus/core'; +import { ClientRequest, IncomingMessage, ServerResponse } from 'http'; export type IgnoreMatcher = - string|RegExp|((url: string, request: T) => boolean); + | string + | RegExp + | ((url: string, request: T) => boolean); export interface HttpCustomAttributeFunction extends CustomAttributeFunction { - (span: Span, request: ClientRequest|IncomingMessage, - response: IncomingMessage|ServerResponse): void; + ( + span: Span, + request: ClientRequest | IncomingMessage, + response: IncomingMessage | ServerResponse + ): void; } -export type HttpPluginConfig = { +export interface HttpPluginConfig { ignoreIncomingPaths?: Array>; ignoreOutgoingUrls?: Array>; applyCustomAttributesOnSpan?: HttpCustomAttributeFunction; -}; +} diff --git a/packages/opencensus-instrumentation-http/test/test-http.ts b/packages/opencensus-instrumentation-http/test/test-http.ts index 976735fa4..ac8ad3855 100644 --- a/packages/opencensus-instrumentation-http/test/test-http.ts +++ b/packages/opencensus-instrumentation-http/test/test-http.ts @@ -14,26 +14,53 @@ * limitations under the License. */ -import {CoreTracer, globalStats, HeaderGetter, HeaderSetter, logger, Measurement, MessageEventType, Propagation, Span, SpanContext, SpanEventListener, SpanKind, StatsEventListener, TagKey, TagMap, TagValue, View} from '@opencensus/core'; +import { + CoreTracer, + globalStats, + HeaderGetter, + HeaderSetter, + logger, + Measurement, + MessageEventType, + Propagation, + Span, + SpanContext, + SpanEventListener, + SpanKind, + StatsEventListener, + TagKey, + TagMap, + TagValue, + View, +} from '@opencensus/core'; import * as assert from 'assert'; import * as http from 'http'; import * as nock from 'nock'; import * as shimmer from 'shimmer'; import * as url from 'url'; -import {HttpPlugin, plugin} from '../src/'; +import { HttpPlugin, plugin } from '../src/'; import * as stats from '../src/http-stats'; function doNock( - url: string, path: string, httpCode: number, respBody: string, - times?: number) { + url: string, + path: string, + httpCode: number, + respBody: string, + times?: number +) { const i = times || 1; - nock(url).get(path).times(i).reply(httpCode, respBody); + nock(url) + .get(path) + .times(i) + .reply(httpCode, respBody); } function customAttributeFunction( - span: Span, request: http.ClientRequest|http.IncomingMessage, - response: http.IncomingMessage|http.ServerResponse): void { + span: Span, + request: http.ClientRequest | http.IncomingMessage, + response: http.IncomingMessage | http.ServerResponse +): void { span.addAttribute('span kind', span.kind); } @@ -47,7 +74,10 @@ class TestExporter implements StatsEventListener { } onRecord( - views: View[], measurement: Measurement, tagMap: Map) { + views: View[], + measurement: Measurement, + tagMap: Map + ) { this.recordedMeasurements.push(measurement); this.recorededTags.push(tagMap); } @@ -63,7 +93,7 @@ class TestExporter implements StatsEventListener { } const httpRequest = { - get: (options: {}|string) => { + get: (options: {} | string) => { return new Promise((resolve, reject) => { return http.get(options, resp => { let data = ''; @@ -78,14 +108,14 @@ const httpRequest = { }); }); }); - } + }, }; const VERSION = process.versions.node; class DummyPropagation implements Propagation { extract(getter: HeaderGetter): SpanContext { - return {traceId: 'dummy-trace-id', spanId: 'dummy-span-id'}; + return { traceId: 'dummy-trace-id', spanId: 'dummy-span-id' }; } inject(setter: HeaderSetter, spanContext: SpanContext): void { @@ -94,7 +124,7 @@ class DummyPropagation implements Propagation { } generate(): SpanContext { - return {traceId: 'dummy-trace-id', spanId: 'dummy-span-id'}; + return { traceId: 'dummy-trace-id', spanId: 'dummy-span-id' }; } } @@ -108,57 +138,82 @@ class SpanVerifier implements SpanEventListener { } function assertSpanAttributes( - span: Span, httpStatusCode: number, httpMethod: string, hostName: string, - path: string, userAgent?: string) { + span: Span, + httpStatusCode: number, + httpMethod: string, + hostName: string, + path: string, + userAgent?: string +) { assert.strictEqual( - span.status.code, HttpPlugin.parseResponseStatus(httpStatusCode)); + span.status.code, + HttpPlugin.parseResponseStatus(httpStatusCode) + ); assert.strictEqual( - span.attributes[HttpPlugin.ATTRIBUTE_HTTP_ERROR_MESSAGE], - span.status.message); + span.attributes[HttpPlugin.ATTRIBUTE_HTTP_ERROR_MESSAGE], + span.status.message + ); assert.strictEqual(span.attributes[HttpPlugin.ATTRIBUTE_HTTP_HOST], hostName); assert.strictEqual( - span.attributes[HttpPlugin.ATTRIBUTE_HTTP_METHOD], httpMethod); + span.attributes[HttpPlugin.ATTRIBUTE_HTTP_METHOD], + httpMethod + ); assert.strictEqual(span.attributes[HttpPlugin.ATTRIBUTE_HTTP_PATH], path); assert.strictEqual(span.attributes[HttpPlugin.ATTRIBUTE_HTTP_ROUTE], path); if (userAgent) { assert.strictEqual( - span.attributes[HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT], userAgent); + span.attributes[HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT], + userAgent + ); } assert.strictEqual( - span.attributes[HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE], - `${httpStatusCode}`); + span.attributes[HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE], + `${httpStatusCode}` + ); } function assertCustomAttribute( - span: Span, attributeName: string, attributeValue: SpanKind) { + span: Span, + attributeName: string, + attributeValue: SpanKind +) { assert.strictEqual(span.attributes[attributeName], attributeValue); } function assertClientStats( - testExporter: TestExporter, httpStatusCode: number, httpMethod: string) { + testExporter: TestExporter, + httpStatusCode: number, + httpMethod: string +) { const tags = new TagMap(); - tags.set(stats.HTTP_CLIENT_METHOD, {value: httpMethod}); - tags.set(stats.HTTP_CLIENT_STATUS, {value: `${httpStatusCode}`}); + tags.set(stats.HTTP_CLIENT_METHOD, { value: httpMethod }); + tags.set(stats.HTTP_CLIENT_STATUS, { value: `${httpStatusCode}` }); assert.strictEqual(testExporter.registeredViews.length, 8); assert.strictEqual(testExporter.recordedMeasurements.length, 1); assert.strictEqual( - testExporter.recordedMeasurements[0].measure, - stats.HTTP_CLIENT_ROUNDTRIP_LATENCY); + testExporter.recordedMeasurements[0].measure, + stats.HTTP_CLIENT_ROUNDTRIP_LATENCY + ); assert.ok(testExporter.recordedMeasurements[0].value >= 0); assert.deepStrictEqual(testExporter.recorededTags[0], tags.tags); } function assertServerStats( - testExporter: TestExporter, httpStatusCode: number, httpMethod: string, - path: string) { + testExporter: TestExporter, + httpStatusCode: number, + httpMethod: string, + path: string +) { const tags = new TagMap(); - tags.set(stats.HTTP_SERVER_METHOD, {value: httpMethod}); - tags.set(stats.HTTP_SERVER_STATUS, {value: `${httpStatusCode}`}); - tags.set(stats.HTTP_SERVER_ROUTE, {value: path}); + tags.set(stats.HTTP_SERVER_METHOD, { value: httpMethod }); + tags.set(stats.HTTP_SERVER_STATUS, { value: `${httpStatusCode}` }); + tags.set(stats.HTTP_SERVER_ROUTE, { value: path }); assert.strictEqual(testExporter.registeredViews.length, 8); assert.strictEqual(testExporter.recordedMeasurements.length, 1); assert.strictEqual( - testExporter.recordedMeasurements[0].measure, stats.HTTP_SERVER_LATENCY); + testExporter.recordedMeasurements[0].measure, + stats.HTTP_SERVER_LATENCY + ); assert.ok(testExporter.recordedMeasurements[0].value >= 0); assert.deepStrictEqual(testExporter.recorededTags[0], tags.tags); } @@ -185,19 +240,25 @@ describe('HttpPlugin', () => { before(() => { plugin.enable( - http, tracer, VERSION, { - ignoreIncomingPaths: [ - '/ignored/string', /^\/ignored\/regexp/, - (url: string) => url === '/ignored/function' - ], - ignoreOutgoingUrls: [ - `${urlHost}/ignored/string`, - /^http:\/\/fake\.service\.io\/ignored\/regexp$/, - (url: string) => url === `${urlHost}/ignored/function` - ], - applyCustomAttributesOnSpan: customAttributeFunction - }, - '', globalStats); + http, + tracer, + VERSION, + { + ignoreIncomingPaths: [ + '/ignored/string', + /^\/ignored\/regexp/, + (url: string) => url === '/ignored/function', + ], + ignoreOutgoingUrls: [ + `${urlHost}/ignored/string`, + /^http:\/\/fake\.service\.io\/ignored\/regexp$/, + (url: string) => url === `${urlHost}/ignored/function`, + ], + applyCustomAttributesOnSpan: customAttributeFunction, + }, + '', + globalStats + ); tracer.registerSpanEventListener(spanVerifier); server = http.createServer((request, response) => { response.end('Test Server Response'); @@ -225,14 +286,13 @@ describe('HttpPlugin', () => { server.close(); }); - /** Should intercept outgoing requests */ describe('patchOutgoingRequest()', () => { it('should create a rootSpan for GET requests as a client', async () => { const testPath = '/outgoing/rootSpan/1'; doNock(urlHost, testPath, 200, 'Ok'); assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.get(`${urlHost}${testPath}`).then((result) => { + await httpRequest.get(`${urlHost}${testPath}`).then(result => { assert.strictEqual(result, 'Ok'); assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); assert.strictEqual(spanVerifier.endedSpans.length, 1); @@ -250,32 +310,39 @@ describe('HttpPlugin', () => { for (let i = 0; i < httpErrorCodes.length; i++) { it(`should test rootSpan for GET requests with http error ${ - httpErrorCodes[i]}`, - async () => { - const testPath = '/outgoing/rootSpan/1'; - doNock( - urlHost, testPath, httpErrorCodes[i], - httpErrorCodes[i].toString()); - assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.get(`${urlHost}${testPath}`).then((result) => { - assert.strictEqual(result, httpErrorCodes[i].toString()); - assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); - assert.strictEqual(spanVerifier.endedSpans.length, 1); - const span = spanVerifier.endedSpans[0]; - assertSpanAttributes( - span, httpErrorCodes[i], 'GET', hostName, testPath); - assertClientStats(testExporter, httpErrorCodes[i], 'GET'); - }); - }); + httpErrorCodes[i] + }`, async () => { + const testPath = '/outgoing/rootSpan/1'; + doNock( + urlHost, + testPath, + httpErrorCodes[i], + httpErrorCodes[i].toString() + ); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + await httpRequest.get(`${urlHost}${testPath}`).then(result => { + assert.strictEqual(result, httpErrorCodes[i].toString()); + assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); + assert.strictEqual(spanVerifier.endedSpans.length, 1); + const span = spanVerifier.endedSpans[0]; + assertSpanAttributes( + span, + httpErrorCodes[i], + 'GET', + hostName, + testPath + ); + assertClientStats(testExporter, httpErrorCodes[i], 'GET'); + }); + }); } - it('should create a child span for GET requests', () => { const testPath = '/outgoing/rootSpan/childs/1'; doNock(urlHost, testPath, 200, 'Ok'); - const options = {name: 'TestRootSpan'}; + const options = { name: 'TestRootSpan' }; return tracer.startRootSpan(options, async (root: Span) => { - await httpRequest.get(`${urlHost}${testPath}`).then((result) => { + await httpRequest.get(`${urlHost}${testPath}`).then(result => { assert.ok(root.name.indexOf('TestRootSpan') >= 0); assert.strictEqual(root.spans.length, 1); assert.ok(root.spans[0].name.indexOf(testPath) >= 0); @@ -292,44 +359,54 @@ describe('HttpPlugin', () => { for (let i = 0; i < httpErrorCodes.length; i++) { it(`should test a child spans for GET requests with http error ${ - httpErrorCodes[i]}`, - () => { - const testPath = '/outgoing/rootSpan/childs/1'; - doNock( - urlHost, testPath, httpErrorCodes[i], - httpErrorCodes[i].toString()); - const options = {name: 'TestRootSpan'}; - return tracer.startRootSpan(options, async (root: Span) => { - await httpRequest.get(`${urlHost}${testPath}`).then((result) => { - assert.ok(root.name.indexOf('TestRootSpan') >= 0); - assert.strictEqual(root.spans.length, 1); - assert.ok(root.spans[0].name.indexOf(testPath) >= 0); - assert.strictEqual(root.traceId, root.spans[0].traceId); - - const span = root.spans[0]; - assertSpanAttributes( - span, httpErrorCodes[i], 'GET', hostName, testPath); - assertClientStats(testExporter, httpErrorCodes[i], 'GET'); - }); - }); - }); + httpErrorCodes[i] + }`, () => { + const testPath = '/outgoing/rootSpan/childs/1'; + doNock( + urlHost, + testPath, + httpErrorCodes[i], + httpErrorCodes[i].toString() + ); + const options = { name: 'TestRootSpan' }; + return tracer.startRootSpan(options, async (root: Span) => { + await httpRequest.get(`${urlHost}${testPath}`).then(result => { + assert.ok(root.name.indexOf('TestRootSpan') >= 0); + assert.strictEqual(root.spans.length, 1); + assert.ok(root.spans[0].name.indexOf(testPath) >= 0); + assert.strictEqual(root.traceId, root.spans[0].traceId); + + const span = root.spans[0]; + assertSpanAttributes( + span, + httpErrorCodes[i], + 'GET', + hostName, + testPath + ); + assertClientStats(testExporter, httpErrorCodes[i], 'GET'); + }); + }); + }); } it('should create multiple child spans for GET requests', () => { const testPath = '/outgoing/rootSpan/childs'; const num = 5; doNock(urlHost, testPath, 200, 'Ok', num); - const options = {name: 'TestRootSpan'}; + const options = { name: 'TestRootSpan' }; return tracer.startRootSpan(options, async (root: Span) => { assert.ok(root.name.indexOf('TestRootSpan') >= 0); for (let i = 0; i < num; i++) { - await httpRequest.get(`${urlHost}${testPath}`).then((result) => { + await httpRequest.get(`${urlHost}${testPath}`).then(result => { assert.strictEqual(root.spans.length, i + 1); assert.ok(root.spans[i].name.indexOf(testPath) >= 0); assert.strictEqual(root.traceId, root.spans[i].traceId); assert.strictEqual(root.spans[i].messageEvents[0].id, 1); assert.strictEqual( - root.spans[i].messageEvents[0].type, MessageEventType.SENT); + root.spans[i].messageEvents[0].type, + MessageEventType.SENT + ); }); } // 5 child spans ended @@ -340,23 +417,22 @@ describe('HttpPlugin', () => { }); }); - it('should not trace requests with \'x-opencensus-outgoing-request\' header', - async () => { - const testPath = '/outgoing/do-not-trace'; - doNock(urlHost, testPath, 200, 'Ok'); + it("should not trace requests with 'x-opencensus-outgoing-request' header", async () => { + const testPath = '/outgoing/do-not-trace'; + doNock(urlHost, testPath, 200, 'Ok'); - const options = { - host: hostName, - path: testPath, - headers: {'x-opencensus-outgoing-request': 1} - }; + const options = { + host: hostName, + path: testPath, + headers: { 'x-opencensus-outgoing-request': 1 }, + }; - assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.get(options).then((result) => { - assert.strictEqual(result, 'Ok'); - assert.strictEqual(spanVerifier.endedSpans.length, 0); - }); - }); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + await httpRequest.get(options).then(result => { + assert.strictEqual(result, 'Ok'); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + }); + }); for (const ignored of ['string', 'function', 'regexp']) { it(`should not trace ignored requests with type ${ignored}`, async () => { @@ -374,25 +450,24 @@ describe('HttpPlugin', () => { }); } - it('should create a rootSpan for GET requests and add propagation headers', - async () => { - nock.enableNetConnect(); - assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.get(`http://google.fr/`).then((result) => { - assert.strictEqual(spanVerifier.endedSpans.length, 1); - assert.ok(spanVerifier.endedSpans[0].name.indexOf('GET /') >= 0); - - const span = spanVerifier.endedSpans[0]; - assertSpanAttributes(span, 301, 'GET', 'google.fr', '/'); - assertClientStats(testExporter, 301, 'GET'); - }); - nock.disableNetConnect(); - }); + it('should create a rootSpan for GET requests and add propagation headers', async () => { + nock.enableNetConnect(); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + await httpRequest.get(`http://google.fr/`).then(result => { + assert.strictEqual(spanVerifier.endedSpans.length, 1); + assert.ok(spanVerifier.endedSpans[0].name.indexOf('GET /') >= 0); + + const span = spanVerifier.endedSpans[0]; + assertSpanAttributes(span, 301, 'GET', 'google.fr', '/'); + assertClientStats(testExporter, 301, 'GET'); + }); + nock.disableNetConnect(); + }); it('custom attributes should show up on client spans', async () => { nock.enableNetConnect(); assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.get(`http://google.fr/`).then((result) => { + await httpRequest.get(`http://google.fr/`).then(result => { assert.strictEqual(spanVerifier.endedSpans.length, 1); assert.ok(spanVerifier.endedSpans[0].name.indexOf('GET /') >= 0); @@ -402,25 +477,24 @@ describe('HttpPlugin', () => { nock.disableNetConnect(); }); - it('should create a rootSpan for GET requests and add propagation headers with Expect headers', - async () => { - nock.enableNetConnect(); - assert.strictEqual(spanVerifier.endedSpans.length, 0); - const options = Object.assign( - {headers: {Expect: '100-continue'}}, - url.parse('http://google.fr/')); - await httpRequest.get(options).then((result) => { - assert.strictEqual(spanVerifier.endedSpans.length, 1); - assert.ok(spanVerifier.endedSpans[0].name.indexOf('GET /') >= 0); - - const span = spanVerifier.endedSpans[0]; - assertSpanAttributes(span, 301, 'GET', 'google.fr', '/'); - assertClientStats(testExporter, 301, 'GET'); - }); - nock.disableNetConnect(); - }); - }); + it('should create a rootSpan for GET requests and add propagation headers with Expect headers', async () => { + nock.enableNetConnect(); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + const options = Object.assign( + { headers: { Expect: '100-continue' } }, + url.parse('http://google.fr/') + ); + await httpRequest.get(options).then(result => { + assert.strictEqual(spanVerifier.endedSpans.length, 1); + assert.ok(spanVerifier.endedSpans[0].name.indexOf('GET /') >= 0); + const span = spanVerifier.endedSpans[0]; + assertSpanAttributes(span, 301, 'GET', 'google.fr', '/'); + assertClientStats(testExporter, 301, 'GET'); + }); + nock.disableNetConnect(); + }); + }); /** Should intercept incoming requests */ describe('patchIncomingRequest()', () => { @@ -431,7 +505,7 @@ describe('HttpPlugin', () => { host: 'localhost', path: testPath, port: serverPort, - headers: {'User-Agent': 'Android'} + headers: { 'User-Agent': 'Android' }, }; shimmer.unwrap(http, 'get'); shimmer.unwrap(http, 'request'); @@ -439,44 +513,56 @@ describe('HttpPlugin', () => { assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.get(options).then((result) => { + await httpRequest.get(options).then(result => { assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); assert.strictEqual(spanVerifier.endedSpans.length, 1); const span = spanVerifier.endedSpans[0]; assertSpanAttributes( - span, 200, 'GET', 'localhost', testPath, 'Android'); + span, + 200, + 'GET', + 'localhost', + testPath, + 'Android' + ); assertServerStats(testExporter, 200, 'GET', testPath); }); }); - it('should handle incoming requests with long request url path', - async () => { - const testPath = '/test&code=' + - 'a'.repeat(300); - const options = { - host: 'localhost', - path: testPath, - port: serverPort, - headers: {'User-Agent': 'Android'} - }; - shimmer.unwrap(http, 'get'); - shimmer.unwrap(http, 'request'); - nock.enableNetConnect(); - - assert.strictEqual(spanVerifier.endedSpans.length, 0); - - await httpRequest.get(options).then((result) => { - assert.strictEqual(spanVerifier.endedSpans.length, 1); - assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); - const [span] = spanVerifier.endedSpans; - assertSpanAttributes( - span, 200, 'GET', 'localhost', testPath, 'Android'); - assertServerStats( - testExporter, 200, 'GET', - '/test&code=' + - 'a'.repeat(244)); - }); - }); + it('should handle incoming requests with long request url path', async () => { + const testPath = '/test&code=' + 'a'.repeat(300); + const options = { + host: 'localhost', + path: testPath, + port: serverPort, + headers: { 'User-Agent': 'Android' }, + }; + shimmer.unwrap(http, 'get'); + shimmer.unwrap(http, 'request'); + nock.enableNetConnect(); + + assert.strictEqual(spanVerifier.endedSpans.length, 0); + + await httpRequest.get(options).then(result => { + assert.strictEqual(spanVerifier.endedSpans.length, 1); + assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); + const [span] = spanVerifier.endedSpans; + assertSpanAttributes( + span, + 200, + 'GET', + 'localhost', + testPath, + 'Android' + ); + assertServerStats( + testExporter, + 200, + 'GET', + '/test&code=' + 'a'.repeat(244) + ); + }); + }); it('custom attributes should show up on server spans', async () => { const testPath = '/incoming/rootSpan/'; @@ -485,7 +571,7 @@ describe('HttpPlugin', () => { host: 'localhost', path: testPath, port: serverPort, - headers: {'User-Agent': 'Android'} + headers: { 'User-Agent': 'Android' }, }; shimmer.unwrap(http, 'get'); shimmer.unwrap(http, 'request'); @@ -493,7 +579,7 @@ describe('HttpPlugin', () => { assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.get(options).then((result) => { + await httpRequest.get(options).then(result => { assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); assert.strictEqual(spanVerifier.endedSpans.length, 1); const span = spanVerifier.endedSpans[0]; @@ -509,7 +595,7 @@ describe('HttpPlugin', () => { host: 'localhost', path: testPath, port: serverPort, - headers: {'User-Agent': 'Android'} + headers: { 'User-Agent': 'Android' }, }; shimmer.unwrap(http, 'get'); shimmer.unwrap(http, 'request'); @@ -533,10 +619,10 @@ describe('HttpPlugin', () => { const testPath = '/incoming/unpatch/'; nock.enableNetConnect(); - const options = {host: 'localhost', path: testPath, port: serverPort}; + const options = { host: 'localhost', path: testPath, port: serverPort }; assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.get(options).then((result) => { + await httpRequest.get(options).then(result => { assert.strictEqual(spanVerifier.endedSpans.length, 0); assert.strictEqual(testExporter.recordedMeasurements.length, 0); }); diff --git a/packages/opencensus-instrumentation-http2/package-lock.json b/packages/opencensus-instrumentation-http2/package-lock.json index dc22aab4d..48f42bae9 100644 --- a/packages/opencensus-instrumentation-http2/package-lock.json +++ b/packages/opencensus-instrumentation-http2/package-lock.json @@ -171,9 +171,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -229,58 +229,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -416,16 +364,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -508,8 +446,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -926,37 +863,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -987,21 +924,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1090,29 +1012,42 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } } } }, @@ -1332,15 +1267,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2198,6 +2128,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2264,9 +2199,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2299,11 +2234,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2337,9 +2272,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2482,17 +2417,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2728,29 +2663,25 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" }, "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - }, "semver": { "version": "5.7.0", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", @@ -2920,9 +2851,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-instrumentation-http2/package.json b/packages/opencensus-instrumentation-http2/package.json index 21e8b3303..5a549e34b 100644 --- a/packages/opencensus-instrumentation-http2/package.json +++ b/packages/opencensus-instrumentation-http2/package.json @@ -54,7 +54,7 @@ "@types/semver": "^6.0.0", "@types/shimmer": "^1.0.1", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "^14.0.0", "rimraf": "^2.6.2", diff --git a/packages/opencensus-instrumentation-http2/src/http2.ts b/packages/opencensus-instrumentation-http2/src/http2.ts index bd4988a2d..539214457 100644 --- a/packages/opencensus-instrumentation-http2/src/http2.ts +++ b/packages/opencensus-instrumentation-http2/src/http2.ts @@ -14,17 +14,27 @@ * limitations under the License. */ -import {Func, HeaderGetter, HeaderSetter, MessageEventType, Span, SpanKind, TraceOptions} from '@opencensus/core'; -import {HttpPlugin} from '@opencensus/instrumentation-http'; +import { + Func, + HeaderGetter, + HeaderSetter, + MessageEventType, + Span, + SpanKind, + TraceOptions, +} from '@opencensus/core'; +import { HttpPlugin } from '@opencensus/instrumentation-http'; import * as http2 from 'http2'; import * as shimmer from 'shimmer'; import * as url from 'url'; export type Http2Module = typeof http2; export type ConnectFunction = typeof http2.connect; -type RequestFunction = - (this: http2.ClientHttp2Session, headers?: http2.OutgoingHttpHeaders, - options?: http2.ClientSessionRequestOptions) => http2.ClientHttp2Stream; +type RequestFunction = ( + this: http2.ClientHttp2Session, + headers?: http2.OutgoingHttpHeaders, + options?: http2.ClientSessionRequestOptions +) => http2.ClientHttp2Stream; export type CreateServerFunction = typeof http2.createServer; /** Http2 instrumentation plugin for Opencensus */ @@ -39,11 +49,15 @@ export class Http2Plugin extends HttpPlugin { */ protected applyPatch() { shimmer.wrap( - this.moduleExports, 'createServer', - this.getPatchCreateServerFunction()); + this.moduleExports, + 'createServer', + this.getPatchCreateServerFunction() + ); shimmer.wrap( - this.moduleExports, 'createSecureServer', - this.getPatchCreateServerFunction()); + this.moduleExports, + 'createSecureServer', + this.getPatchCreateServerFunction() + ); shimmer.wrap(this.moduleExports, 'connect', this.getPatchConnectFunction()); @@ -62,28 +76,32 @@ export class Http2Plugin extends HttpPlugin { private getPatchConnectFunction() { const plugin = this; return (original: ConnectFunction): Func => { - return function patchedConnect(this: Http2Plugin, authority: string): - http2.ClientHttp2Session { - const client = original.apply(this, arguments); - shimmer.wrap( - client, 'request', - (original) => - (plugin.getPatchRequestFunction())(original, authority)); - - shimmer.unwrap(plugin.moduleExports, 'connect'); - - return client; - }; + return function patchedConnect( + this: Http2Plugin, + authority: string + ): http2.ClientHttp2Session { + const client = original.apply(this, arguments); + shimmer.wrap(client, 'request', original => + plugin.getPatchRequestFunction()(original, authority) + ); + + shimmer.unwrap(plugin.moduleExports, 'connect'); + + return client; + }; }; } private getPatchRequestFunction() { const plugin = this; - return (original: RequestFunction, - authority: string): Func => { + return ( + original: RequestFunction, + authority: string + ): Func => { return function patchedRequest( - this: http2.Http2Session, - headers: http2.OutgoingHttpHeaders): http2.ClientHttp2Stream { + this: http2.Http2Session, + headers: http2.OutgoingHttpHeaders + ): http2.ClientHttp2Stream { // Do not trace ourselves if (headers['x-opencensus-outgoing-request']) { return original.apply(this, arguments); @@ -103,29 +121,43 @@ export class Http2Plugin extends HttpPlugin { // the first operation, therefore we create a root span. if (!plugin.tracer.currentRootSpan) { return plugin.tracer.startRootSpan( - traceOptions, - plugin.getMakeHttp2RequestTraceFunction( - request, headers, authority, plugin)); + traceOptions, + plugin.getMakeHttp2RequestTraceFunction( + request, + headers, + authority, + plugin + ) + ); } else { - const span = plugin.tracer.startChildSpan( - {name: traceOptions.name, kind: traceOptions.kind}); - return (plugin.getMakeHttp2RequestTraceFunction( - request, headers, authority, plugin))(span); + const span = plugin.tracer.startChildSpan({ + name: traceOptions.name, + kind: traceOptions.kind, + }); + return plugin.getMakeHttp2RequestTraceFunction( + request, + headers, + authority, + plugin + )(span); } }; }; } private getMakeHttp2RequestTraceFunction( - request: http2.ClientHttp2Stream, headers: http2.OutgoingHttpHeaders, - authority: string, plugin: Http2Plugin): Func { + request: http2.ClientHttp2Stream, + headers: http2.OutgoingHttpHeaders, + authority: string, + plugin: Http2Plugin + ): Func { return (span: Span): http2.ClientHttp2Stream => { if (!span) return request; const setter: HeaderSetter = { setHeader(name: string, value: string) { headers[name] = value; - } + }, }; const propagation = plugin.tracer.propagation; @@ -136,27 +168,37 @@ export class Http2Plugin extends HttpPlugin { request.on('response', (responseHeaders: http2.IncomingHttpHeaders) => { const statusCode = responseHeaders[':status'] || 200; span.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_STATUS_CODE, `${statusCode}`); + Http2Plugin.ATTRIBUTE_HTTP_STATUS_CODE, + `${statusCode}` + ); span.setStatus(Http2Plugin.parseResponseStatus(+statusCode)); }); request.on('end', () => { const userAgent = - headers['user-agent'] || headers['User-Agent'] || null; + headers['user-agent'] || headers['User-Agent'] || null; const host = url.parse(authority).host; if (host) { span.addAttribute(Http2Plugin.ATTRIBUTE_HTTP_HOST, host); } span.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_METHOD, `${headers[':method']}`); + Http2Plugin.ATTRIBUTE_HTTP_METHOD, + `${headers[':method']}` + ); span.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_PATH, `${headers[':path']}`); + Http2Plugin.ATTRIBUTE_HTTP_PATH, + `${headers[':path']}` + ); span.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_ROUTE, `${headers[':path']}`); + Http2Plugin.ATTRIBUTE_HTTP_ROUTE, + `${headers[':path']}` + ); if (userAgent) { span.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_USER_AGENT, `${userAgent}`); + Http2Plugin.ATTRIBUTE_HTTP_USER_AGENT, + `${userAgent}` + ); } span.addMessageEvent(MessageEventType.SENT, 1); span.end(); @@ -176,18 +218,21 @@ export class Http2Plugin extends HttpPlugin { private getPatchCreateServerFunction() { const plugin = this; return (original: CreateServerFunction): Func => { - return function patchedCreateServer(this: Http2Plugin): - http2.Http2Server { - const server = original.apply(this, arguments); - shimmer.wrap( - server.constructor.prototype, 'emit', - plugin.getPatchEmitFunction()); - - shimmer.unwrap(plugin.moduleExports, 'createServer'); - shimmer.unwrap(plugin.moduleExports, 'createSecureServer'); - - return server; - }; + return function patchedCreateServer( + this: Http2Plugin + ): http2.Http2Server { + const server = original.apply(this, arguments); + shimmer.wrap( + server.constructor.prototype, + 'emit', + plugin.getPatchEmitFunction() + ); + + shimmer.unwrap(plugin.moduleExports, 'createServer'); + shimmer.unwrap(plugin.moduleExports, 'createSecureServer'); + + return server; + }; }; } @@ -195,9 +240,11 @@ export class Http2Plugin extends HttpPlugin { const plugin = this; return (original: RequestFunction): Func => { return function patchedEmit( - this: http2.Http2Server, event: string, - stream: http2.ServerHttp2Stream, - headers: http2.IncomingHttpHeaders): http2.ClientHttp2Stream { + this: http2.Http2Server, + event: string, + stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders + ): http2.ClientHttp2Stream { if (event !== 'stream') { return original.apply(this, arguments); } @@ -206,7 +253,7 @@ export class Http2Plugin extends HttpPlugin { const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; const traceOptions: TraceOptions = { @@ -242,21 +289,34 @@ export class Http2Plugin extends HttpPlugin { stream.end = originalEnd; const returned = stream.end.apply(this, arguments); - const userAgent = (headers['user-agent'] || headers['User-Agent'] || - null) as string; + const userAgent = (headers['user-agent'] || + headers['User-Agent'] || + null) as string; rootSpan.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_HOST, `${headers[':authority']}`); + Http2Plugin.ATTRIBUTE_HTTP_HOST, + `${headers[':authority']}` + ); rootSpan.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_METHOD, `${headers[':method']}`); + Http2Plugin.ATTRIBUTE_HTTP_METHOD, + `${headers[':method']}` + ); rootSpan.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_PATH, `${headers[':path']}`); + Http2Plugin.ATTRIBUTE_HTTP_PATH, + `${headers[':path']}` + ); rootSpan.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_ROUTE, `${headers[':path']}`); + Http2Plugin.ATTRIBUTE_HTTP_ROUTE, + `${headers[':path']}` + ); rootSpan.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_USER_AGENT, userAgent); + Http2Plugin.ATTRIBUTE_HTTP_USER_AGENT, + userAgent + ); rootSpan.addAttribute( - Http2Plugin.ATTRIBUTE_HTTP_STATUS_CODE, `${statusCode}`); + Http2Plugin.ATTRIBUTE_HTTP_STATUS_CODE, + `${statusCode}` + ); rootSpan.setStatus(Http2Plugin.parseResponseStatus(statusCode)); rootSpan.addMessageEvent(MessageEventType.RECEIVED, 1); @@ -272,4 +332,4 @@ export class Http2Plugin extends HttpPlugin { } const plugin = new Http2Plugin(); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-instrumentation-http2/test/test-http2.ts b/packages/opencensus-instrumentation-http2/test/test-http2.ts index 11fe67205..6658a813b 100644 --- a/packages/opencensus-instrumentation-http2/test/test-http2.ts +++ b/packages/opencensus-instrumentation-http2/test/test-http2.ts @@ -14,14 +14,19 @@ * limitations under the License. */ - -import {CoreTracer, logger, MessageEventType, Span, SpanEventListener} from '@opencensus/core'; +import { + CoreTracer, + logger, + MessageEventType, + Span, + SpanEventListener, +} from '@opencensus/core'; import * as assert from 'assert'; import * as http2 from 'http2'; import * as semver from 'semver'; -import {plugin} from '../src/'; -import {Http2Plugin} from '../src/'; +import { plugin } from '../src/'; +import { Http2Plugin } from '../src/'; const VERSION = process.versions.node; @@ -35,26 +40,39 @@ class SpanVerifier implements SpanEventListener { } function assertSpanAttributes( - span: Span, httpStatusCode: number, httpMethod: string, hostName: string, - path: string, userAgent?: string) { + span: Span, + httpStatusCode: number, + httpMethod: string, + hostName: string, + path: string, + userAgent?: string +) { assert.strictEqual( - span.status.code, Http2Plugin.parseResponseStatus(httpStatusCode)); + span.status.code, + Http2Plugin.parseResponseStatus(httpStatusCode) + ); assert.strictEqual( - span.attributes[Http2Plugin.ATTRIBUTE_HTTP_HOST], hostName); + span.attributes[Http2Plugin.ATTRIBUTE_HTTP_HOST], + hostName + ); assert.strictEqual( - span.attributes[Http2Plugin.ATTRIBUTE_HTTP_METHOD], httpMethod); + span.attributes[Http2Plugin.ATTRIBUTE_HTTP_METHOD], + httpMethod + ); assert.strictEqual(span.attributes[Http2Plugin.ATTRIBUTE_HTTP_PATH], path); assert.strictEqual(span.attributes[Http2Plugin.ATTRIBUTE_HTTP_ROUTE], path); if (userAgent) { assert.strictEqual( - span.attributes[Http2Plugin.ATTRIBUTE_HTTP_USER_AGENT], userAgent); + span.attributes[Http2Plugin.ATTRIBUTE_HTTP_USER_AGENT], + userAgent + ); } assert.strictEqual( - span.attributes[Http2Plugin.ATTRIBUTE_HTTP_STATUS_CODE], - `${httpStatusCode}`); + span.attributes[Http2Plugin.ATTRIBUTE_HTTP_STATUS_CODE], + `${httpStatusCode}` + ); } - describe('Http2Plugin', () => { if (semver.satisfies(process.version, '<8')) { console.log(`Skipping test-http2 on Node.js version ${process.version}`); @@ -78,7 +96,7 @@ describe('Http2Plugin', () => { reject(err); }); }); - } + }, }; let server: http2.Http2Server; @@ -90,7 +108,7 @@ describe('Http2Plugin', () => { const log = logger.logger(); const tracer = new CoreTracer(); const spanVerifier = new SpanVerifier(); - tracer.start({samplingRate: 1, logger: log}); + tracer.start({ samplingRate: 1, logger: log }); it('should return a plugin', () => { assert.ok(plugin instanceof Http2Plugin); @@ -107,7 +125,7 @@ describe('Http2Plugin', () => { if (path && path.length > 1) { statusCode = isNaN(Number(path.slice(1))) ? 200 : Number(path.slice(1)); } - stream.respond({':status': statusCode, 'content-type': 'text/plain'}); + stream.respond({ ':status': statusCode, 'content-type': 'text/plain' }); stream.end(`${statusCode}`); }); server.listen(serverPort); @@ -124,16 +142,15 @@ describe('Http2Plugin', () => { client.destroy(); }); - /** Should intercept outgoing requests */ describe('Instrumenting outgoing requests', () => { it('should create a rootSpan for GET requests as a client', async () => { const statusCode = 200; const testPath = `/${statusCode}`; - const requestOptions = {':method': 'GET', ':path': testPath}; + const requestOptions = { ':method': 'GET', ':path': testPath }; assert.strictEqual(spanVerifier.endedSpans.length, 0); - await http2Request.get(client, requestOptions).then((result) => { + await http2Request.get(client, requestOptions).then(result => { assert.strictEqual(result, `${statusCode}`); assert.strictEqual(spanVerifier.endedSpans.length, 2); assert.ok(spanVerifier.endedSpans[1].name.indexOf(testPath) >= 0); @@ -153,31 +170,30 @@ describe('Http2Plugin', () => { const httpErrorCodes = [400, 401, 403, 404, 429, 501, 503, 504, 500]; httpErrorCodes.map(errorCode => { - it(`should test rootSpan for GET requests with http error ${errorCode}`, - async () => { - const testPath = `/${errorCode}`; - const requestOptions = {':method': 'GET', ':path': testPath}; - assert.strictEqual(spanVerifier.endedSpans.length, 0); - - await http2Request.get(client, requestOptions).then((result) => { - assert.strictEqual(result, errorCode.toString()); - assert.strictEqual(spanVerifier.endedSpans.length, 2); - assert.ok(spanVerifier.endedSpans[1].name.indexOf(testPath) >= 0); - - const span = spanVerifier.endedSpans[1]; - assertSpanAttributes(span, errorCode, 'GET', host, testPath); - }); - }); + it(`should test rootSpan for GET requests with http error ${errorCode}`, async () => { + const testPath = `/${errorCode}`; + const requestOptions = { ':method': 'GET', ':path': testPath }; + assert.strictEqual(spanVerifier.endedSpans.length, 0); + + await http2Request.get(client, requestOptions).then(result => { + assert.strictEqual(result, errorCode.toString()); + assert.strictEqual(spanVerifier.endedSpans.length, 2); + assert.ok(spanVerifier.endedSpans[1].name.indexOf(testPath) >= 0); + + const span = spanVerifier.endedSpans[1]; + assertSpanAttributes(span, errorCode, 'GET', host, testPath); + }); + }); }); it('should create a child span for GET requests', () => { const statusCode = 200; const testPath = `/${statusCode}`; - const requestOptions = {':method': 'GET', ':path': testPath}; - const options = {name: 'TestRootSpan'}; + const requestOptions = { ':method': 'GET', ':path': testPath }; + const options = { name: 'TestRootSpan' }; return tracer.startRootSpan(options, async (root: Span) => { - await http2Request.get(client, requestOptions).then((result) => { + await http2Request.get(client, requestOptions).then(result => { assert.ok(root.name.indexOf('TestRootSpan') >= 0); assert.strictEqual(root.spans.length, 1); assert.ok(root.spans[0].name.indexOf(testPath) >= 0); @@ -189,38 +205,36 @@ describe('Http2Plugin', () => { }); httpErrorCodes.map(errorCode => { - it(`should test a child spans for GET requests with http error ${ - errorCode}`, - () => { - const testPath = `/${errorCode}`; - const requestOptions = {':method': 'GET', ':path': testPath}; - const options = {name: 'TestRootSpan'}; - - return tracer.startRootSpan(options, async (root: Span) => { - await http2Request.get(client, requestOptions).then((result) => { - assert.ok(root.name.indexOf('TestRootSpan') >= 0); - assert.strictEqual(root.spans.length, 1); - assert.ok(root.spans[0].name.indexOf(testPath) >= 0); - assert.strictEqual(root.traceId, root.spans[0].traceId); - - const span = root.spans[0]; - assertSpanAttributes(span, errorCode, 'GET', host, testPath); - }); - }); - }); + it(`should test a child spans for GET requests with http error ${errorCode}`, () => { + const testPath = `/${errorCode}`; + const requestOptions = { ':method': 'GET', ':path': testPath }; + const options = { name: 'TestRootSpan' }; + + return tracer.startRootSpan(options, async (root: Span) => { + await http2Request.get(client, requestOptions).then(result => { + assert.ok(root.name.indexOf('TestRootSpan') >= 0); + assert.strictEqual(root.spans.length, 1); + assert.ok(root.spans[0].name.indexOf(testPath) >= 0); + assert.strictEqual(root.traceId, root.spans[0].traceId); + + const span = root.spans[0]; + assertSpanAttributes(span, errorCode, 'GET', host, testPath); + }); + }); + }); }); it('should create multiple child spans for GET requests', () => { const statusCode = 200; const testPath = `/${statusCode}`; - const requestOptions = {':method': 'GET', ':path': testPath}; + const requestOptions = { ':method': 'GET', ':path': testPath }; const num = 5; - const options = {name: 'TestRootSpan'}; + const options = { name: 'TestRootSpan' }; return tracer.startRootSpan(options, async (root: Span) => { assert.ok(root.name.indexOf('TestRootSpan') >= 0); for (let i = 0; i < num; i++) { - await http2Request.get(client, requestOptions).then((result) => { + await http2Request.get(client, requestOptions).then(result => { assert.strictEqual(root.spans.length, i + 1); assert.ok(root.spans[i].name.indexOf(testPath) >= 0); assert.strictEqual(root.traceId, root.spans[i].traceId); @@ -234,24 +248,22 @@ describe('Http2Plugin', () => { }); }); - it('should not trace requests with \'x-opencensus-outgoing-request\' header', - async () => { - const statusCode = 200; - const testPath = `/${statusCode}`; - const requestOptions = { - ':method': 'GET', - ':path': testPath, - 'x-opencensus-outgoing-request': 1 - }; - - assert.strictEqual(spanVerifier.endedSpans.length, 0); - await http2Request.get(client, requestOptions).then((result) => { - assert.strictEqual(result, `${statusCode}`); - assert.strictEqual(spanVerifier.endedSpans.length, 1); - }); - }); - }); + it("should not trace requests with 'x-opencensus-outgoing-request' header", async () => { + const statusCode = 200; + const testPath = `/${statusCode}`; + const requestOptions = { + ':method': 'GET', + ':path': testPath, + 'x-opencensus-outgoing-request': 1, + }; + assert.strictEqual(spanVerifier.endedSpans.length, 0); + await http2Request.get(client, requestOptions).then(result => { + assert.strictEqual(result, `${statusCode}`); + assert.strictEqual(spanVerifier.endedSpans.length, 1); + }); + }); + }); /** Should intercept incoming requests */ describe('Instrumenting incoming requests', () => { @@ -261,12 +273,12 @@ describe('Http2Plugin', () => { const requestOptions = { ':method': 'GET', ':path': testPath, - 'User-Agent': 'Android' + 'User-Agent': 'Android', }; assert.strictEqual(spanVerifier.endedSpans.length, 0); - await http2Request.get(client, requestOptions).then((result) => { + await http2Request.get(client, requestOptions).then(result => { assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); assert.strictEqual(spanVerifier.endedSpans.length, 2); const span = spanVerifier.endedSpans[0]; diff --git a/packages/opencensus-instrumentation-https/package-lock.json b/packages/opencensus-instrumentation-https/package-lock.json index c54d40c6f..fd61ec65a 100644 --- a/packages/opencensus-instrumentation-https/package-lock.json +++ b/packages/opencensus-instrumentation-https/package-lock.json @@ -179,9 +179,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -242,58 +242,6 @@ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -447,16 +395,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -539,8 +477,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -975,37 +912,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -1036,21 +973,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1139,29 +1061,42 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } } } }, @@ -1381,15 +1316,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2293,6 +2223,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "propagate": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/propagate/-/propagate-1.0.0.tgz", @@ -2369,9 +2304,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2404,11 +2339,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2442,9 +2377,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2587,17 +2522,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2833,29 +2768,25 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" }, "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - }, "semver": { "version": "5.7.0", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", @@ -3030,9 +2961,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-instrumentation-https/package.json b/packages/opencensus-instrumentation-https/package.json index 79fa0d0f6..596ae503e 100644 --- a/packages/opencensus-instrumentation-https/package.json +++ b/packages/opencensus-instrumentation-https/package.json @@ -55,7 +55,7 @@ "@types/semver": "^6.0.0", "@types/shimmer": "^1.0.1", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nock": "^10.0.0", "nyc": "^14.0.0", diff --git a/packages/opencensus-instrumentation-https/src/https.ts b/packages/opencensus-instrumentation-https/src/https.ts index 4f03c4da9..fb6b775fd 100644 --- a/packages/opencensus-instrumentation-https/src/https.ts +++ b/packages/opencensus-instrumentation-https/src/https.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {Func} from '@opencensus/core'; -import {HttpPlugin} from '@opencensus/instrumentation-http'; +import { Func } from '@opencensus/core'; +import { HttpPlugin } from '@opencensus/instrumentation-http'; import * as http from 'http'; import * as https from 'https'; import * as semver from 'semver'; @@ -34,23 +34,36 @@ export class HttpsPlugin extends HttpPlugin { protected applyPatch() { this.logger.debug('applying patch to %s@%s', this.moduleName, this.version); - if (this.moduleExports && this.moduleExports.Server && - this.moduleExports.Server.prototype) { + if ( + this.moduleExports && + this.moduleExports.Server && + this.moduleExports.Server.prototype + ) { shimmer.wrap( - this.moduleExports && this.moduleExports.Server && - this.moduleExports.Server.prototype, - 'emit', this.getPatchIncomingRequestFunction()); + this.moduleExports && + this.moduleExports.Server && + this.moduleExports.Server.prototype, + 'emit', + this.getPatchIncomingRequestFunction() + ); } else { this.logger.error( - 'Could not apply patch to %s.emit. Interface is not as expected.', - this.moduleName); + 'Could not apply patch to %s.emit. Interface is not as expected.', + this.moduleName + ); } shimmer.wrap( - this.moduleExports, 'request', this.getPatchHttpsOutgoingRequest()); + this.moduleExports, + 'request', + this.getPatchHttpsOutgoingRequest() + ); if (semver.satisfies(this.version, '>=8.0.0')) { shimmer.wrap( - this.moduleExports, 'get', this.getPatchHttpsOutgoingRequest()); + this.moduleExports, + 'get', + this.getPatchHttpsOutgoingRequest() + ); } return this.moduleExports; @@ -61,27 +74,36 @@ export class HttpsPlugin extends HttpPlugin { return (original: Func): Func => { const plugin = this; return function httpsOutgoingRequest( - options, callback): http.ClientRequest { + options, + callback + ): http.ClientRequest { // Makes sure options will have default HTTPS parameters - if (typeof (options) !== 'string') { + if (typeof options !== 'string') { options.protocol = options.protocol || 'https:'; options.port = options.port || 443; options.agent = options.agent || https.globalAgent; } - return (plugin.getPatchOutgoingRequestFunction())(original)( - options, callback); + return plugin.getPatchOutgoingRequestFunction()(original)( + options, + callback + ); }; }; } /** Unpatches all HTTPS patched function. */ protected applyUnpatch(): void { - if (this.moduleExports && this.moduleExports.Server && - this.moduleExports.Server.prototype) { + if ( + this.moduleExports && + this.moduleExports.Server && + this.moduleExports.Server.prototype + ) { shimmer.unwrap( - this.moduleExports && this.moduleExports.Server && - this.moduleExports.Server.prototype, - 'emit'); + this.moduleExports && + this.moduleExports.Server && + this.moduleExports.Server.prototype, + 'emit' + ); } shimmer.unwrap(this.moduleExports, 'request'); if (semver.satisfies(this.version, '>=8.0.0')) { @@ -91,4 +113,4 @@ export class HttpsPlugin extends HttpPlugin { } const plugin = new HttpsPlugin(); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-instrumentation-https/test/test-https.ts b/packages/opencensus-instrumentation-https/test/test-https.ts index eba2829e5..21913a045 100644 --- a/packages/opencensus-instrumentation-https/test/test-https.ts +++ b/packages/opencensus-instrumentation-https/test/test-https.ts @@ -14,7 +14,13 @@ * limitations under the License. */ -import {CoreTracer, logger, Span, SpanEventListener, SpanKind} from '@opencensus/core'; +import { + CoreTracer, + logger, + Span, + SpanEventListener, + SpanKind, +} from '@opencensus/core'; import * as assert from 'assert'; import * as fs from 'fs'; import * as http from 'http'; @@ -22,34 +28,43 @@ import * as https from 'https'; import * as nock from 'nock'; import * as shimmer from 'shimmer'; -import {plugin} from '../src/'; -import {HttpsPlugin} from '../src/'; +import { plugin } from '../src/'; +import { HttpsPlugin } from '../src/'; process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; function doNock( - url: string, path: string, httpCode: number, respBody: string, - times?: number) { + url: string, + path: string, + httpCode: number, + respBody: string, + times?: number +) { const i = times || 1; - nock(url).get(path).times(i).reply(httpCode, respBody); + nock(url) + .get(path) + .times(i) + .reply(httpCode, respBody); } function customAttributeFunction( - span: Span, request: http.ClientRequest|http.IncomingMessage, - response: http.IncomingMessage|http.ServerResponse): void { + span: Span, + request: http.ClientRequest | http.IncomingMessage, + response: http.IncomingMessage | http.ServerResponse +): void { span.addAttribute('span kind', span.kind); } -type RequestFunction = typeof https.request|typeof https.get; +type RequestFunction = typeof https.request | typeof https.get; const httpRequest = { - request: (options: {}|string) => { + request: (options: {} | string) => { return httpRequest.make(options, https.request); }, - get: (options: {}|string) => { + get: (options: {} | string) => { return httpRequest.make(options, https.get); }, - make: (options: {}|string, method: RequestFunction) => { + make: (options: {} | string, method: RequestFunction) => { return new Promise((resolve, reject) => { const req = method(options, resp => { let data = ''; @@ -81,31 +96,48 @@ class SpanVerifier implements SpanEventListener { const httpsOptions = { key: fs.readFileSync('./test/fixtures/key.pem'), - cert: fs.readFileSync('./test/fixtures/cert.pem') + cert: fs.readFileSync('./test/fixtures/cert.pem'), }; function assertSpanAttributes( - span: Span, httpStatusCode: number, httpMethod: string, hostName: string, - path: string, userAgent?: string) { + span: Span, + httpStatusCode: number, + httpMethod: string, + hostName: string, + path: string, + userAgent?: string +) { assert.strictEqual( - span.status.code, HttpsPlugin.parseResponseStatus(httpStatusCode)); + span.status.code, + HttpsPlugin.parseResponseStatus(httpStatusCode) + ); assert.strictEqual( - span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_HOST], hostName); + span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_HOST], + hostName + ); assert.strictEqual( - span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_METHOD], httpMethod); + span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_METHOD], + httpMethod + ); assert.strictEqual(span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_PATH], path); assert.strictEqual(span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_ROUTE], path); if (userAgent) { assert.strictEqual( - span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_USER_AGENT], userAgent); + span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_USER_AGENT], + userAgent + ); } assert.strictEqual( - span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_STATUS_CODE], - `${httpStatusCode}`); + span.attributes[HttpsPlugin.ATTRIBUTE_HTTP_STATUS_CODE], + `${httpStatusCode}` + ); } function assertCustomAttribute( - span: Span, attributeName: string, attributeValue: SpanKind) { + span: Span, + attributeName: string, + attributeValue: SpanKind +) { assert.strictEqual(span.attributes[attributeName], attributeValue); } @@ -118,7 +150,7 @@ describe('HttpsPlugin', () => { const log = logger.logger(); const tracer = new CoreTracer(); const spanVerifier = new SpanVerifier(); - tracer.start({samplingRate: 1, logger: log}); + tracer.start({ samplingRate: 1, logger: log }); it('should return a plugin', () => { assert.ok(plugin instanceof HttpsPlugin); @@ -126,19 +158,24 @@ describe('HttpsPlugin', () => { before(() => { plugin.enable( - https, tracer, VERSION, { - ignoreIncomingPaths: [ - '/ignored/string', /^\/ignored\/regexp/, - (url: string) => url === '/ignored/function' - ], - ignoreOutgoingUrls: [ - `${urlHost}/ignored/string`, - /^https:\/\/fake\.service\.io\/ignored\/regexp$/, - (url: string) => url === `${urlHost}/ignored/function` - ], - applyCustomAttributesOnSpan: customAttributeFunction, - }, - ''); + https, + tracer, + VERSION, + { + ignoreIncomingPaths: [ + '/ignored/string', + /^\/ignored\/regexp/, + (url: string) => url === '/ignored/function', + ], + ignoreOutgoingUrls: [ + `${urlHost}/ignored/string`, + /^https:\/\/fake\.service\.io\/ignored\/regexp$/, + (url: string) => url === `${urlHost}/ignored/function`, + ], + applyCustomAttributesOnSpan: customAttributeFunction, + }, + '' + ); tracer.registerSpanEventListener(spanVerifier); server = https.createServer(httpsOptions, (request, response) => { response.end('Test Server Response'); @@ -168,52 +205,56 @@ describe('HttpsPlugin', () => { methods.map(requestMethod => { /** Should intercept outgoing requests */ describe(`Testing https.${requestMethod.name}() method`, () => { - it('should create a rootSpan for GET requests as a client', - async () => { - const testPath = '/outgoing/rootSpan/1'; - doNock(urlHost, testPath, 200, 'Ok'); - assert.strictEqual(spanVerifier.endedSpans.length, 0); - await requestMethod(`${urlHost}${testPath}`).then((result) => { - assert.strictEqual(result, 'Ok'); - assert.ok( - spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); - assert.strictEqual(spanVerifier.endedSpans.length, 1); - - const span = spanVerifier.endedSpans[0]; - assertSpanAttributes(span, 200, 'GET', hostName, testPath); - }); - }); + it('should create a rootSpan for GET requests as a client', async () => { + const testPath = '/outgoing/rootSpan/1'; + doNock(urlHost, testPath, 200, 'Ok'); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + await requestMethod(`${urlHost}${testPath}`).then(result => { + assert.strictEqual(result, 'Ok'); + assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); + assert.strictEqual(spanVerifier.endedSpans.length, 1); + + const span = spanVerifier.endedSpans[0]; + assertSpanAttributes(span, 200, 'GET', hostName, testPath); + }); + }); const httpErrorCodes = [400, 401, 403, 404, 429, 501, 503, 504, 500]; for (let i = 0; i < httpErrorCodes.length; i++) { it(`should test rootSpan for GET requests with http error ${ - httpErrorCodes[i]}`, - async () => { - const testPath = '/outgoing/rootSpan/1'; - doNock( - urlHost, testPath, httpErrorCodes[i], - httpErrorCodes[i].toString()); - assert.strictEqual(spanVerifier.endedSpans.length, 0); - await requestMethod(`${urlHost}${testPath}`).then((result) => { - assert.strictEqual(result, httpErrorCodes[i].toString()); - assert.ok( - spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); - assert.strictEqual(spanVerifier.endedSpans.length, 1); - const span = spanVerifier.endedSpans[0]; - assertSpanAttributes( - span, httpErrorCodes[i], 'GET', hostName, testPath); - }); - }); + httpErrorCodes[i] + }`, async () => { + const testPath = '/outgoing/rootSpan/1'; + doNock( + urlHost, + testPath, + httpErrorCodes[i], + httpErrorCodes[i].toString() + ); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + await requestMethod(`${urlHost}${testPath}`).then(result => { + assert.strictEqual(result, httpErrorCodes[i].toString()); + assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); + assert.strictEqual(spanVerifier.endedSpans.length, 1); + const span = spanVerifier.endedSpans[0]; + assertSpanAttributes( + span, + httpErrorCodes[i], + 'GET', + hostName, + testPath + ); + }); + }); } - it('should create a child span for GET requests', () => { const testPath = '/outgoing/rootSpan/childs/1'; doNock(urlHost, testPath, 200, 'Ok'); - const options = {name: 'TestRootSpan'}; + const options = { name: 'TestRootSpan' }; return tracer.startRootSpan(options, async (root: Span) => { - await requestMethod(`${urlHost}${testPath}`).then((result) => { + await requestMethod(`${urlHost}${testPath}`).then(result => { assert.ok(root.name.indexOf('TestRootSpan') >= 0); assert.strictEqual(root.spans.length, 1); assert.ok(root.spans[0].name.indexOf(testPath) >= 0); @@ -227,9 +268,9 @@ describe('HttpsPlugin', () => { it('should create a child span for GET requests', async () => { const testPath = '/outgoing/rootSpan/childs/1'; doNock(urlHost, testPath, 200, 'Ok'); - const options = {name: 'TestRootSpan'}; + const options = { name: 'TestRootSpan' }; return tracer.startRootSpan(options, async (root: Span) => { - await requestMethod(`${urlHost}${testPath}`).then((result) => { + await requestMethod(`${urlHost}${testPath}`).then(result => { assert.ok(root.name.indexOf('TestRootSpan') >= 0); assert.strictEqual(root.spans.length, 1); assert.ok(root.spans[0].name.indexOf(testPath) >= 0); @@ -242,37 +283,45 @@ describe('HttpsPlugin', () => { for (let i = 0; i < httpErrorCodes.length; i++) { it(`should test a child spans for GET requests with http error ${ - httpErrorCodes[i]}`, - () => { - const testPath = '/outgoing/rootSpan/childs/1'; - doNock( - urlHost, testPath, httpErrorCodes[i], - httpErrorCodes[i].toString()); - const options = {name: 'TestRootSpan'}; - return tracer.startRootSpan(options, async (root: Span) => { - await requestMethod(`${urlHost}${testPath}`).then((result) => { - assert.ok(root.name.indexOf('TestRootSpan') >= 0); - assert.strictEqual(root.spans.length, 1); - assert.ok(root.spans[0].name.indexOf(testPath) >= 0); - assert.strictEqual(root.traceId, root.spans[0].traceId); - - const span = root.spans[0]; - assertSpanAttributes( - span, httpErrorCodes[i], 'GET', hostName, testPath); - }); - }); - }); + httpErrorCodes[i] + }`, () => { + const testPath = '/outgoing/rootSpan/childs/1'; + doNock( + urlHost, + testPath, + httpErrorCodes[i], + httpErrorCodes[i].toString() + ); + const options = { name: 'TestRootSpan' }; + return tracer.startRootSpan(options, async (root: Span) => { + await requestMethod(`${urlHost}${testPath}`).then(result => { + assert.ok(root.name.indexOf('TestRootSpan') >= 0); + assert.strictEqual(root.spans.length, 1); + assert.ok(root.spans[0].name.indexOf(testPath) >= 0); + assert.strictEqual(root.traceId, root.spans[0].traceId); + + const span = root.spans[0]; + assertSpanAttributes( + span, + httpErrorCodes[i], + 'GET', + hostName, + testPath + ); + }); + }); + }); } it('should create multiple child spans for GET requests', () => { const testPath = '/outgoing/rootSpan/childs'; const num = 5; doNock(urlHost, testPath, 200, 'Ok', num); - const options = {name: 'TestRootSpan'}; + const options = { name: 'TestRootSpan' }; return tracer.startRootSpan(options, async (root: Span) => { assert.ok(root.name.indexOf('TestRootSpan') >= 0); for (let i = 0; i < num; i++) { - await requestMethod(`${urlHost}${testPath}`).then((result) => { + await requestMethod(`${urlHost}${testPath}`).then(result => { assert.strictEqual(root.spans.length, i + 1); assert.ok(root.spans[i].name.indexOf(testPath) >= 0); assert.strictEqual(root.traceId, root.spans[i].traceId); @@ -286,45 +335,42 @@ describe('HttpsPlugin', () => { }); }); - it('should not trace requests with \'x-opencensus-outgoing-request\' header', - async () => { - const testPath = '/outgoing/do-not-trace'; - doNock(urlHost, testPath, 200, 'Ok'); + it("should not trace requests with 'x-opencensus-outgoing-request' header", async () => { + const testPath = '/outgoing/do-not-trace'; + doNock(urlHost, testPath, 200, 'Ok'); - const options = { - host: hostName, - path: testPath, - headers: {'x-opencensus-outgoing-request': 1} - }; + const options = { + host: hostName, + path: testPath, + headers: { 'x-opencensus-outgoing-request': 1 }, + }; - assert.strictEqual(spanVerifier.endedSpans.length, 0); - await requestMethod(options).then((result) => { - assert.strictEqual(result, 'Ok'); - assert.strictEqual(spanVerifier.endedSpans.length, 0); - }); - }); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + await requestMethod(options).then(result => { + assert.strictEqual(result, 'Ok'); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + }); + }); for (const ignored of ['string', 'function', 'regexp']) { - it(`should not trace ignored requests with type ${ignored}`, - async () => { - const testPath = `/ignored/${ignored}`; - doNock(urlHost, testPath, 200, 'Ok'); - - const options = { - host: hostName, - path: testPath, - }; - - assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.get(options); - assert.strictEqual(spanVerifier.endedSpans.length, 0); - }); + it(`should not trace ignored requests with type ${ignored}`, async () => { + const testPath = `/ignored/${ignored}`; + doNock(urlHost, testPath, 200, 'Ok'); + + const options = { + host: hostName, + path: testPath, + }; + + assert.strictEqual(spanVerifier.endedSpans.length, 0); + await httpRequest.get(options); + assert.strictEqual(spanVerifier.endedSpans.length, 0); + }); } }); }); }); - /** Should intercept incoming requests */ describe('Instrumenting incoming requests', () => { it('should create a root span for incoming requests', async () => { @@ -334,18 +380,24 @@ describe('HttpsPlugin', () => { host: 'localhost', path: testPath, port: serverPort, - headers: {'User-Agent': 'Android'} + headers: { 'User-Agent': 'Android' }, }; nock.enableNetConnect(); assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.request(options).then((result) => { + await httpRequest.request(options).then(result => { assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); assert.strictEqual(spanVerifier.endedSpans.length, 2); const span = spanVerifier.endedSpans[0]; assertSpanAttributes( - span, 200, 'GET', 'localhost', testPath, 'Android'); + span, + 200, + 'GET', + 'localhost', + testPath, + 'Android' + ); }); }); @@ -356,13 +408,13 @@ describe('HttpsPlugin', () => { host: 'localhost', path: testPath, port: serverPort, - headers: {'User-Agent': 'Android'} + headers: { 'User-Agent': 'Android' }, }; nock.enableNetConnect(); assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.request(options).then((result) => { + await httpRequest.request(options).then(result => { assert.ok(spanVerifier.endedSpans[0].name.indexOf(testPath) >= 0); assert.strictEqual(spanVerifier.endedSpans.length, 2); const span = spanVerifier.endedSpans[0]; @@ -378,7 +430,7 @@ describe('HttpsPlugin', () => { host: 'localhost', path: testPath, port: serverPort, - headers: {'User-Agent': 'Android'} + headers: { 'User-Agent': 'Android' }, }; shimmer.unwrap(https, 'get'); shimmer.unwrap(https, 'request'); @@ -397,10 +449,10 @@ describe('HttpsPlugin', () => { plugin.disable(); const testPath = '/incoming/unpatch/'; - const options = {host: 'localhost', path: testPath, port: serverPort}; + const options = { host: 'localhost', path: testPath, port: serverPort }; assert.strictEqual(spanVerifier.endedSpans.length, 0); - await httpRequest.request(options).then((result) => { + await httpRequest.request(options).then(result => { assert.strictEqual(spanVerifier.endedSpans.length, 0); }); }); diff --git a/packages/opencensus-instrumentation-ioredis/package-lock.json b/packages/opencensus-instrumentation-ioredis/package-lock.json index bc9f2f695..7cf29bb13 100644 --- a/packages/opencensus-instrumentation-ioredis/package-lock.json +++ b/packages/opencensus-instrumentation-ioredis/package-lock.json @@ -230,58 +230,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -392,16 +340,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -487,9 +425,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -916,21 +854,28 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" + }, + "dependencies": { + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" + } } }, "handlebars": { @@ -959,21 +904,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1062,9 +992,9 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.2.tgz", - "integrity": "sha512-Z2rREiXA6cHRR9KBOarR3WuLlFzlIfAEIiB45ll5SSadMg7WqOh1MKEjjndfuH5ewXdixWCxqnVfGOQzPeiztA==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { "ansi-escapes": "^3.2.0", "chalk": "^2.4.2", @@ -1077,7 +1007,7 @@ "run-async": "^2.2.0", "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" } }, @@ -1319,15 +1249,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.1.tgz", - "integrity": "sha512-um46hB9wNOKlwkHgiuyEVAybXBjwFUV0Z/RaHJblRd9DXltue9FTYvzCr9ErQrK9Adz5MU4gHWVaNUfdmrC8qA==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2176,6 +2101,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2260,9 +2190,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2333,9 +2263,9 @@ } }, "rxjs": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.4.0.tgz", - "integrity": "sha512-Z9Yfa11F6B9Sg/BK9MnqnQ+aQYicPLtilXBp2yUtDt2JRCE0h26d33EnfO3ZxoNxG0T92OUucP3Ct7cpfkdFfw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2490,17 +2420,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2723,23 +2653,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.13.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.13.0.tgz", - "integrity": "sha512-ECOOQRxXCYnUUePG5h/+Z1Zouobk3KFpIHA9aKBB/nnMxs97S1JJPDGt5J4cGm1y9U9VmVlfboOxA8n1kSNzGw==", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" }, "dependencies": { "semver": { diff --git a/packages/opencensus-instrumentation-ioredis/package.json b/packages/opencensus-instrumentation-ioredis/package.json index 95e632d67..f43a236f6 100644 --- a/packages/opencensus-instrumentation-ioredis/package.json +++ b/packages/opencensus-instrumentation-ioredis/package.json @@ -6,7 +6,7 @@ "types": "build/src/index.d.ts", "repository": "census-instrumentation/opencensus-node", "scripts": { - "test": "nyc ts-mocha -p ./tsconfig.json test/**/*.ts", + "test": "nyc mocha build/test/**/*.js", "codecov": "nyc report --reporter=json && codecov -f coverage/*.json", "clean": "rimraf build/*", "check": "gts check", @@ -57,7 +57,7 @@ "@types/semver": "^6.0.0", "@types/shimmer": "^1.0.1", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "ioredis": "^4.6.2", "mocha": "^6.1.0", "nyc": "^14.0.0", diff --git a/packages/opencensus-instrumentation-ioredis/src/ioredis.ts b/packages/opencensus-instrumentation-ioredis/src/ioredis.ts index f19dba6cf..80f24e90f 100644 --- a/packages/opencensus-instrumentation-ioredis/src/ioredis.ts +++ b/packages/opencensus-instrumentation-ioredis/src/ioredis.ts @@ -14,18 +14,19 @@ * limitations under the License. */ -import {BasePlugin, CanonicalCode, Span, SpanKind} from '@opencensus/core'; +import { BasePlugin, CanonicalCode, Span, SpanKind } from '@opencensus/core'; import * as ioredis from 'ioredis'; import * as semver from 'semver'; import * as shimmer from 'shimmer'; -export type IORedisCommand = { - reject: (err: Error) => void; resolve: (result: {}) => void; +export interface IORedisCommand { + reject: (err: Error) => void; + resolve: (result: {}) => void; promise: Promise<{}>; - args: Array; + args: Array; callback: Function | undefined; name: string; -}; +} /** IORedis instrumentation plugin for Opencensus */ export class IORedisPlugin extends BasePlugin { @@ -42,15 +43,18 @@ export class IORedisPlugin extends BasePlugin { if (!semver.satisfies(this.version, '>=2.0.0')) { this.logger.info( - 'disabling ioredis plugin because version isnt supported'); + 'disabling ioredis plugin because version isnt supported' + ); return this.moduleExports; } if (this.moduleExports) { this.logger.debug('patching ioredis.prototype.sendCommand'); shimmer.wrap( - this.moduleExports.prototype, 'sendCommand', - this.getPatchSendCommand()); + this.moduleExports.prototype, + 'sendCommand', + this.getPatchSendCommand() + ); } return this.moduleExports; @@ -66,18 +70,23 @@ export class IORedisPlugin extends BasePlugin { /** Patch send command internal to trace requests */ private getPatchSendCommand() { const plugin = this; - const addArguments = typeof this.options === 'object' && - this.options.detailedCommands === true; + const addArguments = + typeof this.options === 'object' && + this.options.detailedCommands === true; return function internalSendCommandWrap(original: Function) { return function internal_send_command_trace( - this: ioredis.Redis, command: IORedisCommand) { + this: ioredis.Redis, + command: IORedisCommand + ) { if (!plugin.tracer.currentRootSpan) { return original.apply(this, arguments); } - const span = plugin.tracer.startChildSpan( - {name: `redis-${command.name}`, kind: SpanKind.CLIENT}); + const span = plugin.tracer.startChildSpan({ + name: `redis-${command.name}`, + kind: SpanKind.CLIENT, + }); if (span === null) return original.apply(this, arguments); span.addAttribute('command', command.name); @@ -99,8 +108,9 @@ export class IORedisPlugin extends BasePlugin { if (typeof command.promise.finally === 'function') { command.promise.finally(plugin.patchEnd(span)); } else if (typeof command.promise.then === 'function') { - command.promise.then(plugin.patchEnd(span)) - .catch(plugin.patchEnd(span)); + command.promise + .then(plugin.patchEnd(span)) + .catch(plugin.patchEnd(span)); } } return original.apply(this, arguments); @@ -128,4 +138,4 @@ export class IORedisPlugin extends BasePlugin { } const plugin = new IORedisPlugin('ioredis'); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-instrumentation-ioredis/test/test-ioredis.ts b/packages/opencensus-instrumentation-ioredis/test/test-ioredis.ts index b3f7f4c46..b315194bc 100644 --- a/packages/opencensus-instrumentation-ioredis/test/test-ioredis.ts +++ b/packages/opencensus-instrumentation-ioredis/test/test-ioredis.ts @@ -14,11 +14,17 @@ * limitations under the License. */ -import {CoreTracer, logger, Span, SpanEventListener, SpanKind} from '@opencensus/core'; +import { + CoreTracer, + logger, + Span, + SpanEventListener, + SpanKind, +} from '@opencensus/core'; import * as assert from 'assert'; import * as ioredis from 'ioredis'; -import {plugin} from '../src'; +import { plugin } from '../src'; /** Collects ended root spans to allow for later analysis. */ class RootSpanVerifier implements SpanEventListener { @@ -43,14 +49,21 @@ class RootSpanVerifier implements SpanEventListener { * @param expectedKind The expected kind of the first root span. */ function assertSpan( - rootSpanVerifier: RootSpanVerifier, expectedName: string, - expectedKind: SpanKind, verifyAttribute?: (span: Span) => boolean) { + rootSpanVerifier: RootSpanVerifier, + expectedName: string, + expectedKind: SpanKind, + verifyAttribute?: (span: Span) => boolean +) { assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 1); assert.strictEqual(rootSpanVerifier.endedRootSpans[0].spans.length, 1); assert.strictEqual( - rootSpanVerifier.endedRootSpans[0].spans[0].name, expectedName); + rootSpanVerifier.endedRootSpans[0].spans[0].name, + expectedName + ); assert.strictEqual( - rootSpanVerifier.endedRootSpans[0].spans[0].kind, expectedKind); + rootSpanVerifier.endedRootSpans[0].spans[0].kind, + expectedKind + ); if (typeof verifyAttribute === 'function') { for (const span of rootSpanVerifier.endedRootSpans[0].spans) { assert(verifyAttribute(span), 'failed to verify attribute'); @@ -59,7 +72,7 @@ function assertSpan( } describe('IORedisPlugin', () => { - // For these tests, mongo must be runing. Add OPENCENSUS_REDIS_TESTS to run + // For these tests, mongo must be running. Add OPENCENSUS_REDIS_TESTS to run // these tests. const OPENCENSUS_REDIS_TESTS = process.env.OPENCENSUS_REDIS_TESTS; const OPENCENSUS_REDIS_HOST = process.env.OPENCENSUS_REDIS_HOST; @@ -75,8 +88,8 @@ describe('IORedisPlugin', () => { const rootSpanVerifier = new RootSpanVerifier(); let client: ioredis.Redis; - before((done) => { - tracer.start({samplingRate: 1, logger: logger.logger(1)}); + before(done => { + tracer.start({ samplingRate: 1, logger: logger.logger(1) }); tracer.registerSpanEventListener(rootSpanVerifier); plugin.enable(ioredis, tracer, VERSION, {}, ''); client = new ioredis(URL); @@ -109,29 +122,28 @@ describe('IORedisPlugin', () => { }); describe('Instrumenting query operations', () => { - it('should create a child span for hset', (done) => { - tracer.startRootSpan({name: 'insertRootSpan'}, (rootSpan: Span) => { + it('should create a child span for hset', done => { + tracer.startRootSpan({ name: 'insertRootSpan' }, (rootSpan: Span) => { client.hset('hash', 'random', 'random', (err, result) => { assert.ifError(err); assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); rootSpan.end(); - assertSpan( - rootSpanVerifier, `redis-hset`, SpanKind.CLIENT, (span) => { - return span.attributes.arguments === undefined; - }); + assertSpan(rootSpanVerifier, `redis-hset`, SpanKind.CLIENT, span => { + return span.attributes.arguments === undefined; + }); done(); }); }); }); - it('should create a child span for get', (done) => { - tracer.startRootSpan({name: 'getRootSpan'}, (rootSpan: Span) => { + it('should create a child span for get', done => { + tracer.startRootSpan({ name: 'getRootSpan' }, (rootSpan: Span) => { client.get('test', (err, result) => { assert.ifError(err); assert.strictEqual(result, 'data'); assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); rootSpan.end(); - assertSpan(rootSpanVerifier, `redis-get`, SpanKind.CLIENT, (span) => { + assertSpan(rootSpanVerifier, `redis-get`, SpanKind.CLIENT, span => { return span.attributes.arguments === undefined; }); done(); @@ -139,16 +151,19 @@ describe('IORedisPlugin', () => { }); }); - it('should create a child span for del', (done) => { - tracer.startRootSpan({name: 'removeRootSpan'}, async (rootSpan: Span) => { - await client.del('test'); - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); - rootSpan.end(); - assertSpan(rootSpanVerifier, `redis-del`, SpanKind.CLIENT, (span) => { - return span.attributes.arguments === undefined; - }); - done(); - }); + it('should create a child span for del', done => { + tracer.startRootSpan( + { name: 'removeRootSpan' }, + async (rootSpan: Span) => { + await client.del('test'); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); + rootSpan.end(); + assertSpan(rootSpanVerifier, `redis-del`, SpanKind.CLIENT, span => { + return span.attributes.arguments === undefined; + }); + done(); + } + ); }); }); @@ -157,43 +172,53 @@ describe('IORedisPlugin', () => { plugin.applyUnpatch(); }); - it('should not create a child span for insert', (done) => { - tracer.startRootSpan({name: 'insertRootSpan'}, (rootSpan: Span) => { + it('should not create a child span for insert', done => { + tracer.startRootSpan({ name: 'insertRootSpan' }, (rootSpan: Span) => { client.hset('hash', 'random', 'random', (err, result) => { assert.ifError(err); assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); rootSpan.end(); assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 1); assert.strictEqual( - rootSpanVerifier.endedRootSpans[0].spans.length, 0); + rootSpanVerifier.endedRootSpans[0].spans.length, + 0 + ); done(); }); }); }); - it('should not create a child span for get', (done) => { - tracer.startRootSpan({name: 'getRootSpan'}, (rootSpan: Span) => { + it('should not create a child span for get', done => { + tracer.startRootSpan({ name: 'getRootSpan' }, (rootSpan: Span) => { client.get('test', (err, result) => { assert.ifError(err); assert.strictEqual(result, 'data'); rootSpan.end(); assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 1); assert.strictEqual( - rootSpanVerifier.endedRootSpans[0].spans.length, 0); + rootSpanVerifier.endedRootSpans[0].spans.length, + 0 + ); done(); }); }); }); - it('should not create a child span for del', (done) => { - tracer.startRootSpan({name: 'removeRootSpan'}, async (rootSpan: Span) => { - await client.del('test'); - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); - rootSpan.end(); - assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 1); - assert.strictEqual(rootSpanVerifier.endedRootSpans[0].spans.length, 0); - done(); - }); + it('should not create a child span for del', done => { + tracer.startRootSpan( + { name: 'removeRootSpan' }, + async (rootSpan: Span) => { + await client.del('test'); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 0); + rootSpan.end(); + assert.strictEqual(rootSpanVerifier.endedRootSpans.length, 1); + assert.strictEqual( + rootSpanVerifier.endedRootSpans[0].spans.length, + 0 + ); + done(); + } + ); }); }); }); diff --git a/packages/opencensus-instrumentation-mongodb/package-lock.json b/packages/opencensus-instrumentation-mongodb/package-lock.json index 7ae8fe947..be7353b09 100644 --- a/packages/opencensus-instrumentation-mongodb/package-lock.json +++ b/packages/opencensus-instrumentation-mongodb/package-lock.json @@ -189,9 +189,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -247,58 +247,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -439,16 +387,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -531,8 +469,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -949,37 +886,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -1010,21 +947,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1113,29 +1035,42 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "dependencies": { - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } } } }, @@ -1362,15 +1297,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2238,6 +2168,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2304,9 +2239,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2348,11 +2283,11 @@ } }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2386,9 +2321,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2542,17 +2477,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2788,29 +2723,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2975,9 +2904,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-instrumentation-mongodb/package.json b/packages/opencensus-instrumentation-mongodb/package.json index a626c12bc..560f5edaa 100644 --- a/packages/opencensus-instrumentation-mongodb/package.json +++ b/packages/opencensus-instrumentation-mongodb/package.json @@ -54,7 +54,7 @@ "@types/node": "^10.12.12", "@types/shimmer": "^1.0.1", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "mongodb": "3.1.10", "nyc": "^14.0.0", diff --git a/packages/opencensus-instrumentation-mongodb/src/mongodb.ts b/packages/opencensus-instrumentation-mongodb/src/mongodb.ts index 29a80189b..b54194c63 100644 --- a/packages/opencensus-instrumentation-mongodb/src/mongodb.ts +++ b/packages/opencensus-instrumentation-mongodb/src/mongodb.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {BasePlugin, Func, Span, SpanKind} from '@opencensus/core'; +import { BasePlugin, Func, Span, SpanKind } from '@opencensus/core'; import * as mongodb from 'mongodb'; import * as shimmer from 'shimmer'; @@ -39,22 +39,31 @@ export class MongoDBPlugin extends BasePlugin { if (this.moduleExports.Server) { this.logger.debug('patching mongodb-core.Server.prototype.command'); shimmer.wrap( - this.moduleExports.Server.prototype, 'command' as never, - this.getPatchCommand()); + this.moduleExports.Server.prototype, + 'command' as never, + this.getPatchCommand() + ); this.logger.debug( - 'patching mongodb-core.Server.prototype functions:', this.SERVER_FNS); + 'patching mongodb-core.Server.prototype functions:', + this.SERVER_FNS + ); shimmer.massWrap( - [this.moduleExports.Server.prototype], this.SERVER_FNS as never[], - this.getPatchQuery()); + [this.moduleExports.Server.prototype], + this.SERVER_FNS as never[], + this.getPatchQuery() + ); } if (this.moduleExports.Cursor) { this.logger.debug( - 'patching mongodb-core.Cursor.prototype functions:', - this.CURSOR_FNS_FIRST); + 'patching mongodb-core.Cursor.prototype functions:', + this.CURSOR_FNS_FIRST + ); shimmer.massWrap( - [this.moduleExports.Cursor.prototype], - this.CURSOR_FNS_FIRST as never[], this.getPatchCursor()); + [this.moduleExports.Cursor.prototype], + this.CURSOR_FNS_FIRST as never[], + this.getPatchCursor() + ); } return this.moduleExports; @@ -65,7 +74,9 @@ export class MongoDBPlugin extends BasePlugin { shimmer.unwrap(this.moduleExports.Server.prototype, 'command'); shimmer.massUnwrap(this.moduleExports.Server.prototype, this.SERVER_FNS); shimmer.massUnwrap( - this.moduleExports.Cursor.prototype, this.CURSOR_FNS_FIRST); + this.moduleExports.Cursor.prototype, + this.CURSOR_FNS_FIRST + ); } /** Creates spans for Command operations */ @@ -73,13 +84,20 @@ export class MongoDBPlugin extends BasePlugin { const plugin = this; return (original: Func) => { return function( - // tslint:disable-next-line:no-any - this: mongodb.Server, ns: string, command: any, - options: {}|Function, callback: Function): mongodb.Server { + this: mongodb.Server, + ns: string, + // tslint:disable-next-line:no-any + command: any, + options: {} | Function, + callback: Function + ): mongodb.Server { const resultHandler = - typeof options === 'function' ? options : callback; - if (plugin.tracer.currentRootSpan && arguments.length > 0 && - typeof resultHandler === 'function') { + typeof options === 'function' ? options : callback; + if ( + plugin.tracer.currentRootSpan && + arguments.length > 0 && + typeof resultHandler === 'function' + ) { let type: string; if (command.createIndexes) { type = 'createIndexes'; @@ -93,14 +111,25 @@ export class MongoDBPlugin extends BasePlugin { type = 'command'; } - const span = plugin.tracer.startChildSpan( - {name: `${ns}.${type}`, kind: SpanKind.SERVER}); + const span = plugin.tracer.startChildSpan({ + name: `${ns}.${type}`, + kind: SpanKind.SERVER, + }); if (typeof options === 'function') { return original.call( - this, ns, command, plugin.patchEnd(span, options)); + this, + ns, + command, + plugin.patchEnd(span, options) + ); } else { return original.call( - this, ns, command, options, plugin.patchEnd(span, callback)); + this, + ns, + command, + options, + plugin.patchEnd(span, callback) + ); } } @@ -114,21 +143,40 @@ export class MongoDBPlugin extends BasePlugin { const plugin = this; return (original: Func) => { return function( - // tslint:disable-next-line:no-any - this: mongodb.Server, ns: string, command: any, options: any, - callback: Function): mongodb.Server { + this: mongodb.Server, + ns: string, + // tslint:disable-next-line:no-any + command: any, + // tslint:disable-next-line:no-any + options: any, + callback: Function + ): mongodb.Server { const resultHandler = - typeof options === 'function' ? options : callback; - if (plugin.tracer.currentRootSpan && arguments.length > 0 && - typeof resultHandler === 'function') { - const span = plugin.tracer.startChildSpan( - {name: `${ns}.query`, kind: SpanKind.SERVER}); + typeof options === 'function' ? options : callback; + if ( + plugin.tracer.currentRootSpan && + arguments.length > 0 && + typeof resultHandler === 'function' + ) { + const span = plugin.tracer.startChildSpan({ + name: `${ns}.query`, + kind: SpanKind.SERVER, + }); if (typeof options === 'function') { return original.call( - this, ns, command, plugin.patchEnd(span, options)); + this, + ns, + command, + plugin.patchEnd(span, options) + ); } else { return original.call( - this, ns, command, options, plugin.patchEnd(span, callback)); + this, + ns, + command, + options, + plugin.patchEnd(span, callback) + ); } } @@ -144,10 +192,15 @@ export class MongoDBPlugin extends BasePlugin { // tslint:disable-next-line:no-any return function(this: any, ...args: any[]): mongodb.Cursor { let resultHandler = args[0]; - if (plugin.tracer.currentRootSpan && arguments.length > 0 && - typeof resultHandler === 'function') { - const span = plugin.tracer.startChildSpan( - {name: `${this.ns}.cursor`, kind: SpanKind.SERVER}); + if ( + plugin.tracer.currentRootSpan && + arguments.length > 0 && + typeof resultHandler === 'function' + ) { + const span = plugin.tracer.startChildSpan({ + name: `${this.ns}.cursor`, + kind: SpanKind.SERVER, + }); resultHandler = plugin.patchEnd(span, resultHandler); } @@ -171,4 +224,4 @@ export class MongoDBPlugin extends BasePlugin { } const plugin = new MongoDBPlugin('mongodb'); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-instrumentation-mongodb/test/test-mongodb.ts b/packages/opencensus-instrumentation-mongodb/test/test-mongodb.ts index 02625b8c2..3203ef71f 100644 --- a/packages/opencensus-instrumentation-mongodb/test/test-mongodb.ts +++ b/packages/opencensus-instrumentation-mongodb/test/test-mongodb.ts @@ -14,15 +14,20 @@ * limitations under the License. */ -import {CoreTracer, Span, SpanEventListener, SpanKind} from '@opencensus/core'; +import { + CoreTracer, + Span, + SpanEventListener, + SpanKind, +} from '@opencensus/core'; import * as assert from 'assert'; import * as mongodb from 'mongodb'; -import {plugin} from '../src/'; +import { plugin } from '../src/'; -export type MongoDBAccess = { - client: mongodb.MongoClient, - collection: mongodb.Collection -}; +export interface MongoDBAccess { + client: mongodb.MongoClient; + collection: mongodb.Collection; +} /** Collects ended root spans to allow for later analysis. */ class SpanVerifier implements SpanEventListener { @@ -40,8 +45,11 @@ class SpanVerifier implements SpanEventListener { * @param dbName The mongodb database name. * @param collectionName The mongodb collection name. */ -function accessCollection(url: string, dbName: string, collectionName: string): - Promise { +function accessCollection( + url: string, + dbName: string, + collectionName: string +): Promise { return new Promise((resolve, reject) => { mongodb.MongoClient.connect(url, function connectedClient(err, client) { if (err) { @@ -50,7 +58,7 @@ function accessCollection(url: string, dbName: string, collectionName: string): } const db = client.db(dbName); const collection = db.collection(collectionName); - resolve({'client': client, 'collection': collection}); + resolve({ client, collection }); }); }); } @@ -63,27 +71,27 @@ function accessCollection(url: string, dbName: string, collectionName: string): * @param expectedKind The expected kind of the first root span. */ function assertSpan( - rootSpanVerifier: SpanVerifier, expectedName: string, - expectedKind: SpanKind) { + rootSpanVerifier: SpanVerifier, + expectedName: string, + expectedKind: SpanKind +) { assert.strictEqual(rootSpanVerifier.endedSpans.length, 2); assert.strictEqual(rootSpanVerifier.endedSpans[1].spans.length, 1); - // we are forced to ignore the error because 'truncated' is a private - // field but needed to verify that the span are correctly ended. - // @ts-ignore - const isTruncated = rootSpanVerifier.endedSpans[1].spans[0].truncated; - assert.strictEqual( - isTruncated, false, 'the span should not have been truncated'); assert.strictEqual( - rootSpanVerifier.endedSpans[1].spans[0].name, expectedName); + rootSpanVerifier.endedSpans[1].spans[0].name, + expectedName + ); assert.strictEqual( - rootSpanVerifier.endedSpans[1].spans[0].kind, expectedKind); + rootSpanVerifier.endedSpans[1].spans[0].kind, + expectedKind + ); } describe('MongoDBPlugin', () => { - // For these tests, mongo must be runing. Add OPENCENSUS_MONGODB_TESTS to run + // For these tests, mongo must be running. Add OPENCENSUS_MONGODB_TESTS to run // these tests. - const OPENCENSUS_MONGODB_TESTS = - process.env.OPENCENSUS_MONGODB_TESTS as string; + const OPENCENSUS_MONGODB_TESTS = process.env + .OPENCENSUS_MONGODB_TESTS as string; let shouldTest = true; if (!OPENCENSUS_MONGODB_TESTS) { console.log('Skipping test-mongodb. Run MongoDB to test'); @@ -100,22 +108,23 @@ describe('MongoDBPlugin', () => { let client: mongodb.MongoClient; let collection: mongodb.Collection; - before((done) => { - tracer.start({samplingRate: 1}); + before(done => { + tracer.start({ samplingRate: 1 }); tracer.registerSpanEventListener(rootSpanVerifier); plugin.enable(mongodb, tracer, VERSION, {}, ''); accessCollection(URL, DB_NAME, COLLECTION_NAME) - .then(result => { - client = result.client; - collection = result.collection; - done(); - }) - .catch((err: Error) => { - console.log( - 'Skipping test-mongodb. Could not connect. Run MongoDB to test'); - shouldTest = false; - done(); - }); + .then(result => { + client = result.client; + collection = result.collection; + done(); + }) + .catch((err: Error) => { + console.log( + 'Skipping test-mongodb. Could not connect. Run MongoDB to test' + ); + shouldTest = false; + done(); + }); }); beforeEach(function mongoBeforeEach(done) { @@ -127,14 +136,14 @@ describe('MongoDBPlugin', () => { } rootSpanVerifier.endedSpans = []; // Non traced insertion of basic data to perform tests - const insertData = [{a: 1}, {a: 2}, {a: 3}]; + const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; collection.insertMany(insertData, (err, result) => { done(); }); }); - afterEach((done) => { - collection.remove({}, done); + afterEach(done => { + collection.deleteOne({}, done); }); after(() => { @@ -145,45 +154,51 @@ describe('MongoDBPlugin', () => { /** Should intercept query */ describe('Instrumenting query operations', () => { - it('should create a child span for insert', (done) => { - const insertData = [{a: 1}, {a: 2}, {a: 3}]; + it('should create a child span for insert', done => { + const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; - tracer.startRootSpan({name: 'insertRootSpan'}, (rootSpan: Span) => { + tracer.startRootSpan({ name: 'insertRootSpan' }, (rootSpan: Span) => { collection.insertMany(insertData, (err, result) => { assert.strictEqual(rootSpanVerifier.endedSpans.length, 1); rootSpan.end(); assert.ifError(err); assertSpan( - rootSpanVerifier, `${DB_NAME}.${COLLECTION_NAME}.query`, - SpanKind.SERVER); + rootSpanVerifier, + `${DB_NAME}.${COLLECTION_NAME}.query`, + SpanKind.SERVER + ); done(); }); }); }); - it('should create a child span for update', (done) => { - tracer.startRootSpan({name: 'updateRootSpan'}, (rootSpan: Span) => { - collection.updateOne({a: 2}, {$set: {b: 1}}, (err, result) => { + it('should create a child span for update', done => { + tracer.startRootSpan({ name: 'updateRootSpan' }, (rootSpan: Span) => { + collection.updateOne({ a: 2 }, { $set: { b: 1 } }, (err, result) => { assert.strictEqual(rootSpanVerifier.endedSpans.length, 1); rootSpan.end(); assert.ifError(err); assertSpan( - rootSpanVerifier, `${DB_NAME}.${COLLECTION_NAME}.query`, - SpanKind.SERVER); + rootSpanVerifier, + `${DB_NAME}.${COLLECTION_NAME}.query`, + SpanKind.SERVER + ); done(); }); }); }); - it('should create a child span for remove', (done) => { - tracer.startRootSpan({name: 'removeRootSpan'}, (rootSpan: Span) => { - collection.deleteOne({a: 3}, (err, result) => { + it('should create a child span for remove', done => { + tracer.startRootSpan({ name: 'removeRootSpan' }, (rootSpan: Span) => { + collection.deleteOne({ a: 3 }, (err, result) => { assert.strictEqual(rootSpanVerifier.endedSpans.length, 1); rootSpan.end(); assert.ifError(err); assertSpan( - rootSpanVerifier, `${DB_NAME}.${COLLECTION_NAME}.query`, - SpanKind.SERVER); + rootSpanVerifier, + `${DB_NAME}.${COLLECTION_NAME}.query`, + SpanKind.SERVER + ); done(); }); }); @@ -192,15 +207,17 @@ describe('MongoDBPlugin', () => { /** Should intercept cursor */ describe('Instrumenting cursor operations', () => { - it('should create a child span for find', (done) => { - tracer.startRootSpan({name: 'findRootSpan'}, (rootSpan: Span) => { + it('should create a child span for find', done => { + tracer.startRootSpan({ name: 'findRootSpan' }, (rootSpan: Span) => { collection.find({}).toArray((err, result) => { assert.strictEqual(rootSpanVerifier.endedSpans.length, 1); rootSpan.end(); assert.ifError(err); assertSpan( - rootSpanVerifier, `${DB_NAME}.${COLLECTION_NAME}.cursor`, - SpanKind.SERVER); + rootSpanVerifier, + `${DB_NAME}.${COLLECTION_NAME}.cursor`, + SpanKind.SERVER + ); done(); }); }); @@ -209,28 +226,33 @@ describe('MongoDBPlugin', () => { /** Should intercept command */ describe('Instrumenting command operations', () => { - it('should create a child span for create index', (done) => { - tracer.startRootSpan({name: 'indexRootSpan'}, (rootSpan: Span) => { - collection.createIndex({a: 1}, (err, result) => { + it('should create a child span for create index', done => { + tracer.startRootSpan({ name: 'indexRootSpan' }, (rootSpan: Span) => { + collection.createIndex({ a: 1 }, (err, result) => { assert.strictEqual(rootSpanVerifier.endedSpans.length, 1); rootSpan.end(); assert.ifError(err); assertSpan( - rootSpanVerifier, `${DB_NAME}.$cmd.createIndexes`, - SpanKind.SERVER); + rootSpanVerifier, + `${DB_NAME}.$cmd.createIndexes`, + SpanKind.SERVER + ); done(); }); }); }); - it('should create a child span for count', (done) => { - tracer.startRootSpan({name: 'countRootSpan'}, (rootSpan: Span) => { - collection.count({a: 1}, (err, result) => { + it('should create a child span for count', done => { + tracer.startRootSpan({ name: 'countRootSpan' }, (rootSpan: Span) => { + collection.count({ a: 1 }, (err, result) => { assert.strictEqual(rootSpanVerifier.endedSpans.length, 1); rootSpan.end(); assert.ifError(err); assertSpan( - rootSpanVerifier, `${DB_NAME}.$cmd.count`, SpanKind.SERVER); + rootSpanVerifier, + `${DB_NAME}.$cmd.count`, + SpanKind.SERVER + ); done(); }); }); @@ -243,10 +265,10 @@ describe('MongoDBPlugin', () => { plugin.applyUnpatch(); }); - it('should not create a child span for query', (done) => { - const insertData = [{a: 1}, {a: 2}, {a: 3}]; + it('should not create a child span for query', done => { + const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; - tracer.startRootSpan({name: 'insertRootSpan'}, (rootSpan: Span) => { + tracer.startRootSpan({ name: 'insertRootSpan' }, (rootSpan: Span) => { collection.insertMany(insertData, (err, result) => { assert.strictEqual(rootSpanVerifier.endedSpans.length, 0); rootSpan.end(); @@ -258,8 +280,8 @@ describe('MongoDBPlugin', () => { }); }); - it('should not create a child span for cursor', (done) => { - tracer.startRootSpan({name: 'findRootSpan'}, (rootSpan: Span) => { + it('should not create a child span for cursor', done => { + tracer.startRootSpan({ name: 'findRootSpan' }, (rootSpan: Span) => { collection.find({}).toArray((err, result) => { assert.strictEqual(rootSpanVerifier.endedSpans.length, 0); rootSpan.end(); @@ -271,9 +293,9 @@ describe('MongoDBPlugin', () => { }); }); - it('should not create a child span for command', (done) => { - tracer.startRootSpan({name: 'indexRootSpan'}, (rootSpan: Span) => { - collection.createIndex({a: 1}, (err, result) => { + it('should not create a child span for command', done => { + tracer.startRootSpan({ name: 'indexRootSpan' }, (rootSpan: Span) => { + collection.createIndex({ a: 1 }, (err, result) => { assert.strictEqual(rootSpanVerifier.endedSpans.length, 0); rootSpan.end(); assert.ifError(err); diff --git a/packages/opencensus-instrumentation-redis/package-lock.json b/packages/opencensus-instrumentation-redis/package-lock.json index 27652a572..3502a5a3a 100644 --- a/packages/opencensus-instrumentation-redis/package-lock.json +++ b/packages/opencensus-instrumentation-redis/package-lock.json @@ -224,58 +224,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -386,16 +334,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -476,9 +414,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -894,21 +832,28 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" + }, + "dependencies": { + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" + } } }, "handlebars": { @@ -937,21 +882,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1040,9 +970,9 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.2.tgz", - "integrity": "sha512-Z2rREiXA6cHRR9KBOarR3WuLlFzlIfAEIiB45ll5SSadMg7WqOh1MKEjjndfuH5ewXdixWCxqnVfGOQzPeiztA==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { "ansi-escapes": "^3.2.0", "chalk": "^2.4.2", @@ -1055,7 +985,7 @@ "run-async": "^2.2.0", "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" } }, @@ -1280,15 +1210,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.1.tgz", - "integrity": "sha512-um46hB9wNOKlwkHgiuyEVAybXBjwFUV0Z/RaHJblRd9DXltue9FTYvzCr9ErQrK9Adz5MU4gHWVaNUfdmrC8qA==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2110,6 +2035,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2196,9 +2126,9 @@ "integrity": "sha1-Uu0J2srBCPGmMcB+m2mUHnoZUEs=" }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2269,9 +2199,9 @@ } }, "rxjs": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.4.0.tgz", - "integrity": "sha512-Z9Yfa11F6B9Sg/BK9MnqnQ+aQYicPLtilXBp2yUtDt2JRCE0h26d33EnfO3ZxoNxG0T92OUucP3Ct7cpfkdFfw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2421,17 +2351,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2597,23 +2527,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.13.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.13.0.tgz", - "integrity": "sha512-ECOOQRxXCYnUUePG5h/+Z1Zouobk3KFpIHA9aKBB/nnMxs97S1JJPDGt5J4cGm1y9U9VmVlfboOxA8n1kSNzGw==", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" }, "dependencies": { "semver": { diff --git a/packages/opencensus-instrumentation-redis/package.json b/packages/opencensus-instrumentation-redis/package.json index 2df573393..011678c18 100644 --- a/packages/opencensus-instrumentation-redis/package.json +++ b/packages/opencensus-instrumentation-redis/package.json @@ -45,7 +45,7 @@ "@types/semver": "^6.0.0", "@types/shimmer": "^1.0.1", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "^14.0.0", "redis": "^2.8.0", diff --git a/packages/opencensus-instrumentation-redis/src/redis.ts b/packages/opencensus-instrumentation-redis/src/redis.ts index a74ad2cca..d7b712ebd 100644 --- a/packages/opencensus-instrumentation-redis/src/redis.ts +++ b/packages/opencensus-instrumentation-redis/src/redis.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {BasePlugin, CanonicalCode, Span, SpanKind} from '@opencensus/core'; +import { BasePlugin, CanonicalCode, Span, SpanKind } from '@opencensus/core'; import * as redis from 'redis'; import * as semver from 'semver'; import * as shimmer from 'shimmer'; @@ -50,15 +50,22 @@ export class RedisPlugin extends BasePlugin { if (this.moduleExports.RedisClient) { this.logger.debug('patching redis.RedisClient.prototype.create_stream'); shimmer.wrap( - this.moduleExports.RedisClient.prototype, 'create_stream', - this.getPatchCreateStream()); + this.moduleExports.RedisClient.prototype, + 'create_stream', + this.getPatchCreateStream() + ); this.logger.debug('patching redis.RedisClient.prototype.internal_send'); shimmer.wrap( - this.moduleExports.RedisClient.prototype, 'internal_send_command', - this.getPatchSendCommand()); + this.moduleExports.RedisClient.prototype, + 'internal_send_command', + this.getPatchSendCommand() + ); this.logger.debug('patching redis.RedisClient.prototype.createClient'); shimmer.wrap( - this.moduleExports, 'createClient', this.getPatchCreateClient()); + this.moduleExports, + 'createClient', + this.getPatchCreateClient() + ); } return this.moduleExports; } @@ -68,7 +75,9 @@ export class RedisPlugin extends BasePlugin { if (semver.lt(this.version, '2.6.0')) return; shimmer.unwrap( - this.moduleExports.RedisClient.prototype, 'internal_send_command'); + this.moduleExports.RedisClient.prototype, + 'internal_send_command' + ); shimmer.unwrap(this.moduleExports, 'createClient'); shimmer.unwrap(this.moduleExports.RedisClient.prototype, 'create_stream'); } @@ -87,7 +96,7 @@ export class RedisPlugin extends BasePlugin { set(val) { plugin.tracer.wrapEmitter(val); this._patched_redis_stream = val; - } + }, }); } return original.apply(this, arguments); @@ -99,12 +108,13 @@ export class RedisPlugin extends BasePlugin { private getPatchCreateClient() { const plugin = this; return function createClientWrap(original: Function) { - return function createClientTrace(this: redis.RedisClient): - redis.RedisClient { - const client: redis.RedisClient = original.apply(this, arguments); - plugin.tracer.wrapEmitter(client); - return client; - }; + return function createClientTrace( + this: redis.RedisClient + ): redis.RedisClient { + const client: redis.RedisClient = original.apply(this, arguments); + plugin.tracer.wrapEmitter(client); + return client; + }; }; } @@ -113,15 +123,19 @@ export class RedisPlugin extends BasePlugin { const plugin = this; return function internalSendCommandWrap(original: Function) { return function internal_send_command_trace( - this: redis.RedisClient, cmd: RedisCommand|undefined) { + this: redis.RedisClient, + cmd: RedisCommand | undefined + ) { if (!plugin.tracer.currentRootSpan) { return original.apply(this, arguments); } // New versions of redis (2.4+) use a single options object instead // of separate named arguments. if (arguments.length === 1 && typeof cmd === 'object') { - const span = plugin.tracer.startChildSpan( - {name: `redis-${cmd.command}`, kind: SpanKind.CLIENT}); + const span = plugin.tracer.startChildSpan({ + name: `redis-${cmd.command}`, + kind: SpanKind.CLIENT, + }); if (span === null) return original.apply(this, arguments); span.addAttribute('command', cmd.command); @@ -153,4 +167,4 @@ export class RedisPlugin extends BasePlugin { } const plugin = new RedisPlugin('redis'); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-instrumentation-redis/test/test-redis.ts b/packages/opencensus-instrumentation-redis/test/test-redis.ts index 648233d05..03830dfeb 100644 --- a/packages/opencensus-instrumentation-redis/test/test-redis.ts +++ b/packages/opencensus-instrumentation-redis/test/test-redis.ts @@ -14,11 +14,17 @@ * limitations under the License. */ -import {CoreTracer, logger, Span, SpanEventListener, SpanKind} from '@opencensus/core'; +import { + CoreTracer, + logger, + Span, + SpanEventListener, + SpanKind, +} from '@opencensus/core'; import * as assert from 'assert'; import * as redis from 'redis'; -import {plugin} from '../src'; +import { plugin } from '../src'; /** Collects ended root spans to allow for later analysis. */ class SpanVerifier implements SpanEventListener { @@ -40,14 +46,21 @@ class SpanVerifier implements SpanEventListener { * @param expectedKind The expected kind of the first root span. */ function assertSpan( - rootSpanVerifier: SpanVerifier, expectedName: string, - expectedKind: SpanKind, verifyAttribute?: (span: Span) => boolean) { + rootSpanVerifier: SpanVerifier, + expectedName: string, + expectedKind: SpanKind, + verifyAttribute?: (span: Span) => boolean +) { assert.strictEqual(rootSpanVerifier.endedSpans.length, 2); assert.strictEqual(rootSpanVerifier.endedSpans[1].spans.length, 1); assert.strictEqual( - rootSpanVerifier.endedSpans[1].spans[0].name, expectedName); + rootSpanVerifier.endedSpans[1].spans[0].name, + expectedName + ); assert.strictEqual( - rootSpanVerifier.endedSpans[1].spans[0].kind, expectedKind); + rootSpanVerifier.endedSpans[1].spans[0].kind, + expectedKind + ); if (typeof verifyAttribute === 'function') { for (const span of rootSpanVerifier.endedSpans[1].spans) { assert(verifyAttribute(span), 'failed to verify attribute'); @@ -56,7 +69,7 @@ function assertSpan( } describe('RedisPlugin', () => { - // For these tests, mongo must be runing. Add OPENCENSUS_REDIS_TESTS to run + // For these tests, mongo must be running. Add OPENCENSUS_REDIS_TESTS to run // these tests. const OPENCENSUS_REDIS_TESTS = process.env.OPENCENSUS_REDIS_TESTS; const OPENCENSUS_REDIS_HOST = process.env.OPENCENSUS_REDIS_HOST; @@ -73,12 +86,12 @@ describe('RedisPlugin', () => { const rootSpanVerifier = new SpanVerifier(); let client: redis.RedisClient; - before((done) => { - tracer.start({samplingRate: 1, logger: logger.logger(1)}); + before(done => { + tracer.start({ samplingRate: 1, logger: logger.logger(1) }); tracer.registerSpanEventListener(rootSpanVerifier); plugin.enable(redis, tracer, VERSION, {}, ''); - client = redis.createClient({url: URL}); - client.on('error', (err) => { + client = redis.createClient({ url: URL }); + client.on('error', err => { done(err); }); client.on('ready', done); @@ -96,7 +109,7 @@ describe('RedisPlugin', () => { client.set('test', 'data', done); }); - afterEach((done) => { + afterEach(done => { client.del('hash', done); }); @@ -108,47 +121,44 @@ describe('RedisPlugin', () => { /** Should intercept query */ describe('Instrumenting query operations', () => { - it('should create a child span for hset', (done) => { - tracer.startRootSpan({name: 'insertRootSpan'}, (rootSpan: Span) => { + it('should create a child span for hset', done => { + tracer.startRootSpan({ name: 'insertRootSpan' }, (rootSpan: Span) => { client.hset('hash', 'random', 'random', (err, result) => { assert.ifError(err); assert.strictEqual(rootSpanVerifier.endedSpans.length, 1); rootSpan.end(); - assertSpan( - rootSpanVerifier, `redis-hset`, REDIS_QUERY_TYPE, (span) => { - return span.attributes.arguments === undefined; - }); + assertSpan(rootSpanVerifier, `redis-hset`, REDIS_QUERY_TYPE, span => { + return span.attributes.arguments === undefined; + }); done(); }); }); }); - it('should create a child span for get', (done) => { - tracer.startRootSpan({name: 'getRootSpan'}, (rootSpan: Span) => { + it('should create a child span for get', done => { + tracer.startRootSpan({ name: 'getRootSpan' }, (rootSpan: Span) => { client.get('test', (err, result) => { assert.ifError(err); assert.strictEqual(result, 'data'); assert.strictEqual(rootSpanVerifier.endedSpans.length, 1); rootSpan.end(); - assertSpan( - rootSpanVerifier, `redis-get`, REDIS_QUERY_TYPE, (span) => { - return span.attributes.arguments === undefined; - }); + assertSpan(rootSpanVerifier, `redis-get`, REDIS_QUERY_TYPE, span => { + return span.attributes.arguments === undefined; + }); done(); }); }); }); - it('should create a child span for del', (done) => { - tracer.startRootSpan({name: 'removeRootSpan'}, (rootSpan: Span) => { + it('should create a child span for del', done => { + tracer.startRootSpan({ name: 'removeRootSpan' }, (rootSpan: Span) => { client.del('test', (err, result) => { assert.ifError(err); assert.strictEqual(rootSpanVerifier.endedSpans.length, 1); rootSpan.end(); - assertSpan( - rootSpanVerifier, `redis-del`, REDIS_QUERY_TYPE, (span) => { - return span.attributes.arguments === undefined; - }); + assertSpan(rootSpanVerifier, `redis-del`, REDIS_QUERY_TYPE, span => { + return span.attributes.arguments === undefined; + }); done(); }); }); @@ -161,8 +171,8 @@ describe('RedisPlugin', () => { plugin.applyUnpatch(); }); - it('should not create a child span for insert', (done) => { - tracer.startRootSpan({name: 'insertRootSpan'}, (rootSpan: Span) => { + it('should not create a child span for insert', done => { + tracer.startRootSpan({ name: 'insertRootSpan' }, (rootSpan: Span) => { client.hset('hash', 'random', 'random', (err, result) => { assert.ifError(err); assert.strictEqual(rootSpanVerifier.endedSpans.length, 0); @@ -174,8 +184,8 @@ describe('RedisPlugin', () => { }); }); - it('should not create a child span for get', (done) => { - tracer.startRootSpan({name: 'getRootSpan'}, (rootSpan: Span) => { + it('should not create a child span for get', done => { + tracer.startRootSpan({ name: 'getRootSpan' }, (rootSpan: Span) => { client.get('test', (err, result) => { assert.ifError(err); assert.strictEqual(result, 'data'); @@ -187,8 +197,8 @@ describe('RedisPlugin', () => { }); }); - it('should not create a child span for del', (done) => { - tracer.startRootSpan({name: 'removeRootSpan'}, (rootSpan: Span) => { + it('should not create a child span for del', done => { + tracer.startRootSpan({ name: 'removeRootSpan' }, (rootSpan: Span) => { client.del('test', (err, result) => { assert.ifError(err); assert.strictEqual(rootSpanVerifier.endedSpans.length, 0); diff --git a/packages/opencensus-nodejs-base/package-lock.json b/packages/opencensus-nodejs-base/package-lock.json index c580f7cac..c97324995 100644 --- a/packages/opencensus-nodejs-base/package-lock.json +++ b/packages/opencensus-nodejs-base/package-lock.json @@ -165,9 +165,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -223,58 +223,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -405,16 +353,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -497,8 +435,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -904,37 +841,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -965,21 +902,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1068,23 +990,43 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } } }, "intercept-stdout": { @@ -1337,15 +1279,10 @@ "handlebars": "^4.1.2" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2092,9 +2029,9 @@ "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" }, "path-parse": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz", - "integrity": "sha1-PBrfhx6pzWyUMbbqK9dKD/BVxME=" + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==" }, "path-type": { "version": "3.0.0", @@ -2169,6 +2106,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2235,9 +2177,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2303,11 +2245,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.5.0.tgz", - "integrity": "sha512-hgoSGrc3pjzAPHNBg+KnFcK2HwlHTs/YrAGUr6qgTVUZmXv1UEXXl0bZNBKMA9fud6lRYFdPGz0xXxycPzmmiw==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2341,9 +2283,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2479,17 +2421,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2663,29 +2605,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2850,9 +2786,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-nodejs-base/package.json b/packages/opencensus-nodejs-base/package.json index d04e16509..b3103b54b 100644 --- a/packages/opencensus-nodejs-base/package.json +++ b/packages/opencensus-nodejs-base/package.json @@ -45,7 +45,7 @@ "@types/node": "^10.12.12", "@types/shimmer": "^1.0.1", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "intercept-stdout": "^0.1.2", "mocha": "^6.1.0", "nyc": "14.1.1", diff --git a/packages/opencensus-nodejs-base/src/trace/config/default-config.ts b/packages/opencensus-nodejs-base/src/trace/config/default-config.ts index f30940526..27853287d 100644 --- a/packages/opencensus-nodejs-base/src/trace/config/default-config.ts +++ b/packages/opencensus-nodejs-base/src/trace/config/default-config.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {Constants} from '../constants'; +import { Constants } from '../constants'; /** * Defines a default configuration. For fields with primitive values, @@ -30,5 +30,5 @@ export const defaultConfig = { bufferSize: Constants.DEFAULT_BUFFER_SIZE, bufferTimeout: Constants.DEFAULT_BUFFER_TIMEOUT, samplingRate: 1, - traceParams: Constants.DEFAULT_TRACE_PARAMS + traceParams: Constants.DEFAULT_TRACE_PARAMS, }; diff --git a/packages/opencensus-nodejs-base/src/trace/constants.ts b/packages/opencensus-nodejs-base/src/trace/constants.ts index 5e34f16bb..c498554bc 100644 --- a/packages/opencensus-nodejs-base/src/trace/constants.ts +++ b/packages/opencensus-nodejs-base/src/trace/constants.ts @@ -29,8 +29,8 @@ const constants = { numberOfAnnontationEventsPerSpan: 32, numberOfAttributesPerSpan: 32, numberOfLinksPerSpan: 32, - numberOfMessageEventsPerSpan: 128 - } + numberOfMessageEventsPerSpan: 128, + }, }; -export {constants as Constants}; +export { constants as Constants }; diff --git a/packages/opencensus-nodejs-base/src/trace/instrumentation/plugin-loader.ts b/packages/opencensus-nodejs-base/src/trace/instrumentation/plugin-loader.ts index 209ee3fd2..c1f16616a 100644 --- a/packages/opencensus-nodejs-base/src/trace/instrumentation/plugin-loader.ts +++ b/packages/opencensus-nodejs-base/src/trace/instrumentation/plugin-loader.ts @@ -14,16 +14,23 @@ * limitations under the License. */ -import {Logger, Plugin, PluginConfig, PluginNames, Stats, TracerBase} from '@opencensus/core'; +import { + Logger, + Plugin, + PluginConfig, + PluginNames, + Stats, + TracerBase, +} from '@opencensus/core'; import * as fs from 'fs'; import * as path from 'path'; import * as hook from 'require-in-the-middle'; -import {Constants} from '../constants'; +import { Constants } from '../constants'; enum HookState { UNINITIALIZED, ENABLED, - DISABLED + DISABLED, } /** @@ -64,7 +71,8 @@ export class PluginLoader { */ private static defaultPackageName(moduleName: string): string { return `${Constants.OPENCENSUS_SCOPE}/${ - Constants.DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX}-${moduleName}`; + Constants.DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX + }-${moduleName}`; } /** @@ -74,15 +82,16 @@ export class PluginLoader { * @returns Plugin names. */ static defaultPluginsFromArray(modulesToPatch: string[]): PluginNames { - const plugins = - modulesToPatch.reduce((plugins: PluginNames, moduleName: string) => { - plugins[moduleName] = PluginLoader.defaultPackageName(moduleName); - return plugins; - }, {} as PluginNames); + const plugins = modulesToPatch.reduce( + (plugins: PluginNames, moduleName: string) => { + plugins[moduleName] = PluginLoader.defaultPackageName(moduleName); + return plugins; + }, + {} as PluginNames + ); return plugins; } - /** * Gets the package version. * @param name Name. @@ -96,7 +105,10 @@ export class PluginLoader { version = JSON.parse(fs.readFileSync(pkgJson).toString()).version; } catch (e) { this.logger.error( - 'could not get version of %s module: %s', name, e.message); + 'could not get version of %s module: %s', + name, + e.message + ); } } else { version = process.versions.node; @@ -104,7 +116,6 @@ export class PluginLoader { return version; } - /** * Loads a list of plugins (using a map of the target module name * and its instrumentation plugin package name). Each plugin module @@ -142,11 +153,20 @@ export class PluginLoader { const plugin: Plugin = require(moduleName as string).plugin; this.plugins.push(plugin); return plugin.enable( - exports, this.tracer, version, moduleConfig, basedir, this.stats); + exports, + this.tracer, + version, + moduleConfig, + basedir, + this.stats + ); } catch (e) { this.logger.error( - 'could not load plugin %s of module %s. Error: %s', moduleName, - name, e.message); + 'could not load plugin %s of module %s. Error: %s', + moduleName, + name, + e.message + ); return exports; } }); diff --git a/packages/opencensus-nodejs-base/src/trace/tracing-base.ts b/packages/opencensus-nodejs-base/src/trace/tracing-base.ts index 74417c0dd..85f54f99b 100644 --- a/packages/opencensus-nodejs-base/src/trace/tracing-base.ts +++ b/packages/opencensus-nodejs-base/src/trace/tracing-base.ts @@ -14,10 +14,10 @@ * limitations under the License. */ import * as core from '@opencensus/core'; -import {logger} from '@opencensus/core'; +import { logger } from '@opencensus/core'; import * as extend from 'extend'; -import {defaultConfig} from './config/default-config'; -import {PluginLoader} from './instrumentation/plugin-loader'; +import { defaultConfig } from './config/default-config'; +import { PluginLoader } from './instrumentation/plugin-loader'; const NOOP_EXPORTER = new core.NoopExporter(); @@ -64,16 +64,24 @@ export class TracingBase implements core.Tracing { * @param userConfig A configuration object to start tracing. * @returns The started Tracing instance. */ - start(userConfig?: core.Config): core.Tracing|TracingBase { + start(userConfig?: core.Config): core.Tracing | TracingBase { this.configLocal = extend( - true, {}, defaultConfig, {plugins: this.defaultPlugins}, userConfig); + true, + {}, + defaultConfig, + { plugins: this.defaultPlugins }, + userConfig + ); this.logger = - this.configLocal.logger || logger.logger(this.configLocal.logLevel); + this.configLocal.logger || logger.logger(this.configLocal.logLevel); this.configLocal.logger = this.logger; this.logger.debug('config: %o', this.configLocal); - this.pluginLoader = - new PluginLoader(this.logger, this.tracer, this.configLocal.stats); + this.pluginLoader = new PluginLoader( + this.logger, + this.tracer, + this.configLocal.stats + ); this.pluginLoader.loadPlugins(this.configLocal.plugins as core.PluginNames); if (!this.configLocal.exporter) { @@ -100,16 +108,16 @@ export class TracingBase implements core.Tracing { /** Gets the exporter. */ get exporter(): core.Exporter { - return this.configLocal.exporter ? - this.configLocal.exporter as core.Exporter : - NOOP_EXPORTER; + return this.configLocal.exporter + ? (this.configLocal.exporter as core.Exporter) + : NOOP_EXPORTER; } /** * Registers an exporter to send the collected traces to. * @param exporter The exporter to send the traces to. */ - registerExporter(exporter: core.Exporter): core.Tracing|TracingBase { + registerExporter(exporter: core.Exporter): core.Tracing | TracingBase { if (this.configLocal.exporter) { this.unregisterExporter(this.configLocal.exporter); } diff --git a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/@opencensus/instrumentation-load-internal-file-module/load-internal-file-module.ts b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/@opencensus/instrumentation-load-internal-file-module/load-internal-file-module.ts index ebbef3d93..9ac755983 100644 --- a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/@opencensus/instrumentation-load-internal-file-module/load-internal-file-module.ts +++ b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/@opencensus/instrumentation-load-internal-file-module/load-internal-file-module.ts @@ -14,34 +14,37 @@ * limitations under the License. */ -import {BasePlugin, PluginInternalFiles} from '@opencensus/core'; +import { BasePlugin, PluginInternalFiles } from '@opencensus/core'; import * as shimmer from 'shimmer'; - export class SimpleModulePlugin extends BasePlugin { - protected internalFileList: - PluginInternalFiles = {'~0.0.1': {'extra-module': 'src/extra-module'}}; + protected internalFileList: PluginInternalFiles = { + '~0.0.1': { 'extra-module': 'src/extra-module' }, + }; constructor() { super('load-internal-file-module'); } - protected applyPatch() { - shimmer.wrap( - this.moduleExports, 'name', (orig) => () => 'patched-' + orig.apply()); - - shimmer.wrap(this.moduleExports, 'value', (orig) => () => orig.apply() + 1); + shimmer.wrap(this.moduleExports, 'name', orig => () => + 'patched-' + orig.apply() + ); + shimmer.wrap(this.moduleExports, 'value', orig => () => orig.apply() + 1); if (this.internalFilesExports) { shimmer.wrap( - this.internalFilesExports['extra-module'], 'name', - (orig) => () => 'patched-' + orig.apply()); + this.internalFilesExports['extra-module'], + 'name', + orig => () => 'patched-' + orig.apply() + ); shimmer.wrap( - this.internalFilesExports['extra-module'], 'value', - (orig) => () => orig.apply() + 1); + this.internalFilesExports['extra-module'], + 'value', + orig => () => orig.apply() + 1 + ); } return this.moduleExports; @@ -54,4 +57,4 @@ export class SimpleModulePlugin extends BasePlugin { } const plugin = new SimpleModulePlugin(); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/@opencensus/instrumentation-simple-module/simple-module.ts b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/@opencensus/instrumentation-simple-module/simple-module.ts index 0ed72d5d5..f379e5c64 100644 --- a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/@opencensus/instrumentation-simple-module/simple-module.ts +++ b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/@opencensus/instrumentation-simple-module/simple-module.ts @@ -14,24 +14,23 @@ * limitations under the License. */ -import {BasePlugin} from '@opencensus/core'; +import { BasePlugin } from '@opencensus/core'; import * as shimmer from 'shimmer'; - export class SimpleModulePlugin extends BasePlugin { constructor() { super('simple-module'); } - protected applyPatch() { this.logger.debug('apply path to simple module'); - shimmer.wrap( - this.moduleExports, 'name', (orig) => () => 'patched-' + orig.apply()); + shimmer.wrap(this.moduleExports, 'name', orig => () => + 'patched-' + orig.apply() + ); - shimmer.wrap(this.moduleExports, 'value', (orig) => () => orig.apply() + 1); + shimmer.wrap(this.moduleExports, 'value', orig => () => orig.apply() + 1); return this.moduleExports; } @@ -43,4 +42,4 @@ export class SimpleModulePlugin extends BasePlugin { } const plugin = new SimpleModulePlugin(); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/enduser-simple-module-plugin/enduser-simple-module-plugin.ts b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/enduser-simple-module-plugin/enduser-simple-module-plugin.ts index c4b47f520..81dfd2ef7 100644 --- a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/enduser-simple-module-plugin/enduser-simple-module-plugin.ts +++ b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/enduser-simple-module-plugin/enduser-simple-module-plugin.ts @@ -14,20 +14,19 @@ * limitations under the License. */ -import {BasePlugin} from '@opencensus/core'; +import { BasePlugin } from '@opencensus/core'; import * as shimmer from 'shimmer'; - export class MySimpleModulePlugin extends BasePlugin { constructor() { super('simple-module'); } protected applyPatch() { - shimmer.wrap( - this.moduleExports, 'name', - (orig) => () => 'my-patched-' + orig.apply()); - shimmer.wrap(this.moduleExports, 'value', (orig) => () => orig.apply() + 2); + shimmer.wrap(this.moduleExports, 'name', orig => () => + 'my-patched-' + orig.apply() + ); + shimmer.wrap(this.moduleExports, 'value', orig => () => orig.apply() + 2); return this.moduleExports; } @@ -38,4 +37,4 @@ export class MySimpleModulePlugin extends BasePlugin { } const plugin = new MySimpleModulePlugin(); -export {plugin}; +export { plugin }; diff --git a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/load-internal-file-module/index.ts b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/load-internal-file-module/index.ts index 35edb1f74..50e71d4c3 100644 --- a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/load-internal-file-module/index.ts +++ b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/load-internal-file-module/index.ts @@ -1,9 +1,8 @@ - const extraModule = require('./src/extra-module'); export = { name: () => 'load-internal-file-module', value: () => 110, extraName: () => extraModule.name(), - extraValue: () => extraModule.value() + extraValue: () => extraModule.value(), }; diff --git a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/load-internal-file-module/src/extra-module.ts b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/load-internal-file-module/src/extra-module.ts index 5c4336e55..f03cfc9b9 100644 --- a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/load-internal-file-module/src/extra-module.ts +++ b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/load-internal-file-module/src/extra-module.ts @@ -1,4 +1,4 @@ export = { name: () => 'extra-module', - value: () => 120 + value: () => 120, }; diff --git a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/simple-module/index.ts b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/simple-module/index.ts index 8c4803f1d..84a55506e 100644 --- a/packages/opencensus-nodejs-base/test/instrumentation/node_modules/simple-module/index.ts +++ b/packages/opencensus-nodejs-base/test/instrumentation/node_modules/simple-module/index.ts @@ -1,4 +1,4 @@ export = { name: () => 'simple-module', - value: () => 100 + value: () => 100, }; diff --git a/packages/opencensus-nodejs-base/test/test-plugin-loader.ts b/packages/opencensus-nodejs-base/test/test-plugin-loader.ts index dd26c1d3d..2681137b4 100644 --- a/packages/opencensus-nodejs-base/test/test-plugin-loader.ts +++ b/packages/opencensus-nodejs-base/test/test-plugin-loader.ts @@ -14,23 +14,19 @@ * limitations under the License. */ -import {CoreTracerBase, logger} from '@opencensus/core'; +import { CoreTracerBase, logger } from '@opencensus/core'; import * as assert from 'assert'; -import {Constants} from '../src/trace/constants'; -import {PluginLoader} from '../src/trace/instrumentation/plugin-loader'; +import { Constants } from '../src/trace/constants'; +import { PluginLoader } from '../src/trace/instrumentation/plugin-loader'; const INSTALLED_PLUGINS_PATH = `${__dirname}/instrumentation/node_modules`; const TEST_MODULES = [ - 'simple-module' // this module exist and has a plugin - , - 'nonexistent-module' // this module does not exist - , - 'http' // this module does not have a plugin - , - 'load-internal-file-module' // this module has an internal file not exported + 'simple-module', // this module exist and has a plugin + 'nonexistent-module', // this module does not exist + 'http', // this module does not have a plugin + 'load-internal-file-module', // this module has an internal file not exported ]; - const clearRequireCache = () => { Object.keys(require.cache).forEach(key => delete require.cache[key]); }; @@ -47,11 +43,10 @@ describe('Plugin Loader', () => { clearRequireCache(); }); - describe('PluginLoader', () => { const plugins = PluginLoader.defaultPluginsFromArray(TEST_MODULES); const tracer = new CoreTracerBase(); - tracer.start({logger: log}); + tracer.start({ logger: log }); /** Should get the plugins to use. */ describe('static defaultPluginsFromArray()', () => { @@ -61,22 +56,27 @@ describe('Plugin Loader', () => { assert.ok(plugins[TEST_MODULES[2]]); assert.ok(plugins[TEST_MODULES[3]]); assert.strictEqual( - plugins[TEST_MODULES[0]], - `@opencensus/${ - Constants.DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX}-simple-module`); + plugins[TEST_MODULES[0]], + `@opencensus/${ + Constants.DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX + }-simple-module` + ); assert.strictEqual( - plugins[TEST_MODULES[1]], - `@opencensus/${ - Constants - .DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX}-nonexistent-module`); + plugins[TEST_MODULES[1]], + `@opencensus/${ + Constants.DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX + }-nonexistent-module` + ); assert.strictEqual( - plugins[TEST_MODULES[2]], - `@opencensus/${Constants.DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX}-http`); + plugins[TEST_MODULES[2]], + `@opencensus/${Constants.DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX}-http` + ); assert.strictEqual( - plugins[TEST_MODULES[3]], - `@opencensus/${ - Constants - .DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX}-load-internal-file-module`); + plugins[TEST_MODULES[3]], + `@opencensus/${ + Constants.DEFAULT_PLUGIN_PACKAGE_NAME_PREFIX + }-load-internal-file-module` + ); }); }); @@ -109,17 +109,20 @@ describe('Plugin Loader', () => { const loadInternalFileModule = require(moduleName); assert.strictEqual(pluginLoader.plugins.length, 1); assert.strictEqual( - loadInternalFileModule.name(), 'patched-' + moduleName); + loadInternalFileModule.name(), + 'patched-' + moduleName + ); assert.strictEqual(loadInternalFileModule.value(), 111); const extraModuleName = 'extra-module'; assert.strictEqual( - loadInternalFileModule.extraName(), 'patched-' + extraModuleName); + loadInternalFileModule.extraName(), + 'patched-' + extraModuleName + ); assert.strictEqual(loadInternalFileModule.extraValue(), 121); pluginLoader.unloadPlugins(); }); - it('should not load a non existing plugin and just log an error', () => { const intercept = require('intercept-stdout'); @@ -158,13 +161,15 @@ describe('Plugin Loader', () => { assert.strictEqual(pluginLoader.plugins.length, 0); const endUserPlugins = { - 'simple-module': 'enduser-simple-module-plugin' + 'simple-module': 'enduser-simple-module-plugin', }; pluginLoader.loadPlugins(endUserPlugins); const simpleModule = require(TEST_MODULES[0]); assert.strictEqual(pluginLoader.plugins.length, 1); assert.strictEqual( - simpleModule.name(), 'my-patched-' + TEST_MODULES[0]); + simpleModule.name(), + 'my-patched-' + TEST_MODULES[0] + ); assert.strictEqual(simpleModule.value(), 102); pluginLoader.unloadPlugins(); assert.strictEqual(pluginLoader.plugins.length, 0); diff --git a/packages/opencensus-nodejs-base/test/test-tracing.ts b/packages/opencensus-nodejs-base/test/test-tracing.ts index 93832ceea..c11073182 100644 --- a/packages/opencensus-nodejs-base/test/test-tracing.ts +++ b/packages/opencensus-nodejs-base/test/test-tracing.ts @@ -14,10 +14,10 @@ * limitations under the License. */ import * as core from '@opencensus/core'; -import {logger} from '@opencensus/core'; +import { logger } from '@opencensus/core'; import * as assert from 'assert'; -import {defaultConfig} from '../src/trace/config/default-config'; -import {TracingBase} from '../src/trace/tracing-base'; +import { defaultConfig } from '../src/trace/config/default-config'; +import { TracingBase } from '../src/trace/tracing-base'; const NOOP_EXPORTER = new core.NoopExporter(); describe('TracingBase', () => { @@ -64,91 +64,110 @@ describe('TracingBase', () => { tracing.start(); assert.strictEqual(defaultConfig.bufferSize, tracing.config.bufferSize); assert.strictEqual( - defaultConfig.bufferTimeout, tracing.config.bufferTimeout); + defaultConfig.bufferTimeout, + tracing.config.bufferTimeout + ); assert.strictEqual(defaultConfig.logLevel, tracing.config.logLevel); assert.strictEqual( - defaultConfig.maximumLabelValueSize, - tracing.config.maximumLabelValueSize); + defaultConfig.maximumLabelValueSize, + tracing.config.maximumLabelValueSize + ); assert.strictEqual( - defaultConfig.samplingRate, tracing.config.samplingRate); + defaultConfig.samplingRate, + tracing.config.samplingRate + ); assert.ok(tracing.config.plugins); if (tracing.config.plugins) { assert.deepStrictEqual( - tracing.config.plugins, {}, 'plugins are empty by default'); + tracing.config.plugins, + {}, + 'plugins are empty by default' + ); } assert.strictEqual( - defaultConfig.traceParams.numberOfAnnontationEventsPerSpan, 32); + defaultConfig.traceParams.numberOfAnnontationEventsPerSpan, + 32 + ); assert.strictEqual( - defaultConfig.traceParams.numberOfAttributesPerSpan, 32); + defaultConfig.traceParams.numberOfAttributesPerSpan, + 32 + ); assert.strictEqual(defaultConfig.traceParams.numberOfLinksPerSpan, 32); assert.strictEqual( - defaultConfig.traceParams.numberOfMessageEventsPerSpan, 128); + defaultConfig.traceParams.numberOfMessageEventsPerSpan, + 128 + ); }); it('should start tracing with a non-default logLevel', () => { - aTracingBase = tracing.start({logLevel: 3}); + aTracingBase = tracing.start({ logLevel: 3 }); assert.strictEqual(tracing.config.logLevel, 3); - const consoleLogger = - aTracingBase.tracer.logger as logger.ConsoleLogger; + const consoleLogger = aTracingBase.tracer + .logger as logger.ConsoleLogger; assert.strictEqual(consoleLogger.level, 'info'); }); it('should start tracing with a logger instance', () => { const aLogger = logger.logger('debug'); - aTracingBase = tracing.start({logger: aLogger}); + aTracingBase = tracing.start({ logger: aLogger }); assert.strictEqual(tracing.config.logger, aLogger); - const consoleLogger = - aTracingBase.tracer.logger as logger.ConsoleLogger; + const consoleLogger = aTracingBase.tracer + .logger as logger.ConsoleLogger; assert.strictEqual(consoleLogger.level, 'debug'); }); it('should start with an exporter instance', () => { - aTracingBase = tracing.start({exporter: NOOP_EXPORTER}); + aTracingBase = tracing.start({ exporter: NOOP_EXPORTER }); assert.strictEqual(tracing.config.exporter, NOOP_EXPORTER); assert.strictEqual(aTracingBase.exporter, NOOP_EXPORTER); }); it('should start with a non-default bufferSize', () => { const bufferSizeValue = defaultConfig.bufferSize + 1; - tracing.start({bufferSize: bufferSizeValue}); + tracing.start({ bufferSize: bufferSizeValue }); assert.strictEqual(tracing.config.bufferSize, bufferSizeValue); }); it('should start with a non-default bufferTimeout', () => { const bufferTimeoutValue = defaultConfig.bufferTimeout + 100; - tracing.start({bufferTimeout: bufferTimeoutValue}); + tracing.start({ bufferTimeout: bufferTimeoutValue }); assert.strictEqual(tracing.config.bufferTimeout, bufferTimeoutValue); }); it('should start with a non-default maximumLabelValueSize', () => { const maximumLabelValueSizeValue = - defaultConfig.maximumLabelValueSize + 10; - tracing.start({maximumLabelValueSize: maximumLabelValueSizeValue}); + defaultConfig.maximumLabelValueSize + 10; + tracing.start({ maximumLabelValueSize: maximumLabelValueSizeValue }); assert.strictEqual( - tracing.config.maximumLabelValueSize, maximumLabelValueSizeValue); + tracing.config.maximumLabelValueSize, + maximumLabelValueSizeValue + ); }); it('should start with a non-default samplingRate', () => { const samplingRateValue = defaultConfig.samplingRate / 100; - tracing.start({samplingRate: samplingRateValue}); + tracing.start({ samplingRate: samplingRateValue }); assert.strictEqual(tracing.config.samplingRate, samplingRateValue); }); it('should start with an user-provided plugin list', () => { const endUserPlugins = { - 'http': 'enduser-http-pluging', - 'simple-module': 'enduser-simple-module-pluging' + http: 'enduser-http-pluging', + 'simple-module': 'enduser-simple-module-pluging', }; - tracing.start({plugins: endUserPlugins}); + tracing.start({ plugins: endUserPlugins }); assert.ok(tracing.config.plugins); if (tracing.config.plugins) { // should overwrite default http plugin assert.strictEqual( - tracing.config.plugins['http'], endUserPlugins['http']); + tracing.config.plugins['http'], + endUserPlugins['http'] + ); // should add a new plugin assert.strictEqual( - tracing.config.plugins['simple-module'], - endUserPlugins['simple-module']); + tracing.config.plugins['simple-module'], + endUserPlugins['simple-module'] + ); } }); @@ -158,34 +177,50 @@ describe('TracingBase', () => { numberOfAttributesPerSpan: 10, numberOfAnnontationEventsPerSpan: 5, numberOfLinksPerSpan: 8, - numberOfMessageEventsPerSpan: 100 - } + numberOfMessageEventsPerSpan: 100, + }, }); assert.ok(tracing.config.traceParams); if (tracing.config.traceParams) { assert.strictEqual( - tracing.config.traceParams.numberOfAttributesPerSpan, 10); + tracing.config.traceParams.numberOfAttributesPerSpan, + 10 + ); assert.strictEqual( - tracing.config.traceParams.numberOfAnnontationEventsPerSpan, 5); + tracing.config.traceParams.numberOfAnnontationEventsPerSpan, + 5 + ); assert.strictEqual( - tracing.config.traceParams.numberOfLinksPerSpan, 8); + tracing.config.traceParams.numberOfLinksPerSpan, + 8 + ); assert.strictEqual( - tracing.config.traceParams.numberOfMessageEventsPerSpan, 100); + tracing.config.traceParams.numberOfMessageEventsPerSpan, + 100 + ); } }); it('should start with a non-default and default traceparams', () => { - tracing.start({traceParams: {numberOfAttributesPerSpan: 10}}); + tracing.start({ traceParams: { numberOfAttributesPerSpan: 10 } }); if (tracing.config.traceParams) { assert.strictEqual( - tracing.config.traceParams.numberOfAttributesPerSpan, 10); + tracing.config.traceParams.numberOfAttributesPerSpan, + 10 + ); assert.strictEqual( - tracing.config.traceParams.numberOfAnnontationEventsPerSpan, 32); + tracing.config.traceParams.numberOfAnnontationEventsPerSpan, + 32 + ); assert.strictEqual( - tracing.config.traceParams.numberOfLinksPerSpan, 32); + tracing.config.traceParams.numberOfLinksPerSpan, + 32 + ); assert.strictEqual( - tracing.config.traceParams.numberOfMessageEventsPerSpan, 128); + tracing.config.traceParams.numberOfMessageEventsPerSpan, + 128 + ); } }); }); diff --git a/packages/opencensus-nodejs/package-lock.json b/packages/opencensus-nodejs/package-lock.json index 452596d1a..e58378ca3 100644 --- a/packages/opencensus-nodejs/package-lock.json +++ b/packages/opencensus-nodejs/package-lock.json @@ -165,9 +165,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -223,58 +223,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -405,16 +353,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -497,8 +435,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -899,37 +836,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -960,21 +897,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1063,23 +985,43 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } } }, "intercept-stdout": { @@ -1332,15 +1274,10 @@ "handlebars": "^4.1.2" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2082,9 +2019,9 @@ "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" }, "path-parse": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz", - "integrity": "sha1-PBrfhx6pzWyUMbbqK9dKD/BVxME=" + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==" }, "path-type": { "version": "3.0.0", @@ -2159,6 +2096,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2225,9 +2167,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2260,11 +2202,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.5.0.tgz", - "integrity": "sha512-hgoSGrc3pjzAPHNBg+KnFcK2HwlHTs/YrAGUr6qgTVUZmXv1UEXXl0bZNBKMA9fud6lRYFdPGz0xXxycPzmmiw==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2298,9 +2240,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2436,17 +2378,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2620,29 +2562,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2807,9 +2743,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-nodejs/package.json b/packages/opencensus-nodejs/package.json index 84d482dff..90c6a33fd 100644 --- a/packages/opencensus-nodejs/package.json +++ b/packages/opencensus-nodejs/package.json @@ -45,7 +45,7 @@ "@types/node": "^10.12.12", "@types/shimmer": "^1.0.1", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "intercept-stdout": "^0.1.2", "mocha": "^6.1.0", "nyc": "14.1.1", diff --git a/packages/opencensus-nodejs/src/index.ts b/packages/opencensus-nodejs/src/index.ts index b884a0ffe..a232aec94 100644 --- a/packages/opencensus-nodejs/src/index.ts +++ b/packages/opencensus-nodejs/src/index.ts @@ -15,7 +15,7 @@ */ import * as core from '@opencensus/core'; -import {Tracing} from './trace/tracing'; +import { Tracing } from './trace/tracing'; const tracing: core.Tracing = Tracing.instance; diff --git a/packages/opencensus-nodejs/src/trace/tracing.ts b/packages/opencensus-nodejs/src/trace/tracing.ts index 1fb116aa4..e6ad52622 100644 --- a/packages/opencensus-nodejs/src/trace/tracing.ts +++ b/packages/opencensus-nodejs/src/trace/tracing.ts @@ -14,8 +14,8 @@ * limitations under the License. */ import * as core from '@opencensus/core'; -import {DEFAULT_INSTRUMENTATION_MODULES} from '@opencensus/instrumentation-all'; -import {TracingBase} from '@opencensus/nodejs-base'; +import { DEFAULT_INSTRUMENTATION_MODULES } from '@opencensus/instrumentation-all'; +import { TracingBase } from '@opencensus/nodejs-base'; /** Implements a Tracing with Continuation Local Storage (CLS). */ export class Tracing extends TracingBase { diff --git a/packages/opencensus-nodejs/test/test-tracing.ts b/packages/opencensus-nodejs/test/test-tracing.ts index 513cac90d..e0e27bba5 100644 --- a/packages/opencensus-nodejs/test/test-tracing.ts +++ b/packages/opencensus-nodejs/test/test-tracing.ts @@ -14,9 +14,9 @@ * limitations under the License. */ import * as core from '@opencensus/core'; -import {DEFAULT_INSTRUMENTATION_MODULES} from '@opencensus/instrumentation-all'; +import { DEFAULT_INSTRUMENTATION_MODULES } from '@opencensus/instrumentation-all'; import * as assert from 'assert'; -import {Tracing} from '../src/trace/tracing'; +import { Tracing } from '../src/trace/tracing'; describe('Tracing', () => { /** Should create a Tracing instance */ @@ -62,35 +62,40 @@ describe('Tracing', () => { tracing.start(); assert.ok(tracing.config.plugins); - DEFAULT_INSTRUMENTATION_MODULES.forEach((pluginName) => { + DEFAULT_INSTRUMENTATION_MODULES.forEach(pluginName => { if (tracing.config.plugins) { assert.ok(tracing.config.plugins[pluginName]); assert.strictEqual( - tracing.config.plugins[pluginName], - `@opencensus/instrumentation-${pluginName}`); + tracing.config.plugins[pluginName], + `@opencensus/instrumentation-${pluginName}` + ); } }); }); it('should start with an user-provided plugin list', () => { const endUserPlugins = { - 'http': 'enduser-http-pluging', - 'simple-module': 'enduser-simple-module-pluging' + http: 'enduser-http-pluging', + 'simple-module': 'enduser-simple-module-pluging', }; - tracing.start({plugins: endUserPlugins}); + tracing.start({ plugins: endUserPlugins }); assert.ok(tracing.config.plugins); if (tracing.config.plugins) { // should overwrite default http plugin assert.strictEqual( - tracing.config.plugins['http'], endUserPlugins['http']); + tracing.config.plugins['http'], + endUserPlugins['http'] + ); // should add a new plugin assert.strictEqual( - tracing.config.plugins['simple-module'], - endUserPlugins['simple-module']); + tracing.config.plugins['simple-module'], + endUserPlugins['simple-module'] + ); // should keep plugins default value assert.strictEqual( - tracing.config.plugins['https'], - '@opencensus/instrumentation-https'); + tracing.config.plugins['https'], + '@opencensus/instrumentation-https' + ); } }); }); diff --git a/packages/opencensus-propagation-b3/package-lock.json b/packages/opencensus-propagation-b3/package-lock.json index 7cd4ae144..b5107399c 100644 --- a/packages/opencensus-propagation-b3/package-lock.json +++ b/packages/opencensus-propagation-b3/package-lock.json @@ -169,9 +169,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -227,58 +227,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -409,16 +357,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -501,8 +439,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -909,37 +846,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -970,21 +907,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1073,23 +995,43 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } } }, "invert-kv": { @@ -1305,15 +1247,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2150,6 +2087,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2216,9 +2158,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2251,11 +2193,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2289,9 +2231,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2422,17 +2364,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2675,29 +2617,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2862,9 +2798,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-propagation-b3/package.json b/packages/opencensus-propagation-b3/package.json index ec654c44a..81d5aa161 100644 --- a/packages/opencensus-propagation-b3/package.json +++ b/packages/opencensus-propagation-b3/package.json @@ -53,7 +53,7 @@ "@types/node": "^10.12.12", "@types/uuid": "^3.4.3", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "^14.0.0", "rimraf": "^2.6.2", diff --git a/packages/opencensus-propagation-b3/src/b3-format.ts b/packages/opencensus-propagation-b3/src/b3-format.ts index 9d646be88..f62d89869 100644 --- a/packages/opencensus-propagation-b3/src/b3-format.ts +++ b/packages/opencensus-propagation-b3/src/b3-format.ts @@ -14,10 +14,15 @@ * limitations under the License. */ -import {HeaderGetter, HeaderSetter, Propagation, SpanContext} from '@opencensus/core'; +import { + HeaderGetter, + HeaderSetter, + Propagation, + SpanContext, +} from '@opencensus/core'; import * as crypto from 'crypto'; import * as uuid from 'uuid'; -import {isValidSpanId, isValidTraceId} from './validators'; +import { isValidSpanId, isValidTraceId } from './validators'; export const X_B3_TRACE_ID = 'x-b3-traceid'; export const X_B3_SPAN_ID = 'x-b3-spanid'; @@ -33,7 +38,7 @@ export class B3Format implements Propagation { * in the headers, null is returned. * @param getter */ - extract(getter: HeaderGetter): SpanContext|null { + extract(getter: HeaderGetter): SpanContext | null { const traceId = this.parseHeader(getter.getHeader(X_B3_TRACE_ID)); const spanId = this.parseHeader(getter.getHeader(X_B3_SPAN_ID)); const opt = this.parseHeader(getter.getHeader(X_B3_SAMPLED)); @@ -42,7 +47,7 @@ export class B3Format implements Propagation { return { traceId, spanId, - options: isNaN(Number(opt)) ? NOT_SAMPLED_VALUE : Number(opt) + options: isNaN(Number(opt)) ? NOT_SAMPLED_VALUE : Number(opt), }; } return null; @@ -54,8 +59,11 @@ export class B3Format implements Propagation { * @param spanContext */ inject(setter: HeaderSetter, spanContext: SpanContext): void { - if (!spanContext || !isValidTraceId(spanContext.traceId) || - !isValidSpanId(spanContext.spanId)) { + if ( + !spanContext || + !isValidTraceId(spanContext.traceId) || + !isValidSpanId(spanContext.spanId) + ) { return; } @@ -73,14 +81,17 @@ export class B3Format implements Propagation { */ generate(): SpanContext { return { - traceId: uuid.v4().split('-').join(''), + traceId: uuid + .v4() + .split('-') + .join(''), spanId: crypto.randomBytes(8).toString('hex'), - options: SAMPLED_VALUE + options: SAMPLED_VALUE, }; } /** Converts a headers type to a string. */ - private parseHeader(str: string|string[]|undefined): string|undefined { + private parseHeader(str: string | string[] | undefined): string | undefined { if (Array.isArray(str)) { return str[0]; } diff --git a/packages/opencensus-propagation-b3/src/validators.ts b/packages/opencensus-propagation-b3/src/validators.ts index f26fc180d..3fbcb858f 100644 --- a/packages/opencensus-propagation-b3/src/validators.ts +++ b/packages/opencensus-propagation-b3/src/validators.ts @@ -57,16 +57,27 @@ const compose = (...fns: ValidationFn[]): ValidationFn => { * Determines if the given traceId is valid based on section 2.2.2.1 of the * Trace Context spec. */ -export const isValidTraceId = compose(isHex, isNotAllZeros, isLength(32)); +export const isValidTraceId = compose( + isHex, + isNotAllZeros, + isLength(32) +); /** * Determines if the given spanId is valid based on section 2.2.2.2 of the Trace * Context spec. */ -export const isValidSpanId = compose(isHex, isNotAllZeros, isLength(16)); +export const isValidSpanId = compose( + isHex, + isNotAllZeros, + isLength(16) +); /** * Determines if the given option is valid based on section 2.2.3 of the Trace * Context spec. */ -export const isValidOption = compose(isHex, isLength(2)); +export const isValidOption = compose( + isHex, + isLength(2) +); diff --git a/packages/opencensus-propagation-b3/test/test-b3-format.ts b/packages/opencensus-propagation-b3/test/test-b3-format.ts index f538643ad..ee2f1cfa0 100644 --- a/packages/opencensus-propagation-b3/test/test-b3-format.ts +++ b/packages/opencensus-propagation-b3/test/test-b3-format.ts @@ -14,11 +14,18 @@ * limitations under the License. */ -import {HeaderGetter, HeaderSetter} from '@opencensus/core'; +import { HeaderGetter, HeaderSetter } from '@opencensus/core'; import * as assert from 'assert'; import * as uuid from 'uuid'; -import {B3Format, NOT_SAMPLED_VALUE, SAMPLED_VALUE, X_B3_SAMPLED, X_B3_SPAN_ID, X_B3_TRACE_ID} from '../src/'; +import { + B3Format, + NOT_SAMPLED_VALUE, + SAMPLED_VALUE, + X_B3_SAMPLED, + X_B3_SPAN_ID, + X_B3_TRACE_ID, +} from '../src/'; const b3Format = new B3Format(); @@ -37,14 +44,17 @@ describe('B3Propagation', () => { const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; assert.deepStrictEqual(b3Format.extract(getter), spanContext); }); it('should return null when options and spanId are undefined', () => { - const traceId = uuid.v4().split('-').join(''); + const traceId = uuid + .v4() + .split('-') + .join(''); // tslint:disable-next-line const headers = {} as any; headers[X_B3_TRACE_ID] = traceId; @@ -53,7 +63,7 @@ describe('B3Propagation', () => { const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; assert.deepStrictEqual(b3Format.extract(getter), null); @@ -68,7 +78,7 @@ describe('B3Propagation', () => { const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; assert.deepStrictEqual(b3Format.extract(getter), null); @@ -78,15 +88,20 @@ describe('B3Propagation', () => { const spanContext = b3Format.generate(); // tslint:disable-next-line const headers = {} as any; - headers[X_B3_TRACE_ID] = - [spanContext.traceId, uuid.v4().split('-').join('')]; + headers[X_B3_TRACE_ID] = [ + spanContext.traceId, + uuid + .v4() + .split('-') + .join(''), + ]; headers[X_B3_SPAN_ID] = [spanContext.spanId]; headers[X_B3_SAMPLED] = [SAMPLED_VALUE]; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; assert.deepStrictEqual(b3Format.extract(getter), spanContext); @@ -102,12 +117,12 @@ describe('B3Propagation', () => { const setter: HeaderSetter = { setHeader(name: string, value: string) { headers[name] = value; - } + }, }; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; b3Format.inject(setter, spanContext); @@ -126,12 +141,12 @@ describe('B3Propagation', () => { const setter: HeaderSetter = { setHeader(name: string, value: string) { headers[name] = value; - } + }, }; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; b3Format.inject(setter, emptySpanContext); @@ -139,23 +154,23 @@ describe('B3Propagation', () => { }); }); - // Same test as propagation-stackdriver. describe('generate', () => { const TIMES = 20; // Generate some span contexts. - const GENERATED = - Array.from({length: TIMES}).fill(0).map(_ => b3Format.generate()); + const GENERATED = Array.from({ length: TIMES }) + .fill(0) + .map(_ => b3Format.generate()); it('should generate unique traceIds', () => { const traceIds = GENERATED.map(c => c.traceId); - assert.strictEqual((new Set(traceIds)).size, TIMES); + assert.strictEqual(new Set(traceIds).size, TIMES); }); it('should generate unique spanIds', () => { const spanIds = GENERATED.map(c => c.spanId); - assert.strictEqual((new Set(spanIds)).size, TIMES); + assert.strictEqual(new Set(spanIds).size, TIMES); }); }); }); diff --git a/packages/opencensus-propagation-binaryformat/package-lock.json b/packages/opencensus-propagation-binaryformat/package-lock.json index feba403ae..7903aa83c 100644 --- a/packages/opencensus-propagation-binaryformat/package-lock.json +++ b/packages/opencensus-propagation-binaryformat/package-lock.json @@ -212,58 +212,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -369,16 +317,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -459,9 +397,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -868,21 +806,28 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" + }, + "dependencies": { + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" + } } }, "handlebars": { @@ -911,21 +856,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1014,9 +944,9 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.2.tgz", - "integrity": "sha512-Z2rREiXA6cHRR9KBOarR3WuLlFzlIfAEIiB45ll5SSadMg7WqOh1MKEjjndfuH5ewXdixWCxqnVfGOQzPeiztA==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { "ansi-escapes": "^3.2.0", "chalk": "^2.4.2", @@ -1029,7 +959,7 @@ "run-async": "^2.2.0", "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" } }, @@ -1251,15 +1181,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.1.tgz", - "integrity": "sha512-um46hB9wNOKlwkHgiuyEVAybXBjwFUV0Z/RaHJblRd9DXltue9FTYvzCr9ErQrK9Adz5MU4gHWVaNUfdmrC8qA==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2078,6 +2003,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2137,9 +2067,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2210,9 +2140,9 @@ } }, "rxjs": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.4.0.tgz", - "integrity": "sha512-Z9Yfa11F6B9Sg/BK9MnqnQ+aQYicPLtilXBp2yUtDt2JRCE0h26d33EnfO3ZxoNxG0T92OUucP3Ct7cpfkdFfw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2350,17 +2280,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2570,22 +2500,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.12.1.tgz", - "integrity": "sha512-sfodBHOucFg6egff8d1BvuofoOQ/nOeYNfbp7LDlKBcLNrL3lmS5zoiDGyOMdT7YsEXAwWpTdAHwOGOc8eRZAw==", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" } }, "tsutils": { diff --git a/packages/opencensus-propagation-binaryformat/package.json b/packages/opencensus-propagation-binaryformat/package.json index 6a19eb844..541b7ea52 100644 --- a/packages/opencensus-propagation-binaryformat/package.json +++ b/packages/opencensus-propagation-binaryformat/package.json @@ -52,7 +52,7 @@ "@types/mocha": "^5.2.5", "@types/node": "^10.12.12", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "^14.0.0", "rimraf": "^2.6.2", diff --git a/packages/opencensus-propagation-binaryformat/src/binary-format.ts b/packages/opencensus-propagation-binaryformat/src/binary-format.ts index dc94ed68b..8750b72b9 100644 --- a/packages/opencensus-propagation-binaryformat/src/binary-format.ts +++ b/packages/opencensus-propagation-binaryformat/src/binary-format.ts @@ -22,7 +22,7 @@ * master/encodings/BinaryEncoding.md */ -import {SpanContext} from '@opencensus/core'; +import { SpanContext } from '@opencensus/core'; const VERSION_ID = 0; const TRACE_ID_FIELD_ID = 0; @@ -44,7 +44,7 @@ const TRACE_OPTION_FIELD_ID_OFFSET = SPAN_ID_OFFSET + SPAN_ID_SIZE; const TRACE_OPTIONS_OFFSET = TRACE_OPTION_FIELD_ID_OFFSET + ID_SIZE; const FORMAT_LENGTH = - 4 * ID_SIZE + TRACE_ID_SIZE + SPAN_ID_SIZE + TRACE_OPTION_SIZE; + 4 * ID_SIZE + TRACE_ID_SIZE + SPAN_ID_SIZE + TRACE_OPTION_SIZE; /** * Serialize the given span context into a Buffer. @@ -83,25 +83,28 @@ export function serializeSpanContext(spanContext: SpanContext): Buffer { * null. * @param buffer The span context to deserialize. */ -export function deserializeSpanContext(buffer: Buffer): SpanContext|null { - const result: SpanContext = {traceId: '', spanId: ''}; +export function deserializeSpanContext(buffer: Buffer): SpanContext | null { + const result: SpanContext = { traceId: '', spanId: '' }; // Length must be 29. if (buffer.length !== FORMAT_LENGTH) { return null; } // Check version and field numbers. - if (buffer.readUInt8(VERSION_ID_OFFSET) !== VERSION_ID || - buffer.readUInt8(TRACE_ID_FIELD_ID_OFFSET) !== TRACE_ID_FIELD_ID || - buffer.readUInt8(SPAN_ID_FIELD_ID_OFFSET) !== SPAN_ID_FIELD_ID || - buffer.readUInt8(TRACE_OPTION_FIELD_ID_OFFSET) !== - TRACE_OPTION_FIELD_ID) { + if ( + buffer.readUInt8(VERSION_ID_OFFSET) !== VERSION_ID || + buffer.readUInt8(TRACE_ID_FIELD_ID_OFFSET) !== TRACE_ID_FIELD_ID || + buffer.readUInt8(SPAN_ID_FIELD_ID_OFFSET) !== SPAN_ID_FIELD_ID || + buffer.readUInt8(TRACE_OPTION_FIELD_ID_OFFSET) !== TRACE_OPTION_FIELD_ID + ) { return null; } // See serializeSpanContext for byte offsets. - result.traceId = - buffer.slice(TRACE_ID_OFFSET, SPAN_ID_FIELD_ID_OFFSET).toString('hex'); - result.spanId = buffer.slice(SPAN_ID_OFFSET, TRACE_OPTION_FIELD_ID_OFFSET) - .toString('hex'); + result.traceId = buffer + .slice(TRACE_ID_OFFSET, SPAN_ID_FIELD_ID_OFFSET) + .toString('hex'); + result.spanId = buffer + .slice(SPAN_ID_OFFSET, TRACE_OPTION_FIELD_ID_OFFSET) + .toString('hex'); result.options = buffer.readUInt8(TRACE_OPTIONS_OFFSET); return result; } diff --git a/packages/opencensus-propagation-binaryformat/test/test-binary-format.ts b/packages/opencensus-propagation-binaryformat/test/test-binary-format.ts index 7f3cd567c..7a0ee23a6 100644 --- a/packages/opencensus-propagation-binaryformat/test/test-binary-format.ts +++ b/packages/opencensus-propagation-binaryformat/test/test-binary-format.ts @@ -14,56 +14,68 @@ * limitations under the License. */ -import {SpanContext} from '@opencensus/core'; +import { SpanContext } from '@opencensus/core'; import * as assert from 'assert'; -import {deserializeSpanContext, serializeSpanContext} from '../src/binary-format'; +import { + deserializeSpanContext, + serializeSpanContext, +} from '../src/binary-format'; describe('Binary Format Propagator', () => { const commonTraceId = 'd4cda95b652f4a1592b449d5929fda1b'; - const testCases: Array< - {structured: SpanContext | null; binary: string; description: string;}> = - [ - { - structured: - {traceId: commonTraceId, spanId: '75e8ed491aec7eca', options: 1}, - binary: `0000${commonTraceId}01${'75e8ed491aec7eca'}02${'01'}`, - description: 'span context with 64-bit span ID' - }, - { - structured: {traceId: commonTraceId, spanId: '75e8ed491aec7eca'}, - binary: `0000${commonTraceId}01${'75e8ed491aec7eca'}02${'00'}`, - description: 'span context with no options' - }, - { - structured: null, - binary: '00', - description: 'incomplete binary span context (by returning null)' - }, - { - structured: null, - binary: '0'.repeat(58), - description: 'bad binary span context (by returning null)' - } - ]; + const testCases: Array<{ + structured: SpanContext | null; + binary: string; + description: string; + }> = [ + { + structured: { + traceId: commonTraceId, + spanId: '75e8ed491aec7eca', + options: 1, + }, + binary: `0000${commonTraceId}01${'75e8ed491aec7eca'}02${'01'}`, + description: 'span context with 64-bit span ID', + }, + { + structured: { traceId: commonTraceId, spanId: '75e8ed491aec7eca' }, + binary: `0000${commonTraceId}01${'75e8ed491aec7eca'}02${'00'}`, + description: 'span context with no options', + }, + { + structured: null, + binary: '00', + description: 'incomplete binary span context (by returning null)', + }, + { + structured: null, + binary: '0'.repeat(58), + description: 'bad binary span context (by returning null)', + }, + ]; describe('serializeSpanContext', () => { testCases.forEach( - testCase => - testCase.structured && - it(`should serialize ${testCase.description}`, () => { - assert.deepStrictEqual( - serializeSpanContext(testCase.structured!).toString('hex'), - testCase.binary); - })); + testCase => + testCase.structured && + it(`should serialize ${testCase.description}`, () => { + assert.deepStrictEqual( + serializeSpanContext(testCase.structured!).toString('hex'), + testCase.binary + ); + }) + ); }); describe('deserializeSpanContext', () => { - testCases.forEach( - testCase => it(`should deserialize ${testCase.description}`, () => { - assert.deepStrictEqual( - deserializeSpanContext(Buffer.from(testCase.binary, 'hex')), - testCase.structured && - Object.assign({options: 0}, testCase.structured)); - })); + testCases.forEach(testCase => + it(`should deserialize ${testCase.description}`, () => { + assert.deepStrictEqual( + deserializeSpanContext(Buffer.from(testCase.binary, 'hex')), + testCase.structured && + Object.assign({ options: 0 }, testCase.structured) + ); + }) + ); }); }); diff --git a/packages/opencensus-propagation-jaeger/package-lock.json b/packages/opencensus-propagation-jaeger/package-lock.json index 7cd4ae144..b5107399c 100644 --- a/packages/opencensus-propagation-jaeger/package-lock.json +++ b/packages/opencensus-propagation-jaeger/package-lock.json @@ -169,9 +169,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -227,58 +227,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -409,16 +357,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -501,8 +439,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -909,37 +846,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -970,21 +907,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1073,23 +995,43 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } } }, "invert-kv": { @@ -1305,15 +1247,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2150,6 +2087,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2216,9 +2158,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2251,11 +2193,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2289,9 +2231,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2422,17 +2364,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2675,29 +2617,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2862,9 +2798,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-propagation-jaeger/package.json b/packages/opencensus-propagation-jaeger/package.json index e609b690d..151ce8136 100644 --- a/packages/opencensus-propagation-jaeger/package.json +++ b/packages/opencensus-propagation-jaeger/package.json @@ -52,7 +52,7 @@ "@types/node": "^10.12.12", "@types/uuid": "^3.4.3", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "^14.0.0", "rimraf": "^2.6.2", diff --git a/packages/opencensus-propagation-jaeger/src/jaeger-format.ts b/packages/opencensus-propagation-jaeger/src/jaeger-format.ts index 72d119558..a42a4c7e3 100644 --- a/packages/opencensus-propagation-jaeger/src/jaeger-format.ts +++ b/packages/opencensus-propagation-jaeger/src/jaeger-format.ts @@ -14,10 +14,15 @@ * limitations under the License. */ -import {HeaderGetter, HeaderSetter, Propagation, SpanContext} from '@opencensus/core'; +import { + HeaderGetter, + HeaderSetter, + Propagation, + SpanContext, +} from '@opencensus/core'; import * as crypto from 'crypto'; import * as uuid from 'uuid'; -import {isValidSpanId, isValidTraceId} from './validators'; +import { isValidSpanId, isValidTraceId } from './validators'; // TRACER_STATE_HEADER_NAME is the header key used for a span's serialized // context. @@ -42,10 +47,11 @@ export class JaegerFormat implements Propagation { * in the headers, null is returned. * @param getter */ - extract(getter: HeaderGetter): SpanContext|null { + extract(getter: HeaderGetter): SpanContext | null { const debugId = this.parseHeader(getter.getHeader(JAEGER_DEBUG_HEADER)); - const tracerStateHeader = - this.parseHeader(getter.getHeader(TRACER_STATE_HEADER_NAME)); + const tracerStateHeader = this.parseHeader( + getter.getHeader(TRACER_STATE_HEADER_NAME) + ); if (!tracerStateHeader) return null; const tracerStateHeaderParts = tracerStateHeader.split(':'); @@ -54,15 +60,16 @@ export class JaegerFormat implements Propagation { const traceId = tracerStateHeaderParts[0]; const spanId = tracerStateHeaderParts[1]; const jflags = Number( - '0x' + - (isNaN(Number(tracerStateHeaderParts[3])) ? - SAMPLED_VALUE : - Number(tracerStateHeaderParts[3]))); + '0x' + + (isNaN(Number(tracerStateHeaderParts[3])) + ? SAMPLED_VALUE + : Number(tracerStateHeaderParts[3])) + ); const sampled = jflags & SAMPLED_VALUE; - const debug = (jflags & DEBUG_VALUE) || (debugId ? SAMPLED_VALUE : 0); - const options = (sampled || debug) ? SAMPLED_VALUE : 0; + const debug = jflags & DEBUG_VALUE || (debugId ? SAMPLED_VALUE : 0); + const options = sampled || debug ? SAMPLED_VALUE : 0; - return {traceId, spanId, options}; + return { traceId, spanId, options }; } /** @@ -71,21 +78,29 @@ export class JaegerFormat implements Propagation { * @param spanContext */ inject(setter: HeaderSetter, spanContext: SpanContext): void { - if (!spanContext || !isValidTraceId(spanContext.traceId) || - !isValidSpanId(spanContext.spanId)) { + if ( + !spanContext || + !isValidTraceId(spanContext.traceId) || + !isValidSpanId(spanContext.spanId) + ) { return; } let flags = '0'; if (spanContext.options) { - flags = ((spanContext.options & SAMPLED_VALUE) ? SAMPLED_VALUE : 0) - .toString(16); + flags = (spanContext.options & SAMPLED_VALUE + ? SAMPLED_VALUE + : 0 + ).toString(16); } // {parent-span-id} Deprecated, most Jaeger clients ignore on the receiving // side, but still include it on the sending side. const header = [ - spanContext.traceId, spanContext.spanId, /** parent-span-id */ '', flags + spanContext.traceId, + spanContext.spanId, + /** parent-span-id */ '', + flags, ].join(':'); setter.setHeader(TRACER_STATE_HEADER_NAME, header); } @@ -95,14 +110,17 @@ export class JaegerFormat implements Propagation { */ generate(): SpanContext { return { - traceId: uuid.v4().split('-').join(''), + traceId: uuid + .v4() + .split('-') + .join(''), spanId: crypto.randomBytes(8).toString('hex'), - options: SAMPLED_VALUE + options: SAMPLED_VALUE, }; } /** Converts a headers type to a string. */ - private parseHeader(str: string|string[]|undefined): string|undefined { + private parseHeader(str: string | string[] | undefined): string | undefined { if (Array.isArray(str)) { return str[0]; } diff --git a/packages/opencensus-propagation-jaeger/src/validators.ts b/packages/opencensus-propagation-jaeger/src/validators.ts index f26fc180d..3fbcb858f 100644 --- a/packages/opencensus-propagation-jaeger/src/validators.ts +++ b/packages/opencensus-propagation-jaeger/src/validators.ts @@ -57,16 +57,27 @@ const compose = (...fns: ValidationFn[]): ValidationFn => { * Determines if the given traceId is valid based on section 2.2.2.1 of the * Trace Context spec. */ -export const isValidTraceId = compose(isHex, isNotAllZeros, isLength(32)); +export const isValidTraceId = compose( + isHex, + isNotAllZeros, + isLength(32) +); /** * Determines if the given spanId is valid based on section 2.2.2.2 of the Trace * Context spec. */ -export const isValidSpanId = compose(isHex, isNotAllZeros, isLength(16)); +export const isValidSpanId = compose( + isHex, + isNotAllZeros, + isLength(16) +); /** * Determines if the given option is valid based on section 2.2.3 of the Trace * Context spec. */ -export const isValidOption = compose(isHex, isLength(2)); +export const isValidOption = compose( + isHex, + isLength(2) +); diff --git a/packages/opencensus-propagation-jaeger/test/test-jaeger-format.ts b/packages/opencensus-propagation-jaeger/test/test-jaeger-format.ts index 95e89fcd0..a53df66da 100644 --- a/packages/opencensus-propagation-jaeger/test/test-jaeger-format.ts +++ b/packages/opencensus-propagation-jaeger/test/test-jaeger-format.ts @@ -14,17 +14,17 @@ * limitations under the License. */ -import {HeaderGetter, HeaderSetter} from '@opencensus/core'; +import { HeaderGetter, HeaderSetter } from '@opencensus/core'; import * as assert from 'assert'; -import {JaegerFormat, SAMPLED_VALUE, TRACER_STATE_HEADER_NAME} from '../src/'; +import { JaegerFormat, SAMPLED_VALUE, TRACER_STATE_HEADER_NAME } from '../src/'; -function helperGetter(value: string|string[]|undefined) { - const headers: {[key: string]: string|string[]|undefined} = {}; +function helperGetter(value: string | string[] | undefined) { + const headers: { [key: string]: string | string[] | undefined } = {}; headers[TRACER_STATE_HEADER_NAME] = value; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; return getter; } @@ -35,20 +35,21 @@ describe('JaegerPropagation', () => { describe('extract()', () => { it('should extract context of a sampled span from headers', () => { const spanContext = jaegerFormat.generate(); - const getter = helperGetter(`${spanContext.traceId}:${ - spanContext.spanId}::${spanContext.options}`); + const getter = helperGetter( + `${spanContext.traceId}:${spanContext.spanId}::${spanContext.options}` + ); assert.deepStrictEqual(jaegerFormat.extract(getter), spanContext); }); it('should return null when header is undefined', () => { - const headers: {[key: string]: string|string[]|undefined} = {}; + const headers: { [key: string]: string | string[] | undefined } = {}; headers[TRACER_STATE_HEADER_NAME] = undefined; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; assert.deepStrictEqual(jaegerFormat.extract(getter), null); @@ -56,8 +57,9 @@ describe('JaegerPropagation', () => { it('should extract data from an array', () => { const spanContext = jaegerFormat.generate(); - const getter = helperGetter(`${spanContext.traceId}:${ - spanContext.spanId}::${spanContext.options}`); + const getter = helperGetter( + `${spanContext.traceId}:${spanContext.spanId}::${spanContext.options}` + ); assert.deepStrictEqual(jaegerFormat.extract(getter), spanContext); }); }); @@ -65,16 +67,16 @@ describe('JaegerPropagation', () => { describe('inject', () => { it('should inject a context of a sampled span', () => { const spanContext = jaegerFormat.generate(); - const headers: {[key: string]: string|string[]|undefined} = {}; + const headers: { [key: string]: string | string[] | undefined } = {}; const setter: HeaderSetter = { setHeader(name: string, value: string) { headers[name] = value; - } + }, }; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; jaegerFormat.inject(setter, spanContext); @@ -87,16 +89,16 @@ describe('JaegerPropagation', () => { spanId: '', options: SAMPLED_VALUE, }; - const headers: {[key: string]: string|string[]|undefined} = {}; + const headers: { [key: string]: string | string[] | undefined } = {}; const setter: HeaderSetter = { setHeader(name: string, value: string) { headers[name] = value; - } + }, }; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; jaegerFormat.inject(setter, emptySpanContext); @@ -104,23 +106,23 @@ describe('JaegerPropagation', () => { }); }); - // Same test as propagation-stackdriver. describe('generate', () => { const TIMES = 20; // Generate some span contexts. - const GENERATED = - Array.from({length: TIMES}).fill(0).map(_ => jaegerFormat.generate()); + const GENERATED = Array.from({ length: TIMES }) + .fill(0) + .map(_ => jaegerFormat.generate()); it('should generate unique traceIds', () => { const traceIds = GENERATED.map(c => c.traceId); - assert.strictEqual((new Set(traceIds)).size, TIMES); + assert.strictEqual(new Set(traceIds).size, TIMES); }); it('should generate unique spanIds', () => { const spanIds = GENERATED.map(c => c.spanId); - assert.strictEqual((new Set(spanIds)).size, TIMES); + assert.strictEqual(new Set(spanIds).size, TIMES); }); }); }); diff --git a/packages/opencensus-propagation-stackdriver/package-lock.json b/packages/opencensus-propagation-stackdriver/package-lock.json index bfdeb1304..da79f760c 100644 --- a/packages/opencensus-propagation-stackdriver/package-lock.json +++ b/packages/opencensus-propagation-stackdriver/package-lock.json @@ -181,9 +181,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -234,58 +234,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -406,16 +354,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -496,9 +434,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -861,9 +799,9 @@ "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=" }, "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -915,21 +853,28 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" + }, + "dependencies": { + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" + } } }, "handlebars": { @@ -958,21 +903,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1066,23 +996,35 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + } } }, "invert-kv": { @@ -1321,15 +1263,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.1.tgz", - "integrity": "sha512-um46hB9wNOKlwkHgiuyEVAybXBjwFUV0Z/RaHJblRd9DXltue9FTYvzCr9ErQrK9Adz5MU4gHWVaNUfdmrC8qA==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -1398,9 +1335,9 @@ } }, "lodash": { - "version": "4.17.10", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.10.tgz", - "integrity": "sha512-UejweD1pDoXu+AD825lWwp4ZGtSwgnpZxb3JDViD7StjQz+Nb/6l093lx4OQ0foGWNRoc19mWy7BzL+UAK2iVg==" + "version": "4.17.11", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", + "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" }, "lodash.flattendeep": { "version": "4.4.0", @@ -2184,6 +2121,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2243,9 +2185,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2278,9 +2220,9 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.9.0.tgz", - "integrity": "sha512-TZNye00tI67lwYvzxCxHGjwTNlUV70io54/Ed4j6PscB8xVfuBJpRenI/o6dVk0cY0PYTY27AgCoGGxRnYuItQ==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { "path-parse": "^1.0.6" } @@ -2331,9 +2273,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2471,17 +2413,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2692,22 +2634,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.12.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.12.0.tgz", - "integrity": "sha512-CKEcH1MHUBhoV43SA/Jmy1l24HJJgI0eyLbBNSRyFlsQvb9v6Zdq+Nz2vEOH00nC5SUx4SneJ59PZUS/ARcokQ==", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2886,9 +2829,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-propagation-stackdriver/package.json b/packages/opencensus-propagation-stackdriver/package.json index fa98e3400..b87d92794 100644 --- a/packages/opencensus-propagation-stackdriver/package.json +++ b/packages/opencensus-propagation-stackdriver/package.json @@ -30,7 +30,7 @@ "@types/node": "^10.12.12", "@types/uuid": "^3.4.3", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "^14.0.0", "ts-mocha": "^6.0.0", diff --git a/packages/opencensus-propagation-stackdriver/src/index.ts b/packages/opencensus-propagation-stackdriver/src/index.ts index 6a2ec50c7..f5b929261 100644 --- a/packages/opencensus-propagation-stackdriver/src/index.ts +++ b/packages/opencensus-propagation-stackdriver/src/index.ts @@ -31,7 +31,7 @@ export interface SpanContext { * An transport and environment neutral API for getting request headers. */ export interface HeaderGetter { - getHeader(name: string): string|string[]|undefined; + getHeader(name: string): string | string[] | undefined; } /** @@ -41,9 +41,8 @@ export interface HeaderSetter { setHeader(name: string, value: string): void; } - export interface Propagation { - extract(getter: HeaderGetter): SpanContext|null; + extract(getter: HeaderGetter): SpanContext | null; inject(setter: HeaderSetter, spanContext: SpanContext): void; generate(): SpanContext; } @@ -56,10 +55,13 @@ export interface Propagation { export const v1: Propagation = { extract: v1API.extract, inject: v1API.inject, - generate: v1API.generate + generate: v1API.generate, }; // Also export the v1 API as the default API. +// tslint:disable-next-line:deprecation export const extract = v1.extract; +// tslint:disable-next-line:deprecation export const inject = v1.inject; +// tslint:disable-next-line:deprecation export const generate = v1.generate; diff --git a/packages/opencensus-propagation-stackdriver/src/stackdriver-format.ts b/packages/opencensus-propagation-stackdriver/src/stackdriver-format.ts index b8994e112..aee305869 100644 --- a/packages/opencensus-propagation-stackdriver/src/stackdriver-format.ts +++ b/packages/opencensus-propagation-stackdriver/src/stackdriver-format.ts @@ -31,9 +31,9 @@ */ import * as crypto from 'crypto'; -import {decToHex, hexToDec} from 'hex2dec'; +import { decToHex, hexToDec } from 'hex2dec'; import * as uuid from 'uuid'; -import {HeaderGetter, HeaderSetter, Propagation, SpanContext} from './index'; +import { HeaderGetter, HeaderSetter, Propagation, SpanContext } from './index'; /** Header that carries span context across Google infrastructure. */ export const TRACE_CONTEXT_HEADER_NAME = 'x-cloud-trace-context'; @@ -47,15 +47,20 @@ export class StackdriverFormat implements Propagation { * in the headers, null is returned. * @param getter */ - extract(getter: HeaderGetter): SpanContext|null { + extract(getter: HeaderGetter): SpanContext | null { const traceContextHeader = getter.getHeader(TRACE_CONTEXT_HEADER_NAME); if (typeof traceContextHeader !== 'string') { return null; } - const matches = - traceContextHeader.match(/^([0-9a-fA-F]+)(?:\/([0-9]+))(?:;o=(.*))?/); - if (!matches || matches.length !== 4 || matches[0] !== traceContextHeader || - (matches[2] && isNaN(Number(matches[2])))) { + const matches = traceContextHeader.match( + /^([0-9a-fA-F]+)(?:\/([0-9]+))(?:;o=(.*))?/ + ); + if ( + !matches || + matches.length !== 4 || + matches[0] !== traceContextHeader || + (matches[2] && isNaN(Number(matches[2]))) + ) { return null; } return { @@ -63,7 +68,7 @@ export class StackdriverFormat implements Propagation { // strip 0x prefix from hex output from decToHex, and and pad so it's // always a length-16 hex string spanId: `0000000000000000${decToHex(matches[2]).slice(2)}`.slice(-16), - options: isNaN(Number(matches[3])) ? TRACE_TRUE : Number(matches[3]) + options: isNaN(Number(matches[3])) ? TRACE_TRUE : Number(matches[3]), }; } @@ -86,7 +91,7 @@ export class StackdriverFormat implements Propagation { return { traceId: uuid.v4().replace(/-/g, ''), spanId: spanRandomBuffer().toString('hex'), - options: TRACE_TRUE + options: TRACE_TRUE, }; } } @@ -98,6 +103,6 @@ export class StackdriverFormat implements Propagation { const spanIdBuffer = Buffer.alloc(SPAN_ID_RANDOM_BYTES); const randomFillSync = crypto.randomFillSync; const randomBytes = crypto.randomBytes; -const spanRandomBuffer = randomFillSync ? - () => randomFillSync(spanIdBuffer) : - () => randomBytes(SPAN_ID_RANDOM_BYTES); +const spanRandomBuffer = randomFillSync + ? () => randomFillSync(spanIdBuffer) + : () => randomBytes(SPAN_ID_RANDOM_BYTES); diff --git a/packages/opencensus-propagation-stackdriver/src/v1.ts b/packages/opencensus-propagation-stackdriver/src/v1.ts index 7fc8e1d93..dc898749a 100644 --- a/packages/opencensus-propagation-stackdriver/src/v1.ts +++ b/packages/opencensus-propagation-stackdriver/src/v1.ts @@ -21,20 +21,25 @@ */ import * as crypto from 'crypto'; -import {decToHex, hexToDec} from 'hex2dec'; +import { decToHex, hexToDec } from 'hex2dec'; import * as uuid from 'uuid'; -import {HeaderGetter, HeaderSetter, SpanContext} from './index'; +import { HeaderGetter, HeaderSetter, SpanContext } from './index'; const TRACE_CONTEXT_HEADER_NAME = 'x-cloud-trace-context'; -export function parseContextFromHeader(str: string|string[]| - undefined): SpanContext|null { +export function parseContextFromHeader( + str: string | string[] | undefined +): SpanContext | null { if (typeof str !== 'string') { return null; } const matches = str.match(/^([0-9a-fA-F]+)(?:\/([0-9]+))(?:;o=(.*))?/); - if (!matches || matches.length !== 4 || matches[0] !== str || - (matches[2] && isNaN(Number(matches[2])))) { + if ( + !matches || + matches.length !== 4 || + matches[0] !== str || + (matches[2] && isNaN(Number(matches[2]))) + ) { return null; } return { @@ -42,7 +47,7 @@ export function parseContextFromHeader(str: string|string[]| // strip 0x prefix from hex output from decToHex, and and pad so it's always // a length-16 hex string spanId: `0000000000000000${decToHex(matches[2]).slice(2)}`.slice(-16), - options: isNaN(Number(matches[3])) ? undefined : Number(matches[3]) + options: isNaN(Number(matches[3])) ? undefined : Number(matches[3]), }; } @@ -60,7 +65,9 @@ export function extract(getter: HeaderGetter) { export function inject(setter: HeaderSetter, spanContext: SpanContext) { setter.setHeader( - TRACE_CONTEXT_HEADER_NAME, serializeSpanContext(spanContext)); + TRACE_CONTEXT_HEADER_NAME, + serializeSpanContext(spanContext) + ); } const SPAN_ID_RANDOM_BYTES = 8; @@ -72,13 +79,16 @@ const SPAN_ID_RANDOM_BYTES = 8; const spanIdBuffer = Buffer.alloc(SPAN_ID_RANDOM_BYTES); const randomFillSync = crypto.randomFillSync; const randomBytes = crypto.randomBytes; -const spanRandomBuffer = randomFillSync ? - () => randomFillSync(spanIdBuffer) : - () => randomBytes(SPAN_ID_RANDOM_BYTES); +const spanRandomBuffer = randomFillSync + ? () => randomFillSync(spanIdBuffer) + : () => randomBytes(SPAN_ID_RANDOM_BYTES); export function generate(): SpanContext { return { - traceId: uuid.v4().split('-').join(''), - spanId: spanRandomBuffer().toString('hex') + traceId: uuid + .v4() + .split('-') + .join(''), + spanId: spanRandomBuffer().toString('hex'), }; } diff --git a/packages/opencensus-propagation-stackdriver/test/test-stackdriver-format.ts b/packages/opencensus-propagation-stackdriver/test/test-stackdriver-format.ts index 22090eaee..d82cbcb01 100644 --- a/packages/opencensus-propagation-stackdriver/test/test-stackdriver-format.ts +++ b/packages/opencensus-propagation-stackdriver/test/test-stackdriver-format.ts @@ -14,19 +14,19 @@ * limitations under the License. */ -import {HeaderGetter, HeaderSetter} from '@opencensus/core'; +import { HeaderGetter, HeaderSetter } from '@opencensus/core'; import * as assert from 'assert'; -import {StackdriverFormat, TRACE_CONTEXT_HEADER_NAME} from '../src'; +import { StackdriverFormat, TRACE_CONTEXT_HEADER_NAME } from '../src'; const stackdriverFormat = new StackdriverFormat(); -function helperGetter(value: string|string[]|undefined) { - const headers: {[key: string]: string|string[]|undefined} = {}; +function helperGetter(value: string | string[] | undefined) { + const headers: { [key: string]: string | string[] | undefined } = {}; headers[TRACE_CONTEXT_HEADER_NAME] = value; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; return getter; } @@ -35,31 +35,43 @@ describe('StackdriverPropagation', () => { describe('extract()', () => { it('should extract context of a sampled span from headers', () => { const getter = helperGetter('123456/667;o=1'); - assert.deepStrictEqual( - stackdriverFormat.extract(getter), - {traceId: '123456', spanId: '000000000000029b', options: 1}); + assert.deepStrictEqual(stackdriverFormat.extract(getter), { + traceId: '123456', + spanId: '000000000000029b', + options: 1, + }); }); - it('should extract context of a span from headers when TRACE_TRUE set to 0', - () => { - const getter = - helperGetter('123456/123456123456123456123456123456123456;o=0'); - assert.deepStrictEqual( - stackdriverFormat.extract(getter), - {traceId: '123456', spanId: 'a89bb45f10f2f240', options: 0}); - }); + it('should extract context of a span from headers when TRACE_TRUE set to 0', () => { + const getter = helperGetter( + '123456/123456123456123456123456123456123456;o=0' + ); + assert.deepStrictEqual(stackdriverFormat.extract(getter), { + traceId: '123456', + spanId: 'a89bb45f10f2f240', + options: 0, + }); + }); - it('should extract context of a span from headers when option is undefined', - () => { - const getter = helperGetter('cafef00d/123'); - assert.deepStrictEqual( - stackdriverFormat.extract(getter), - {traceId: 'cafef00d', spanId: '000000000000007b', options: 1}); - }); + it('should extract context of a span from headers when option is undefined', () => { + const getter = helperGetter('cafef00d/123'); + assert.deepStrictEqual(stackdriverFormat.extract(getter), { + traceId: 'cafef00d', + spanId: '000000000000007b', + options: 1, + }); + }); const inputs = [ - '', undefined, '123456', '123456;o=1', 'o=1;123456', '123;456;o=1', - '123/o=1;456', '123/abc/o=1', 'cafefood/667;o=1' + '', + undefined, + '123456', + '123456;o=1', + 'o=1;123456', + '123;456;o=1', + '123/o=1;456', + '123/abc/o=1', + 'cafefood/667;o=1', ]; inputs.forEach(s => { it(`should reject ${s}`, () => { @@ -73,16 +85,16 @@ describe('StackdriverPropagation', () => { describe('inject', () => { it('should inject a context of a sampled span', () => { const spanContext = stackdriverFormat.generate(); - const headers: {[key: string]: string|string[]|undefined} = {}; + const headers: { [key: string]: string | string[] | undefined } = {}; const setter: HeaderSetter = { setHeader(name: string, value: string) { headers[name] = value; - } + }, }; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; stackdriverFormat.inject(setter, spanContext); @@ -90,17 +102,17 @@ describe('StackdriverPropagation', () => { }); it('should not inject empty spancontext', () => { - const emptySpanContext = {traceId: '', spanId: ''}; - const headers: {[key: string]: string|string[]|undefined} = {}; + const emptySpanContext = { traceId: '', spanId: '' }; + const headers: { [key: string]: string | string[] | undefined } = {}; const setter: HeaderSetter = { setHeader(name: string, value: string) { headers[name] = value; - } + }, }; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; stackdriverFormat.inject(setter, emptySpanContext); @@ -112,18 +124,18 @@ describe('StackdriverPropagation', () => { const TIMES = 20; // Generate some span contexts. - const GENERATED = Array.from({length: TIMES}) - .fill(0) - .map(_ => stackdriverFormat.generate()); + const GENERATED = Array.from({ length: TIMES }) + .fill(0) + .map(_ => stackdriverFormat.generate()); it('should generate unique traceIds', () => { const traceIds = GENERATED.map(c => c.traceId); - assert.strictEqual((new Set(traceIds)).size, TIMES); + assert.strictEqual(new Set(traceIds).size, TIMES); }); it('should generate unique spanIds', () => { const spanIds = GENERATED.map(c => c.spanId); - assert.strictEqual((new Set(spanIds)).size, TIMES); + assert.strictEqual(new Set(spanIds).size, TIMES); }); }); }); diff --git a/packages/opencensus-propagation-stackdriver/test/test-v1.ts b/packages/opencensus-propagation-stackdriver/test/test-v1.ts index 0e4f8a157..f54dce398 100644 --- a/packages/opencensus-propagation-stackdriver/test/test-v1.ts +++ b/packages/opencensus-propagation-stackdriver/test/test-v1.ts @@ -15,11 +15,17 @@ */ import * as assert from 'assert'; -import {inspect} from 'util'; -import {SpanContext} from '../src/index'; -import {extract, generate, inject, parseContextFromHeader, serializeSpanContext} from '../src/v1'; +import { inspect } from 'util'; +import { SpanContext } from '../src/index'; +import { + extract, + generate, + inject, + parseContextFromHeader, + serializeSpanContext, +} from '../src/v1'; -const notNull = (x: T|null|undefined): T => { +const notNull = (x: T | null | undefined): T => { assert.notStrictEqual(x, null); assert.notStrictEqual(x, undefined); return x as T; @@ -35,15 +41,17 @@ describe('parseContextFromHeader', () => { assert.strictEqual(result.options, 1); }); - it('should return expected values:' + - '123456/123456123456123456123456123456123456;o=1', - () => { - const header = '123456/123456123456123456123456123456123456;o=1'; - const result = notNull(parseContextFromHeader(header)); - assert.strictEqual(result.traceId, '123456'); - assert.strictEqual(result.spanId, 'a89bb45f10f2f240'); - assert.strictEqual(result.options, 1); - }); + it( + 'should return expected values:' + + '123456/123456123456123456123456123456123456;o=1', + () => { + const header = '123456/123456123456123456123456123456123456;o=1'; + const result = notNull(parseContextFromHeader(header)); + assert.strictEqual(result.traceId, '123456'); + assert.strictEqual(result.spanId, 'a89bb45f10f2f240'); + assert.strictEqual(result.options, 1); + } + ); it('should return expected values: 123456/667', () => { const header = '123456/667'; @@ -56,8 +64,16 @@ describe('parseContextFromHeader', () => { describe('invalid inputs', () => { const inputs = [ - '', null, undefined, '123456', '123456;o=1', 'o=1;123456', '123;456;o=1', - '123/o=1;456', '123/abc/o=1', 'cafefood/667;o=1' + '', + null, + undefined, + '123456', + '123456;o=1', + 'o=1;123456', + '123;456;o=1', + '123/o=1;456', + '123/abc/o=1', + 'cafefood/667;o=1', ]; inputs.forEach(s => { it(`should reject ${s}`, () => { @@ -76,17 +92,17 @@ describe('serializeSpanContext', () => { } const testData: TestData[] = [ { - input: {traceId: '123456', spanId: '29b', options: 1}, - output: '123456/667;o=1' + input: { traceId: '123456', spanId: '29b', options: 1 }, + output: '123456/667;o=1', }, { - input: {traceId: '123456', spanId: '29b', options: undefined}, - output: '123456/667' + input: { traceId: '123456', spanId: '29b', options: undefined }, + output: '123456/667', }, - {input: {traceId: '123456', spanId: '29b'}, output: '123456/667'} + { input: { traceId: '123456', spanId: '29b' }, output: '123456/667' }, ]; - testData.forEach(({input, output}) => { + testData.forEach(({ input, output }) => { it(`returns well-formatted trace context for ${inspect(input)}`, () => { const header = serializeSpanContext(input); assert.deepStrictEqual(header, output); @@ -100,20 +116,20 @@ describe('extract', () => { const getter = { getHeader(name: string) { return HEADER; - } + }, }; assert.deepStrictEqual(extract(getter), parseContextFromHeader(HEADER)); }); }); describe('inject', () => { - it('should call setter.setHeader with serialized header', (done) => { + it('should call setter.setHeader with serialized header', done => { const spanContext = generate(); const setter = { setHeader(name: string, value: string) { assert.deepStrictEqual(value, serializeSpanContext(spanContext)); done(); - } + }, }; inject(setter, spanContext); }); @@ -123,7 +139,9 @@ describe('generate', () => { const TIMES = 20; // Generate some span contexts. - const GENERATED = Array.from({length: TIMES}).fill(0).map(_ => generate()); + const GENERATED = Array.from({ length: TIMES }) + .fill(0) + .map(_ => generate()); it('should generate a valid span context', () => { const ok = GENERATED.every(c => { @@ -136,11 +154,11 @@ describe('generate', () => { it('should generate unique traceIds', () => { const traceIds = GENERATED.map(c => c.traceId); - assert.strictEqual((new Set(traceIds)).size, TIMES); + assert.strictEqual(new Set(traceIds).size, TIMES); }); it('should generate unique spanIds', () => { const spanIds = GENERATED.map(c => c.spanId); - assert.strictEqual((new Set(spanIds)).size, TIMES); + assert.strictEqual(new Set(spanIds).size, TIMES); }); }); diff --git a/packages/opencensus-propagation-tracecontext/package-lock.json b/packages/opencensus-propagation-tracecontext/package-lock.json index 76e63e61d..09688f6ee 100644 --- a/packages/opencensus-propagation-tracecontext/package-lock.json +++ b/packages/opencensus-propagation-tracecontext/package-lock.json @@ -161,9 +161,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -219,58 +219,6 @@ "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" }, - "async": { - "version": "1.5.2", - "resolved": "http://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -401,16 +349,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -493,8 +431,7 @@ "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", - "optional": true + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -901,37 +838,37 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" }, "dependencies": { "chalk": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", - "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" }, "supports-color": { "version": "5.5.0", @@ -962,21 +899,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1065,23 +987,43 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } } }, "invert-kv": { @@ -1297,15 +1239,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2137,6 +2074,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -2203,9 +2145,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2238,11 +2180,11 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", - "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { - "path-parse": "^1.0.5" + "path-parse": "^1.0.6" } }, "resolve-from": { @@ -2276,9 +2218,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2409,17 +2351,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2655,29 +2597,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.11.0.tgz", - "integrity": "sha1-mPMMAurjzecAYgHkwzywi0hYHu0=", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" - }, - "dependencies": { - "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" - } + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2842,9 +2778,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-propagation-tracecontext/package.json b/packages/opencensus-propagation-tracecontext/package.json index 7b248ca31..bbaf05fc5 100644 --- a/packages/opencensus-propagation-tracecontext/package.json +++ b/packages/opencensus-propagation-tracecontext/package.json @@ -52,7 +52,7 @@ "@types/mocha": "^5.2.5", "@types/node": "^10.12.12", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nyc": "^14.0.0", "rimraf": "^2.6.2", diff --git a/packages/opencensus-propagation-tracecontext/src/tracecontext-format.ts b/packages/opencensus-propagation-tracecontext/src/tracecontext-format.ts index f6f393fd2..2950e8f61 100644 --- a/packages/opencensus-propagation-tracecontext/src/tracecontext-format.ts +++ b/packages/opencensus-propagation-tracecontext/src/tracecontext-format.ts @@ -14,9 +14,14 @@ * limitations under the License. */ -import {HeaderGetter, HeaderSetter, Propagation, SpanContext} from '@opencensus/core'; +import { + HeaderGetter, + HeaderSetter, + Propagation, + SpanContext, +} from '@opencensus/core'; import * as crypto from 'crypto'; -import {isValidSpanId, isValidTraceId, isValidVersion} from './validators'; +import { isValidSpanId, isValidTraceId, isValidVersion } from './validators'; /** The traceparent header key. */ export const TRACE_PARENT = 'traceparent'; @@ -31,7 +36,7 @@ const TRACE_PARENT_REGEX = /^[\da-f]{2}-[\da-f]{32}-[\da-f]{16}-[\da-f]{2}$/; * Parses a traceparent header value into a SpanContext object, or null if the * traceparent value is invalid. */ -function traceParentToSpanContext(traceParent: string): SpanContext|null { +function traceParentToSpanContext(traceParent: string): SpanContext | null { const match = traceParent.match(TRACE_PARENT_REGEX); if (!match) return null; const parts = traceParent.split('-'); @@ -39,15 +44,18 @@ function traceParentToSpanContext(traceParent: string): SpanContext|null { // tslint:disable-next-line:ban Needed to parse hexadecimal. const options = parseInt(option, 16); - if (!isValidVersion(version) || !isValidTraceId(traceId) || - !isValidSpanId(spanId)) { + if ( + !isValidVersion(version) || + !isValidTraceId(traceId) || + !isValidSpanId(spanId) + ) { return null; } - return {traceId, spanId, options}; + return { traceId, spanId, options }; } /** Converts a headers type to a string. */ -function parseHeader(str: string|string[]|undefined): string|undefined { +function parseHeader(str: string | string[] | undefined): string | undefined { return Array.isArray(str) ? str[0] : str; } @@ -69,7 +77,7 @@ export class TraceContextFormat implements Propagation { * returned. * @param getter */ - extract(getter: HeaderGetter): SpanContext|null { + extract(getter: HeaderGetter): SpanContext | null { const traceParentHeader = getter.getHeader(TRACE_PARENT); if (!traceParentHeader) return null; const traceParent = parseHeader(traceParentHeader); @@ -82,9 +90,9 @@ export class TraceContextFormat implements Propagation { if (traceStateHeader) { // If more than one `tracestate` header is found, we merge them into a // single header. - spanContext.traceState = Array.isArray(traceStateHeader) ? - traceStateHeader.join(',') : - traceStateHeader; + spanContext.traceState = Array.isArray(traceStateHeader) + ? traceStateHeader.join(',') + : traceStateHeader; } return spanContext; } @@ -97,8 +105,9 @@ export class TraceContextFormat implements Propagation { inject(setter: HeaderSetter, spanContext: SpanContext): void { // Construct traceparent from parts. Make sure the traceId and spanId // contain the proper number of characters. - const traceParent = `00-${spanContext.traceId}-${spanContext.spanId}-0${ - (spanContext.options || DEFAULT_OPTIONS).toString(16)}`; + const traceParent = `00-${spanContext.traceId}-${spanContext.spanId}-0${( + spanContext.options || DEFAULT_OPTIONS + ).toString(16)}`; setter.setHeader(TRACE_PARENT, traceParent); if (spanContext.traceState) { @@ -116,7 +125,7 @@ export class TraceContextFormat implements Propagation { return { traceId: buff.slice(0, 32), spanId: buff.slice(32, 48), - options: DEFAULT_OPTIONS + options: DEFAULT_OPTIONS, }; } } diff --git a/packages/opencensus-propagation-tracecontext/src/validators.ts b/packages/opencensus-propagation-tracecontext/src/validators.ts index fd09712cd..6903d6806 100644 --- a/packages/opencensus-propagation-tracecontext/src/validators.ts +++ b/packages/opencensus-propagation-tracecontext/src/validators.ts @@ -59,22 +59,36 @@ const compose = (...fns: ValidationFn[]): ValidationFn => { * the version. If the version is parsable as hex and of length 2, we will * attempt to parse the header. This is per section 2.2.5 of the spec. */ -export const isValidVersion = compose(isHex, isLength(2)); +export const isValidVersion = compose( + isHex, + isLength(2) +); /** * Determines if the given traceId is valid based on section 2.2.2.1 of the * Trace Context spec. */ -export const isValidTraceId = compose(isHex, isNotAllZeros, isLength(32)); +export const isValidTraceId = compose( + isHex, + isNotAllZeros, + isLength(32) +); /** * Determines if the given spanId is valid based on section 2.2.2.2 of the Trace * Context spec. */ -export const isValidSpanId = compose(isHex, isNotAllZeros, isLength(16)); +export const isValidSpanId = compose( + isHex, + isNotAllZeros, + isLength(16) +); /** * Determines if the given option is valid based on section 2.2.3 of the Trace * Context spec. */ -export const isValidOption = compose(isHex, isLength(2)); +export const isValidOption = compose( + isHex, + isLength(2) +); diff --git a/packages/opencensus-propagation-tracecontext/test/test-tracecontext-format.ts b/packages/opencensus-propagation-tracecontext/test/test-tracecontext-format.ts index 17ef01348..30a7c6d93 100644 --- a/packages/opencensus-propagation-tracecontext/test/test-tracecontext-format.ts +++ b/packages/opencensus-propagation-tracecontext/test/test-tracecontext-format.ts @@ -14,22 +14,29 @@ * limitations under the License. */ -import {HeaderGetter, HeaderSetter, SpanContext} from '@opencensus/core'; +import { HeaderGetter, HeaderSetter, SpanContext } from '@opencensus/core'; import * as assert from 'assert'; -import {DEFAULT_OPTIONS, TRACE_PARENT, TRACE_STATE, TraceContextFormat} from '../src/'; +import { + DEFAULT_OPTIONS, + TRACE_PARENT, + TRACE_STATE, + TraceContextFormat, +} from '../src/'; const traceContextFormat = new TraceContextFormat(); -type Headers = Record; +type Headers = Record; describe('TraceContextPropagation', () => { // Generates the appropriate `traceparent` header for the given SpanContext - const traceParentHeaderFromSpanContext = - (spanContext: SpanContext): string => { - const {traceId, spanId} = spanContext; - return `00-${traceId}-${spanId}-${ - Buffer.from([spanContext.options]).toString('hex')}`; - }; + const traceParentHeaderFromSpanContext = ( + spanContext: SpanContext + ): string => { + const { traceId, spanId } = spanContext; + return `00-${traceId}-${spanId}-${Buffer.from([ + spanContext.options, + ]).toString('hex')}`; + }; /** Should get the singleton trancing instance. */ describe('extract()', () => { @@ -45,7 +52,7 @@ describe('TraceContextPropagation', () => { const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; // Extract a span context from the constructed headers and verify that @@ -66,7 +73,7 @@ describe('TraceContextPropagation', () => { const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; // Extract a span context from the constructed headers and verify that @@ -87,33 +94,33 @@ describe('TraceContextPropagation', () => { const testCases: Record = { invalidParts_tooShort: '00-ffffffffffffffffffffffffffffffff', invalidParts_tooLong: - '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-00-01', + '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-00-01', invalidVersion_notHex: - '0x-ffffffffffffffffffffffffffffffff-ffffffffffffffff-00', + '0x-ffffffffffffffffffffffffffffffff-ffffffffffffffff-00', invalidVersion_tooShort: - '0-ffffffffffffffffffffffffffffffff-ffffffffffffffff-00', + '0-ffffffffffffffffffffffffffffffff-ffffffffffffffff-00', invalidVersion_tooLong: - '000-ffffffffffffffffffffffffffffffff-ffffffffffffffff-00', + '000-ffffffffffffffffffffffffffffffff-ffffffffffffffff-00', invalidTraceId_empty: '00--ffffffffffffffff-01', invalidTraceId_notHex: - '00-fffffffffffffffffffffffffffffffx-ffffffffffffffff-01', + '00-fffffffffffffffffffffffffffffffx-ffffffffffffffff-01', invalidTraceId_allZeros: - '00-00000000000000000000000000000000-ffffffffffffffff-01', + '00-00000000000000000000000000000000-ffffffffffffffff-01', invalidTraceId_tooShort: '00-ffffffff-ffffffffffffffff-01', invalidTraceId_tooLong: - '00-ffffffffffffffffffffffffffffffff00-ffffffffffffffff-01', + '00-ffffffffffffffffffffffffffffffff00-ffffffffffffffff-01', invalidSpanId_empty: '00-ffffffffffffffffffffffffffffffff--01', invalidSpanId_notHex: - '00-ffffffffffffffffffffffffffffffff-fffffffffffffffx-01', + '00-ffffffffffffffffffffffffffffffff-fffffffffffffffx-01', invalidSpanId_allZeros: - '00-ffffffffffffffffffffffffffffffff-0000000000000000-01', + '00-ffffffffffffffffffffffffffffffff-0000000000000000-01', invalidSpanId_tooShort: - '00-ffffffffffffffffffffffffffffffff-ffffffff-01', + '00-ffffffffffffffffffffffffffffffff-ffffffff-01', invalidSpanId_tooLong: - '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff0000-01', + '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff0000-01', }; Object.getOwnPropertyNames(testCases).forEach(testCase => { @@ -124,7 +131,7 @@ describe('TraceContextPropagation', () => { const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; const extractedSpanContext = traceContextFormat.extract(getter); @@ -135,13 +142,13 @@ describe('TraceContextPropagation', () => { it('should reset options if they are invalid', () => { const testCases: Record = { invalidOptions_empty: - '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-', + '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-', invalidOptions_notHex: - '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-0x', + '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-0x', invalidOptions_tooShort: - '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-0', + '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-0', invalidOptions_tooLong: - '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-0f0', + '00-ffffffffffffffffffffffffffffffff-ffffffffffffffff-0f0', }; Object.getOwnPropertyNames(testCases).forEach(testCase => { @@ -152,13 +159,16 @@ describe('TraceContextPropagation', () => { const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; const extractedSpanContext = traceContextFormat.extract(getter); if (extractedSpanContext !== null) { assert.strictEqual( - extractedSpanContext.options, DEFAULT_OPTIONS, testCase); + extractedSpanContext.options, + DEFAULT_OPTIONS, + testCase + ); } }); }); @@ -169,12 +179,12 @@ describe('TraceContextPropagation', () => { spanContext.traceState = traceStateHeaders.join(','); const headers: Headers = { [TRACE_PARENT]: traceParentHeaderFromSpanContext(spanContext), - [TRACE_STATE]: traceStateHeaders + [TRACE_STATE]: traceStateHeaders, }; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; const extractedSpanContext = traceContextFormat.extract(getter); @@ -185,7 +195,7 @@ describe('TraceContextPropagation', () => { const getter: HeaderGetter = { getHeader(name: string) { return undefined; - } + }, }; const extractedSpanContext = traceContextFormat.extract(getter); @@ -200,12 +210,12 @@ describe('TraceContextPropagation', () => { const setter: HeaderSetter = { setHeader(name: string, value: string) { headers[name] = value; - } + }, }; const getter: HeaderGetter = { getHeader(name: string) { return headers[name]; - } + }, }; traceContextFormat.inject(setter, spanContext); @@ -217,13 +227,13 @@ describe('TraceContextPropagation', () => { traceId: '', spanId: '', options: DEFAULT_OPTIONS, - traceState: 'foo=bar' + traceState: 'foo=bar', }; const headers: Headers = {}; const setter: HeaderSetter = { setHeader(name: string, value: string) { headers[name] = value; - } + }, }; traceContextFormat.inject(setter, spanContext); @@ -235,18 +245,18 @@ describe('TraceContextPropagation', () => { const TIMES = 20; // Generate some span contexts. - const GENERATED = Array.from({length: TIMES}) - .fill(0) - .map(_ => traceContextFormat.generate()); + const GENERATED = Array.from({ length: TIMES }) + .fill(0) + .map(_ => traceContextFormat.generate()); it('should generate unique traceIds', () => { const traceIds = GENERATED.map(c => c.traceId); - assert.strictEqual((new Set(traceIds)).size, TIMES); + assert.strictEqual(new Set(traceIds).size, TIMES); }); it('should generate unique spanIds', () => { const spanIds = GENERATED.map(c => c.spanId); - assert.strictEqual((new Set(spanIds)).size, TIMES); + assert.strictEqual(new Set(spanIds).size, TIMES); }); }); }); diff --git a/packages/opencensus-resource-util/package-lock.json b/packages/opencensus-resource-util/package-lock.json index a60099b52..aec36b6eb 100644 --- a/packages/opencensus-resource-util/package-lock.json +++ b/packages/opencensus-resource-util/package-lock.json @@ -175,9 +175,9 @@ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==" }, "ansi-escapes": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", - "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" }, "ansi-regex": { "version": "3.0.0", @@ -233,58 +233,6 @@ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==" }, - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "^1.1.3", - "esutils": "^2.0.2", - "js-tokens": "^3.0.2" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - } - } - }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -423,16 +371,6 @@ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==" }, - "clang-format": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.2.3.tgz", - "integrity": "sha512-x90Hac4ERacGDcZSvHKK58Ga0STuMD+Doi5g0iG2zf7wlJef5Huvhs/3BvMRFxwRYyYSdl6mpQNrtfMxE8MQzw==", - "requires": { - "async": "^1.5.2", - "glob": "^7.0.0", - "resolve": "^1.1.6" - } - }, "cli-boxes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", @@ -513,9 +451,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "commander": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", - "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" }, "commondir": { "version": "1.0.1", @@ -977,21 +915,28 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==" }, "gts": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/gts/-/gts-0.9.0.tgz", - "integrity": "sha512-Id2Vmg0xNU1FODc0AwmaFA1h0+h6V9/zBqu4NfT8FucVOVEP7pyJ16btyHfSH/UdzTCXjV1fq+fNBEgx/50EaA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gts/-/gts-1.0.0.tgz", + "integrity": "sha512-/CRhAi0/xkH1l9UveIlTxLLBcTzUNa2PHyBrllLuYtVXZc8NPh/hZmxO6JwxF6OD1GxJyAwyMt5+RjnBncI5jw==", "requires": { "chalk": "^2.4.1", - "clang-format": "1.2.3", - "diff": "^3.5.0", + "diff": "^4.0.1", "entities": "^1.1.1", "inquirer": "^6.0.0", "meow": "^5.0.0", "pify": "^4.0.0", + "prettier": "^1.15.3", "rimraf": "^2.6.2", - "tslint": "^5.9.1", + "tslint": "^5.12.0", "update-notifier": "^2.5.0", "write-file-atomic": "^2.3.0" + }, + "dependencies": { + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==" + } } }, "handlebars": { @@ -1020,21 +965,6 @@ "function-bind": "^1.1.1" } }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "^2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - } - } - }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -1123,22 +1053,22 @@ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" }, "inquirer": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.1.tgz", - "integrity": "sha512-088kl3DRT2dLU5riVMKKr1DlImd6X7smDhpXUCkJDCKvTEJeRiXh0G132HG9u5a+6Ylw9plFRY7RuTnwohYSpg==", + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.3.1.tgz", + "integrity": "sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==", "requires": { - "ansi-escapes": "^3.0.0", - "chalk": "^2.0.0", + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", "cli-cursor": "^2.1.0", "cli-width": "^2.0.0", - "external-editor": "^3.0.0", + "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.10", + "lodash": "^4.17.11", "mute-stream": "0.0.7", "run-async": "^2.2.0", - "rxjs": "^6.1.0", + "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" } }, @@ -1373,15 +1303,10 @@ "handlebars": "^4.1.0" } }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, "js-yaml": { - "version": "3.12.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.1.tgz", - "integrity": "sha512-um46hB9wNOKlwkHgiuyEVAybXBjwFUV0Z/RaHJblRd9DXltue9FTYvzCr9ErQrK9Adz5MU4gHWVaNUfdmrC8qA==", + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2249,6 +2174,11 @@ "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=" }, + "prettier": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.17.1.tgz", + "integrity": "sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==" + }, "propagate": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/propagate/-/propagate-1.0.0.tgz", @@ -2318,9 +2248,9 @@ } }, "registry-auth-token": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.2.tgz", - "integrity": "sha512-JL39c60XlzCVgNrO+qq68FoNb56w/m7JYvGR2jT5iR1xBrUA3Mfx5Twk5rqTThPmQKMWydGmq8oFtDlxfrmxnQ==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" @@ -2353,9 +2283,9 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.9.0.tgz", - "integrity": "sha512-TZNye00tI67lwYvzxCxHGjwTNlUV70io54/Ed4j6PscB8xVfuBJpRenI/o6dVk0cY0PYTY27AgCoGGxRnYuItQ==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", + "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "requires": { "path-parse": "^1.0.6" } @@ -2391,9 +2321,9 @@ } }, "rxjs": { - "version": "6.3.3", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", - "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } @@ -2531,17 +2461,17 @@ } }, "strip-ansi": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", - "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { - "ansi-regex": "^4.0.0" + "ansi-regex": "^4.1.0" }, "dependencies": { "ansi-regex": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", - "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" } } }, @@ -2732,22 +2662,23 @@ "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.12.1.tgz", - "integrity": "sha512-sfodBHOucFg6egff8d1BvuofoOQ/nOeYNfbp7LDlKBcLNrL3lmS5zoiDGyOMdT7YsEXAwWpTdAHwOGOc8eRZAw==", + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.16.0.tgz", + "integrity": "sha512-UxG2yNxJ5pgGwmMzPMYh/CCnCnh0HfPgtlVRDs1ykZklufFBL1ZoTlWFRz2NQjcoEiDoRp+JyT0lhBbbH/obyA==", "requires": { - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", - "js-yaml": "^3.7.0", + "js-yaml": "^3.13.0", "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", - "tsutils": "^2.27.2" + "tsutils": "^2.29.0" } }, "tsutils": { @@ -2931,9 +2862,9 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", "requires": { "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", diff --git a/packages/opencensus-resource-util/package.json b/packages/opencensus-resource-util/package.json index c4d3ed765..3246072aa 100644 --- a/packages/opencensus-resource-util/package.json +++ b/packages/opencensus-resource-util/package.json @@ -53,7 +53,7 @@ "@types/nock": "^10.0.0", "@types/node": "^9.4.7", "codecov": "^3.4.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "mocha": "^6.1.0", "nock": "^10.0.0", "nyc": "^14.0.0", diff --git a/packages/opencensus-resource-util/src/constants.ts b/packages/opencensus-resource-util/src/constants.ts index 9eb644ab0..3b796dc20 100644 --- a/packages/opencensus-resource-util/src/constants.ts +++ b/packages/opencensus-resource-util/src/constants.ts @@ -41,7 +41,7 @@ export const CLOUD_RESOURCE = { ACCOUNT_ID_KEY: 'cloud.account.id', /** Key for the zone in which entities are running. */ - ZONE_KEY: 'cloud.zone' + ZONE_KEY: 'cloud.zone', }; /** Constants for K8S container Resource. */ @@ -56,7 +56,7 @@ export const CONTAINER_RESOURCE = { IMAGE_NAME_KEY: 'container.image.name', /** Key for the container image tag. */ - IMAGE_TAG_KEY: 'container.image.tag' + IMAGE_TAG_KEY: 'container.image.tag', }; /** @@ -84,7 +84,7 @@ export const HOST_RESOURCE = { ID_KEY: 'host.id', /** Key for the type of the host (machine type). */ - TYPE_KEY: 'host.type' + TYPE_KEY: 'host.type', }; /** Constants for Kubernetes deployment service Resource. */ @@ -99,5 +99,5 @@ export const K8S_RESOURCE = { NAMESPACE_NAME_KEY: 'k8s.namespace.name', /** Key for the name of the pod. */ - POD_NAME_KEY: 'k8s.pod.name' + POD_NAME_KEY: 'k8s.pod.name', }; diff --git a/packages/opencensus-resource-util/src/detect-resource.ts b/packages/opencensus-resource-util/src/detect-resource.ts index 6b885841f..6daf938d7 100644 --- a/packages/opencensus-resource-util/src/detect-resource.ts +++ b/packages/opencensus-resource-util/src/detect-resource.ts @@ -14,8 +14,14 @@ * limitations under the License. */ -import {CoreResource, Resource} from '@opencensus/core'; -import {getAwsEC2Resource, getComputerEngineResource, getKubernetesEngineResource, getResourceType, ResourceType} from './resource-utils'; +import { CoreResource, Resource } from '@opencensus/core'; +import { + getAwsEC2Resource, + getComputerEngineResource, + getKubernetesEngineResource, + getResourceType, + ResourceType, +} from './resource-utils'; /** * Returns a Resource. Detector sequentially runs resource detection from diff --git a/packages/opencensus-resource-util/src/resource-utils.ts b/packages/opencensus-resource-util/src/resource-utils.ts index d8ee6edf4..3309e4be6 100644 --- a/packages/opencensus-resource-util/src/resource-utils.ts +++ b/packages/opencensus-resource-util/src/resource-utils.ts @@ -19,16 +19,21 @@ * where the application is running. */ -import {Labels, Resource} from '@opencensus/core'; +import { Labels, Resource } from '@opencensus/core'; import * as gcpMetadata from 'gcp-metadata'; import * as http from 'http'; import * as os from 'os'; -import {CLOUD_RESOURCE, CONTAINER_RESOURCE, HOST_RESOURCE, K8S_RESOURCE} from './constants'; +import { + CLOUD_RESOURCE, + CONTAINER_RESOURCE, + HOST_RESOURCE, + K8S_RESOURCE, +} from './constants'; import * as constants from './resource-labels'; export const AWS_INSTANCE_IDENTITY_DOCUMENT_URI = - 'http://169.254.169.254/latest/dynamic/instance-identity/document'; -let resourceType: ResourceType|undefined; + 'http://169.254.169.254/latest/dynamic/instance-identity/document'; +let resourceType: ResourceType | undefined; let gkeResourceLabels: Labels = {}; let gceResourceLabels: Labels = {}; let awsResourceLabels: Labels = {}; @@ -38,7 +43,7 @@ export enum ResourceType { GCP_GKE_CONTAINER = 'k8s_container', GCP_GCE_INSTANCE = 'gce_instance', AWS_EC2_INSTANCE = 'aws_ec2_instance', - NONE = 'NONE' + NONE = 'NONE', } /** Determine the compute environment in which the code is running. */ @@ -72,7 +77,7 @@ async function isRunningOnAwsEc2() { try { const awsIdentityDocument: Labels = await awsMetadataAccessor(); awsResourceLabels[CLOUD_RESOURCE.ACCOUNT_ID_KEY] = - awsIdentityDocument.accountId; + awsIdentityDocument.accountId; awsResourceLabels[CLOUD_RESOURCE.REGION_KEY] = awsIdentityDocument.region; awsResourceLabels[HOST_RESOURCE.ID_KEY] = awsIdentityDocument.instanceId; return true; @@ -84,35 +89,42 @@ async function isRunningOnAwsEc2() { /** Returns Resource for GCP GCE instance. */ export async function getComputerEngineResource(): Promise { if (Object.keys(gceResourceLabels).length === 0) { - const [projectId, instanceId, zoneId] = - await Promise.all([getProjectId(), getInstanceId(), getZone()]); + const [projectId, instanceId, zoneId] = await Promise.all([ + getProjectId(), + getInstanceId(), + getZone(), + ]); gceResourceLabels[CLOUD_RESOURCE.ACCOUNT_ID_KEY] = projectId; gceResourceLabels[HOST_RESOURCE.ID_KEY] = instanceId; gceResourceLabels[CLOUD_RESOURCE.ZONE_KEY] = zoneId; } - return {type: constants.GCP_GCE_INSTANCE_TYPE, labels: gceResourceLabels}; + return { type: constants.GCP_GCE_INSTANCE_TYPE, labels: gceResourceLabels }; } /** Returns Resource for GCP GKE container. */ export async function getKubernetesEngineResource(): Promise { if (Object.keys(gkeResourceLabels).length === 0) { - const [projectId, zoneId, clusterName, hostname] = await Promise.all( - [getProjectId(), getZone(), getClusterName(), getHostname()]); + const [projectId, zoneId, clusterName, hostname] = await Promise.all([ + getProjectId(), + getZone(), + getClusterName(), + getHostname(), + ]); gkeResourceLabels[CLOUD_RESOURCE.ACCOUNT_ID_KEY] = projectId; gkeResourceLabels[CLOUD_RESOURCE.ZONE_KEY] = zoneId; gkeResourceLabels[K8S_RESOURCE.CLUSTER_NAME_KEY] = clusterName; gkeResourceLabels[K8S_RESOURCE.NAMESPACE_NAME_KEY] = - process.env.NAMESPACE || ''; + process.env.NAMESPACE || ''; gkeResourceLabels[K8S_RESOURCE.POD_NAME_KEY] = hostname; gkeResourceLabels[CONTAINER_RESOURCE.NAME_KEY] = - process.env.CONTAINER_NAME || ''; + process.env.CONTAINER_NAME || ''; } - return {type: constants.K8S_CONTAINER_TYPE, labels: gkeResourceLabels}; + return { type: constants.K8S_CONTAINER_TYPE, labels: gkeResourceLabels }; } /** Returns Resource for AWS EC2 instance. */ export async function getAwsEC2Resource(): Promise { - return {type: constants.AWS_EC2_INSTANCE_TYPE, labels: awsResourceLabels}; + return { type: constants.AWS_EC2_INSTANCE_TYPE, labels: awsResourceLabels }; } /** @@ -127,27 +139,27 @@ async function awsMetadataAccessor(): Promise { reject(new Error('EC2 metadata api request timed out.')); }, 2000); - const req = http.get(AWS_INSTANCE_IDENTITY_DOCUMENT_URI, (res) => { + const req = http.get(AWS_INSTANCE_IDENTITY_DOCUMENT_URI, res => { clearTimeout(timeoutId); - const {statusCode} = res; + const { statusCode } = res; res.setEncoding('utf8'); let rawData = ''; - res.on('data', (chunk) => rawData += chunk); + res.on('data', chunk => (rawData += chunk)); res.on('end', () => { if (statusCode && statusCode >= 200 && statusCode < 300) { try { resolve(JSON.parse(rawData)); } catch (e) { - res.resume(); // consume response data to free up memory + res.resume(); // consume response data to free up memory reject(e); } } else { - res.resume(); // consume response data to free up memory + res.resume(); // consume response data to free up memory reject(new Error('Failed to load page, status code: ' + statusCode)); } }); }); - req.on('error', (err) => { + req.on('error', err => { clearTimeout(timeoutId); reject(err); }); diff --git a/packages/opencensus-resource-util/test/test-detect-resource.ts b/packages/opencensus-resource-util/test/test-detect-resource.ts index 5e74dd431..f1678c8c4 100644 --- a/packages/opencensus-resource-util/test/test-detect-resource.ts +++ b/packages/opencensus-resource-util/test/test-detect-resource.ts @@ -13,17 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {CoreResource} from '@opencensus/core'; +import { CoreResource } from '@opencensus/core'; import * as assert from 'assert'; -import {BASE_PATH, HEADER_NAME, HEADER_VALUE, HOST_ADDRESS} from 'gcp-metadata'; +import { + BASE_PATH, + HEADER_NAME, + HEADER_VALUE, + HOST_ADDRESS, +} from 'gcp-metadata'; import * as nock from 'nock'; import * as resource from '../src'; -import {CLOUD_RESOURCE, CONTAINER_RESOURCE, HOST_RESOURCE, K8S_RESOURCE} from '../src/constants'; +import { + CLOUD_RESOURCE, + CONTAINER_RESOURCE, + HOST_RESOURCE, + K8S_RESOURCE, +} from '../src/constants'; import * as resourceUtil from '../src/resource-utils'; // NOTE: nodejs switches all incoming header names to lower case. const HEADERS = { - [HEADER_NAME.toLowerCase()]: HEADER_VALUE + [HEADER_NAME.toLowerCase()]: HEADER_VALUE, }; const INSTANCE_PATH = BASE_PATH + '/instance'; const INSTANCE_ID_PATH = BASE_PATH + '/instance/id'; @@ -34,7 +44,7 @@ const CLUSTER_NAME_PATH = BASE_PATH + '/instance/attributes/cluster-name'; const mockedAwsResponse = { instanceId: 'my-instance-id', accountId: 'my-account-id', - region: 'my-region' + region: 'my-region', }; describe('detectResource', () => { @@ -57,109 +67,104 @@ describe('detectResource', () => { CoreResource.setup(); }); - it('should return GCP_GKE_CONTAINER resource when KUBERNETES_SERVICE_HOST is set', - async () => { - process.env.KUBERNETES_SERVICE_HOST = 'my-host'; - const scope = nock(HOST_ADDRESS) - .get(CLUSTER_NAME_PATH) - .reply(200, () => 'my-cluster', HEADERS) - .get(PROJECT_ID_PATH) - .reply(200, () => 'my-project-id', HEADERS) - .get(ZONE_PATH) - .reply(200, () => 'project/zone/my-zone', HEADERS) - .get(HOSTNAME_PATH) - .reply(200, () => 'my-hostname', HEADERS); - const {type, labels} = await resource.detectResource(); - scope.done(); + it('should return GCP_GKE_CONTAINER resource when KUBERNETES_SERVICE_HOST is set', async () => { + process.env.KUBERNETES_SERVICE_HOST = 'my-host'; + const scope = nock(HOST_ADDRESS) + .get(CLUSTER_NAME_PATH) + .reply(200, () => 'my-cluster', HEADERS) + .get(PROJECT_ID_PATH) + .reply(200, () => 'my-project-id', HEADERS) + .get(ZONE_PATH) + .reply(200, () => 'project/zone/my-zone', HEADERS) + .get(HOSTNAME_PATH) + .reply(200, () => 'my-hostname', HEADERS); + const { type, labels } = await resource.detectResource(); + scope.done(); - assert.deepStrictEqual(type, resource.K8S_CONTAINER_TYPE); - assert.strictEqual(Object.keys(labels).length, 6); - assert.strictEqual( - labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); - assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], 'my-zone'); - assert.strictEqual(labels[K8S_RESOURCE.CLUSTER_NAME_KEY], 'my-cluster'); - assert.strictEqual(labels[K8S_RESOURCE.POD_NAME_KEY], 'my-hostname'); - assert.strictEqual(labels[K8S_RESOURCE.NAMESPACE_NAME_KEY], ''); - assert.strictEqual(labels[CONTAINER_RESOURCE.NAME_KEY], ''); - }); + assert.deepStrictEqual(type, resource.K8S_CONTAINER_TYPE); + assert.strictEqual(Object.keys(labels).length, 6); + assert.strictEqual(labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); + assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], 'my-zone'); + assert.strictEqual(labels[K8S_RESOURCE.CLUSTER_NAME_KEY], 'my-cluster'); + assert.strictEqual(labels[K8S_RESOURCE.POD_NAME_KEY], 'my-hostname'); + assert.strictEqual(labels[K8S_RESOURCE.NAMESPACE_NAME_KEY], ''); + assert.strictEqual(labels[CONTAINER_RESOURCE.NAME_KEY], ''); + }); - it('should return GCP_GKE_CONTAINER resource when KUBERNETES_SERVICE_HOST, NAMESPACE and CONTAINER_NAME is set', - async () => { - process.env.KUBERNETES_SERVICE_HOST = 'my-host'; - process.env.NAMESPACE = 'my-namespace'; - process.env.CONTAINER_NAME = 'my-container-name'; - const scope = nock(HOST_ADDRESS) - .get(CLUSTER_NAME_PATH) - .reply(200, () => 'my-cluster', HEADERS) - .get(PROJECT_ID_PATH) - .reply(200, () => 'my-project-id', HEADERS) - .get(ZONE_PATH) - .reply(200, () => 'project/zone/my-zone', HEADERS) - .get(HOSTNAME_PATH) - .reply(200, () => 'my-hostname', HEADERS); - const {type, labels} = await resource.detectResource(); - scope.done(); + it('should return GCP_GKE_CONTAINER resource when KUBERNETES_SERVICE_HOST, NAMESPACE and CONTAINER_NAME is set', async () => { + process.env.KUBERNETES_SERVICE_HOST = 'my-host'; + process.env.NAMESPACE = 'my-namespace'; + process.env.CONTAINER_NAME = 'my-container-name'; + const scope = nock(HOST_ADDRESS) + .get(CLUSTER_NAME_PATH) + .reply(200, () => 'my-cluster', HEADERS) + .get(PROJECT_ID_PATH) + .reply(200, () => 'my-project-id', HEADERS) + .get(ZONE_PATH) + .reply(200, () => 'project/zone/my-zone', HEADERS) + .get(HOSTNAME_PATH) + .reply(200, () => 'my-hostname', HEADERS); + const { type, labels } = await resource.detectResource(); + scope.done(); - assert.deepStrictEqual(type, resource.K8S_CONTAINER_TYPE); - assert.strictEqual(Object.keys(labels).length, 6); - assert.strictEqual( - labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); - assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], 'my-zone'); - assert.strictEqual(labels[K8S_RESOURCE.CLUSTER_NAME_KEY], 'my-cluster'); - assert.strictEqual(labels[K8S_RESOURCE.POD_NAME_KEY], 'my-hostname'); - assert.strictEqual( - labels[K8S_RESOURCE.NAMESPACE_NAME_KEY], 'my-namespace'); - assert.strictEqual( - labels[CONTAINER_RESOURCE.NAME_KEY], 'my-container-name'); + assert.deepStrictEqual(type, resource.K8S_CONTAINER_TYPE); + assert.strictEqual(Object.keys(labels).length, 6); + assert.strictEqual(labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); + assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], 'my-zone'); + assert.strictEqual(labels[K8S_RESOURCE.CLUSTER_NAME_KEY], 'my-cluster'); + assert.strictEqual(labels[K8S_RESOURCE.POD_NAME_KEY], 'my-hostname'); + assert.strictEqual(labels[K8S_RESOURCE.NAMESPACE_NAME_KEY], 'my-namespace'); + assert.strictEqual( + labels[CONTAINER_RESOURCE.NAME_KEY], + 'my-container-name' + ); - // fetch again, this shouldn't make http call again - const {type: type1, labels: labels1} = await resource.detectResource(); - assert.deepStrictEqual(type, type1); - assert.deepStrictEqual(labels, labels1); - }); + // fetch again, this shouldn't make http call again + const { type: type1, labels: labels1 } = await resource.detectResource(); + assert.deepStrictEqual(type, type1); + assert.deepStrictEqual(labels, labels1); + }); - it('Should merge resources from CoreResource and detected k8s resource', - async () => { - process.env.OC_RESOURCE_TYPE = 'k8s.io/container'; - process.env.OC_RESOURCE_LABELS = - 'k8s.pod.name=pod-xyz-123,container.name=c1,k8s.namespace.name=default'; - CoreResource.setup(); + it('Should merge resources from CoreResource and detected k8s resource', async () => { + process.env.OC_RESOURCE_TYPE = 'k8s.io/container'; + process.env.OC_RESOURCE_LABELS = + 'k8s.pod.name=pod-xyz-123,container.name=c1,k8s.namespace.name=default'; + CoreResource.setup(); - process.env.KUBERNETES_SERVICE_HOST = 'my-host'; - const scope = nock(HOST_ADDRESS) - .get(CLUSTER_NAME_PATH) - .reply(200, () => 'my-cluster', HEADERS) - .get(PROJECT_ID_PATH) - .reply(200, () => 'my-project-id', HEADERS) - .get(ZONE_PATH) - .reply(200, () => 'project/zone/my-zone', HEADERS) - .get(HOSTNAME_PATH) - .reply(200, () => 'my-hostname', HEADERS); - const {type, labels} = await resource.detectResource(); - scope.done(); + process.env.KUBERNETES_SERVICE_HOST = 'my-host'; + const scope = nock(HOST_ADDRESS) + .get(CLUSTER_NAME_PATH) + .reply(200, () => 'my-cluster', HEADERS) + .get(PROJECT_ID_PATH) + .reply(200, () => 'my-project-id', HEADERS) + .get(ZONE_PATH) + .reply(200, () => 'project/zone/my-zone', HEADERS) + .get(HOSTNAME_PATH) + .reply(200, () => 'my-hostname', HEADERS); + const { type, labels } = await resource.detectResource(); + scope.done(); - assert.deepStrictEqual(type, resource.K8S_CONTAINER_TYPE); - assert.strictEqual(Object.keys(labels).length, 6); - assert.strictEqual( - labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); - assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], 'my-zone'); - assert.strictEqual(labels[K8S_RESOURCE.CLUSTER_NAME_KEY], 'my-cluster'); - assert.strictEqual(labels[K8S_RESOURCE.POD_NAME_KEY], 'pod-xyz-123'); - assert.strictEqual(labels[K8S_RESOURCE.NAMESPACE_NAME_KEY], 'default'); - assert.strictEqual(labels[CONTAINER_RESOURCE.NAME_KEY], 'c1'); - }); + assert.deepStrictEqual(type, resource.K8S_CONTAINER_TYPE); + assert.strictEqual(Object.keys(labels).length, 6); + assert.strictEqual(labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); + assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], 'my-zone'); + assert.strictEqual(labels[K8S_RESOURCE.CLUSTER_NAME_KEY], 'my-cluster'); + assert.strictEqual(labels[K8S_RESOURCE.POD_NAME_KEY], 'pod-xyz-123'); + assert.strictEqual(labels[K8S_RESOURCE.NAMESPACE_NAME_KEY], 'default'); + assert.strictEqual(labels[CONTAINER_RESOURCE.NAME_KEY], 'c1'); + }); it('should return GCP_GCE_INSTANCE resource', async () => { const scope = nock(HOST_ADDRESS) - .get(INSTANCE_PATH) - .reply(200, {}, HEADERS) - .get(PROJECT_ID_PATH) - .reply(200, () => 'my-project-id', HEADERS) - .get(ZONE_PATH) - .reply(200, () => 'project/zone/my-zone', HEADERS) - .get(INSTANCE_ID_PATH) - .reply(200, () => 4520031799277581759, HEADERS); - const {type, labels} = await resource.detectResource(); + .get(INSTANCE_PATH) + .reply(200, {}, HEADERS) + .get(PROJECT_ID_PATH) + .reply(200, () => 'my-project-id', HEADERS) + .get(ZONE_PATH) + .reply(200, () => 'project/zone/my-zone', HEADERS) + .get(INSTANCE_ID_PATH) + .reply(200, () => 4520031799277581759, HEADERS); + const { type, labels } = await resource.detectResource(); scope.done(); assert.deepStrictEqual(type, resource.GCP_GCE_INSTANCE_TYPE); @@ -171,18 +176,18 @@ describe('detectResource', () => { it('should retry if the initial request fails', async () => { const scope = nock(HOST_ADDRESS) - .get(INSTANCE_PATH) - .times(2) - .reply(500) - .get(INSTANCE_PATH) - .reply(200, {}, HEADERS) - .get(PROJECT_ID_PATH) - .reply(200, () => 'my-project-id', HEADERS) - .get(ZONE_PATH) - .reply(200, () => 'project/zone/my-zone', HEADERS) - .get(INSTANCE_ID_PATH) - .reply(200, () => 4520031799277581759, HEADERS); - const {type, labels} = await resource.detectResource(); + .get(INSTANCE_PATH) + .times(2) + .reply(500) + .get(INSTANCE_PATH) + .reply(200, {}, HEADERS) + .get(PROJECT_ID_PATH) + .reply(200, () => 'my-project-id', HEADERS) + .get(ZONE_PATH) + .reply(200, () => 'project/zone/my-zone', HEADERS) + .get(INSTANCE_ID_PATH) + .reply(200, () => 4520031799277581759, HEADERS); + const { type, labels } = await resource.detectResource(); scope.done(); assert.deepStrictEqual(type, resource.GCP_GCE_INSTANCE_TYPE); @@ -192,70 +197,67 @@ describe('detectResource', () => { assert.strictEqual(labels[HOST_RESOURCE.ID_KEY], '4520031799277582000'); }); - it('should return GCP_GCE_INSTANCE resource and empty data for non avaiable metadata attribute', - async () => { - const scope = nock(HOST_ADDRESS) - .get(INSTANCE_PATH) - .reply(200, {}, HEADERS) - .get(PROJECT_ID_PATH) - .reply(200, () => 'my-project-id', HEADERS) - .get(ZONE_PATH) - .reply(413) - .get(INSTANCE_ID_PATH) - .reply(400, undefined, HEADERS); - const {type, labels} = await resource.detectResource(); - scope.done(); + it('should return GCP_GCE_INSTANCE resource and empty data for non avaiable metadata attribute', async () => { + const scope = nock(HOST_ADDRESS) + .get(INSTANCE_PATH) + .reply(200, {}, HEADERS) + .get(PROJECT_ID_PATH) + .reply(200, () => 'my-project-id', HEADERS) + .get(ZONE_PATH) + .reply(413) + .get(INSTANCE_ID_PATH) + .reply(400, undefined, HEADERS); + const { type, labels } = await resource.detectResource(); + scope.done(); - assert.deepStrictEqual(type, resource.GCP_GCE_INSTANCE_TYPE); - assert.strictEqual(Object.keys(labels).length, 3); - assert.strictEqual( - labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); - assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], ''); - assert.strictEqual(labels[HOST_RESOURCE.ID_KEY], ''); + assert.deepStrictEqual(type, resource.GCP_GCE_INSTANCE_TYPE); + assert.strictEqual(Object.keys(labels).length, 3); + assert.strictEqual(labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); + assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], ''); + assert.strictEqual(labels[HOST_RESOURCE.ID_KEY], ''); - // fetch again, this shouldn't make http call again - const {type: type1, labels: labels1} = await resource.detectResource(); - assert.deepStrictEqual(type, type1); - assert.deepStrictEqual(labels, labels1); - }); + // fetch again, this shouldn't make http call again + const { type: type1, labels: labels1 } = await resource.detectResource(); + assert.deepStrictEqual(type, type1); + assert.deepStrictEqual(labels, labels1); + }); - it('Should merge resources from CoreResource and detected gce resource', - async () => { - process.env.OC_RESOURCE_TYPE = 'global'; - process.env.OC_RESOURCE_LABELS = - 'cloud.zone=zone1,user=user1,version=1.0'; - CoreResource.setup(); + it('Should merge resources from CoreResource and detected gce resource', async () => { + process.env.OC_RESOURCE_TYPE = 'global'; + process.env.OC_RESOURCE_LABELS = 'cloud.zone=zone1,user=user1,version=1.0'; + CoreResource.setup(); - const scope = nock(HOST_ADDRESS) - .get(INSTANCE_PATH) - .reply(200, {}, HEADERS) - .get(PROJECT_ID_PATH) - .reply(200, () => 'my-project-id', HEADERS) - .get(ZONE_PATH) - .reply(200, () => 'project/zone/my-zone', HEADERS) - .get(INSTANCE_ID_PATH) - .reply(200, () => 4520031799277581759, HEADERS); - const {type, labels} = await resource.detectResource(); - scope.done(); + const scope = nock(HOST_ADDRESS) + .get(INSTANCE_PATH) + .reply(200, {}, HEADERS) + .get(PROJECT_ID_PATH) + .reply(200, () => 'my-project-id', HEADERS) + .get(ZONE_PATH) + .reply(200, () => 'project/zone/my-zone', HEADERS) + .get(INSTANCE_ID_PATH) + .reply(200, () => 4520031799277581759, HEADERS); + const { type, labels } = await resource.detectResource(); + scope.done(); - assert.deepStrictEqual(type, 'global'); - assert.strictEqual(Object.keys(labels).length, 5); - assert.strictEqual( - labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); - assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], 'zone1'); - assert.strictEqual(labels[HOST_RESOURCE.ID_KEY], '4520031799277582000'); - assert.strictEqual(labels['user'], 'user1'); - assert.strictEqual(labels['version'], '1.0'); - }); + assert.deepStrictEqual(type, 'global'); + assert.strictEqual(Object.keys(labels).length, 5); + assert.strictEqual(labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-project-id'); + assert.strictEqual(labels[CLOUD_RESOURCE.ZONE_KEY], 'zone1'); + assert.strictEqual(labels[HOST_RESOURCE.ID_KEY], '4520031799277582000'); + assert.strictEqual(labels['user'], 'user1'); + assert.strictEqual(labels['version'], '1.0'); + }); it('should return aws_ec2_instance resource', async () => { - const gcpScope = nock(HOST_ADDRESS).get(INSTANCE_PATH).replyWithError({ - code: 'ENOTFOUND' - }); + const gcpScope = nock(HOST_ADDRESS) + .get(INSTANCE_PATH) + .replyWithError({ + code: 'ENOTFOUND', + }); const awsScope = nock(resourceUtil.AWS_INSTANCE_IDENTITY_DOCUMENT_URI) - .get('') - .reply(200, () => mockedAwsResponse, HEADERS); - const {type, labels} = await resource.detectResource(); + .get('') + .reply(200, () => mockedAwsResponse, HEADERS); + const { type, labels } = await resource.detectResource(); awsScope.done(); gcpScope.done(); @@ -266,43 +268,45 @@ describe('detectResource', () => { assert.strictEqual(labels[CLOUD_RESOURCE.REGION_KEY], 'my-region'); // fetch again, this shouldn't make http call again - const {type: type1, labels: labels1} = await resource.detectResource(); + const { type: type1, labels: labels1 } = await resource.detectResource(); assert.deepStrictEqual(type, type1); assert.deepStrictEqual(labels, labels1); }); - it('Should merge resources from CoreResource and detected aws_ec2_instance resource', - async () => { - process.env.OC_RESOURCE_TYPE = 'aws.com/ec2/instance'; - process.env.OC_RESOURCE_LABELS = 'cloud.region=default'; - CoreResource.setup(); + it('Should merge resources from CoreResource and detected aws_ec2_instance resource', async () => { + process.env.OC_RESOURCE_TYPE = 'aws.com/ec2/instance'; + process.env.OC_RESOURCE_LABELS = 'cloud.region=default'; + CoreResource.setup(); - const gcpScope = nock(HOST_ADDRESS).get(INSTANCE_PATH).replyWithError({ - code: 'ENOTFOUND' - }); - const awsScope = nock(resourceUtil.AWS_INSTANCE_IDENTITY_DOCUMENT_URI) - .get('') - .reply(200, () => mockedAwsResponse, HEADERS); - const {type, labels} = await resource.detectResource(); - awsScope.done(); - gcpScope.done(); + const gcpScope = nock(HOST_ADDRESS) + .get(INSTANCE_PATH) + .replyWithError({ + code: 'ENOTFOUND', + }); + const awsScope = nock(resourceUtil.AWS_INSTANCE_IDENTITY_DOCUMENT_URI) + .get('') + .reply(200, () => mockedAwsResponse, HEADERS); + const { type, labels } = await resource.detectResource(); + awsScope.done(); + gcpScope.done(); - assert.deepStrictEqual(type, resource.AWS_EC2_INSTANCE_TYPE); - assert.strictEqual(Object.keys(labels).length, 3); - assert.strictEqual( - labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-account-id'); - assert.strictEqual(labels[HOST_RESOURCE.ID_KEY], 'my-instance-id'); - assert.strictEqual(labels[CLOUD_RESOURCE.REGION_KEY], 'default'); - }); + assert.deepStrictEqual(type, resource.AWS_EC2_INSTANCE_TYPE); + assert.strictEqual(Object.keys(labels).length, 3); + assert.strictEqual(labels[CLOUD_RESOURCE.ACCOUNT_ID_KEY], 'my-account-id'); + assert.strictEqual(labels[HOST_RESOURCE.ID_KEY], 'my-instance-id'); + assert.strictEqual(labels[CLOUD_RESOURCE.REGION_KEY], 'default'); + }); it('return empty labels when failed to find any resources', async () => { - const gcpScope = nock(HOST_ADDRESS).get(INSTANCE_PATH).replyWithError({ - code: 'ENOTFOUND' - }); + const gcpScope = nock(HOST_ADDRESS) + .get(INSTANCE_PATH) + .replyWithError({ + code: 'ENOTFOUND', + }); const awsScope = nock(resourceUtil.AWS_INSTANCE_IDENTITY_DOCUMENT_URI) - .get('') - .replyWithError({code: 'ENOTFOUND'}); - const {type, labels} = await resource.detectResource(); + .get('') + .replyWithError({ code: 'ENOTFOUND' }); + const { type, labels } = await resource.detectResource(); awsScope.done(); gcpScope.done();