UNPKG

3.56 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var tslib_1 = require("tslib");
4var statsd_1 = require("@shopify/statsd");
5var tags_1 = require("./tags");
6var timing_1 = require("./timing");
7var content_1 = require("./content");
8var timer_1 = require("./timer");
9var CustomMetric;
10(function (CustomMetric) {
11 CustomMetric["ContentLength"] = "request_content_length";
12 CustomMetric["QueuingTime"] = "request_queuing_time";
13 CustomMetric["RequestDuration"] = "request_time";
14})(CustomMetric = exports.CustomMetric || (exports.CustomMetric = {}));
15function metrics(_a) {
16 var prefix = _a.prefix, host = _a.host, _b = _a.skipInstrumentation, skipInstrumentation = _b === void 0 ? false : _b, logger = _a.logger;
17 var statsdHost = host.split(':')[0];
18 var statsdPort = parseInt(host.split(':')[1], 10);
19 return function statsdMiddleware(ctx, next) {
20 return tslib_1.__awaiter(this, void 0, void 0, function () {
21 var metrics, promises, timer, queuingTime, duration, contentLength;
22 return tslib_1.__generator(this, function (_a) {
23 switch (_a.label) {
24 case 0:
25 metrics = new statsd_1.StatsDClient({
26 host: statsdHost,
27 port: statsdPort,
28 prefix: prefix,
29 globalTags: tags_1.tagsForRequest(ctx),
30 // eslint-disable-next-line no-console
31 logger: logger || ctx.log || console.log,
32 });
33 promises = [];
34 if (!skipInstrumentation) {
35 timer = timer_1.initTimer();
36 queuingTime = timing_1.getQueuingTime(ctx);
37 if (queuingTime) {
38 promises.push(metrics.distribution(CustomMetric.QueuingTime, queuingTime));
39 }
40 }
41 // allow later middleware to add metrics
42 ctx.metrics = metrics;
43 _a.label = 1;
44 case 1:
45 _a.trys.push([1, , 3, 6]);
46 return [4 /*yield*/, next()];
47 case 2:
48 _a.sent();
49 return [3 /*break*/, 6];
50 case 3:
51 metrics.addGlobalTags(tags_1.tagsForResponse(ctx));
52 if (!skipInstrumentation) {
53 if (timer) {
54 duration = timer.stop();
55 promises.push(metrics.distribution(CustomMetric.RequestDuration, duration));
56 }
57 contentLength = content_1.getContentLength(ctx);
58 if (contentLength) {
59 promises.push(metrics.distribution(CustomMetric.ContentLength, contentLength));
60 }
61 }
62 return [4 /*yield*/, Promise.all(promises)];
63 case 4:
64 _a.sent();
65 return [4 /*yield*/, metrics.close()];
66 case 5:
67 _a.sent();
68 return [7 /*endfinally*/];
69 case 6: return [2 /*return*/];
70 }
71 });
72 });
73 };
74}
75exports.default = metrics;