UNPKG

@netdata/charts

Version:

Netdata frontend SDK and chart utilities

418 lines (417 loc) 22.1 kB
"use strict"; var _dataFetcher = require("./dataFetcher"); var _calculations = require("./calculations"); var _testUtilities = require("@jest/testUtilities"); function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); } function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } var customPeriods = [{ id: "24h", label: "24 hours before", offsetSeconds: 86400 }, { id: "7d", label: "7 days before", offsetSeconds: 604800 }]; var makeRawPayload = function makeRawPayload() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$value = _ref.value, value = _ref$value === void 0 ? 51 : _ref$value, _ref$pointValue = _ref.pointValue, pointValue = _ref$pointValue === void 0 ? 1 : _ref$pointValue; return { result: { labels: ["time", "cpu"], point: { value: pointValue, arp: pointValue ? 0 : 1 }, data: [[1000, pointValue ? [50, value] : [value, 50]], [2000, pointValue ? [60, value + 10] : [value + 10, 60]]] }, view: { update_every: 5 } }; }; var loadChart = function loadChart(chart) { return new Promise(function (resolve) { var unsubscribe = chart.on("successFetch", function () { unsubscribe(); resolve(); }); chart.fetch(); }); }; describe("dataFetcher", function () { var chart; beforeEach(function () { chart = (0, _testUtilities.makeTestChart)({ attributes: { after: 1000, before: 2000, contextScope: ["system.cpu"], customPeriods: customPeriods } }).chart; }); describe("getCurrentTimeRange", function () { it("uses the chart's canonical absolute window", function () { expect((0, _dataFetcher.getCurrentTimeRange)(chart)).toEqual({ after: 1000, before: 2000 }); chart.updateAttributes({ after: -900, before: 0, renderedAt: 2000000 }); expect((0, _dataFetcher.getCurrentTimeRange)(chart)).toEqual({ after: 1100, before: 2000 }); }); }); describe("getComparisonPeriods", function () { it("generates the selected and custom periods in order", function () { expect((0, _dataFetcher.getComparisonPeriods)({ after: 1000, before: 2000 }, customPeriods)).toEqual([{ id: "selected", label: "Selected timeframe", after: 1000, before: 2000, isBase: true }, _objectSpread(_objectSpread({}, customPeriods[0]), {}, { after: 1000 - 86400, before: 2000 - 86400 }), _objectSpread(_objectSpread({}, customPeriods[1]), {}, { after: 1000 - 604800, before: 2000 - 604800 })]); }); }); describe("normalizeComparisonPayload", function () { it("extracts the configured scalar value without chart-only object copies", function () { var result = (0, _dataFetcher.normalizeComparisonPayload)({ result: { labels: ["time", "cpu", "memory"], point: { value: 1, arp: 2 }, data: [[1000, [50, 51, 0], [30, 31, 0]], [2000, [60, 61, 0], [40, 41, 0]]] }, view: { update_every: 5 } }); expect(result).toEqual({ labels: ["time", "cpu", "memory", "ANOMALY_RATE", "ANNOTATIONS"], data: [[1000, 51, 31, null, null], [2000, 61, 41, null, null]], viewUpdateEvery: 5 }); expect(result).not.toHaveProperty("all"); expect(result).not.toHaveProperty("tree"); expect(result).not.toHaveProperty("byDimension"); expect((0, _calculations.extractDimensionValues)(result)).toEqual({ cpu: 61, memory: 41 }); expect((0, _calculations.calculateStats)(result)).toMatchObject({ points: 2, dimensions: 4 }); }); it("supports point.value zero and preserves nulls", function () { var rawPayload = makeRawPayload({ value: 0, pointValue: 0 }); rawPayload.result.data[0][1][0] = null; expect((0, _dataFetcher.normalizeComparisonPayload)(rawPayload).data).toEqual([[1000, null, null, null], [2000, 10, null, null]]); }); it("rejects malformed responses instead of treating them as empty data", function () { expect(function () { return (0, _dataFetcher.normalizeComparisonPayload)({ result: {} }); }).toThrow("Invalid comparison response"); expect(function () { return (0, _dataFetcher.normalizeComparisonPayload)({ result: { labels: ["time", "cpu"], data: [[1000]], point: { value: 0 } } }); }).toThrow("Invalid comparison data row"); }); it("handles thousands of dimensions with the compact contract", function () { var dimensionCount = 5256; var labels = ["time"].concat(_toConsumableArray(Array.from({ length: dimensionCount }, function (_, index) { return "d".concat(index); }))); var data = Array.from({ length: 3 }, function (_, pointIndex) { return [pointIndex * 1000].concat(_toConsumableArray(Array.from({ length: dimensionCount }, function (_, dimensionIndex) { return [dimensionIndex + pointIndex, 0, 0]; }))); }); var result = (0, _dataFetcher.normalizeComparisonPayload)({ result: { labels: labels, data: data, point: { value: 0, arp: 1, pa: 2 } }, view: { update_every: 5 } }); expect(result.data).toHaveLength(3); expect(result.data[0]).toHaveLength(dimensionCount + 3); expect(result.labels).toHaveLength(dimensionCount + 3); expect(result.data[2][dimensionCount]).toBe(dimensionCount + 1); }); }); describe("fetchComparisonData", function () { it("does not request comparison data before the main chart loads", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() { var getChart, calls, _t; return _regenerator().w(function (_context) { while (1) switch (_context.n) { case 0: getChart = chart.getChart; calls = 0; chart.getChart = function () { calls++; return getChart.apply(void 0, arguments); }; _t = expect; _context.n = 1; return (0, _dataFetcher.fetchComparisonData)(chart); case 1: _t(_context.v).toEqual([]); expect(calls).toBe(0); case 2: return _context.a(2); } }, _callee); }))); it("always reuses the loaded main payload and fetches only historical periods", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() { var getChart, calls, result; return _regenerator().w(function (_context2) { while (1) switch (_context2.n) { case 0: _context2.n = 1; return loadChart(chart); case 1: getChart = chart.getChart; calls = 0; chart.getChart = function () { calls++; return getChart.apply(void 0, arguments); }; _context2.n = 2; return (0, _dataFetcher.fetchComparisonData)(chart); case 2: result = _context2.v; expect(calls).toBe(customPeriods.length); expect(result[0].payload.data).toBe(chart.getPayload().data); expect((0, _dataFetcher.getMainPeriodPayload)(chart).data).toBe(chart.getPayload().data); expect(chart.getAttribute("comparePeriods")).toBe(result); case 3: return _context2.a(2); } }, _callee2); }))); it("uses a successful empty main payload without refetching it", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() { var calls, result; return _regenerator().w(function (_context4) { while (1) switch (_context4.n) { case 0: chart.updateAttribute("loaded", true); chart.updateAttribute("customPeriods", []); calls = 0; chart.getChart = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() { return _regenerator().w(function (_context3) { while (1) switch (_context3.n) { case 0: calls++; return _context3.a(2, makeRawPayload()); } }, _callee3); })); _context4.n = 1; return (0, _dataFetcher.fetchComparisonData)(chart); case 1: result = _context4.v; expect(calls).toBe(0); expect(result).toHaveLength(1); expect(result[0].payload.data).toBe(chart.getPayload().data); expect(result[0].payload.data).toEqual([]); case 2: return _context4.a(2); } }, _callee4); }))); it("deduplicates identical concurrent batches but not completed batches", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6() { var calls, _yield$Promise$all, _yield$Promise$all2, first, second; return _regenerator().w(function (_context6) { while (1) switch (_context6.n) { case 0: _context6.n = 1; return loadChart(chart); case 1: calls = 0; chart.getChart = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() { return _regenerator().w(function (_context5) { while (1) switch (_context5.n) { case 0: calls++; _context5.n = 1; return new Promise(function (resolve) { return setTimeout(resolve, 5); }); case 1: return _context5.a(2, makeRawPayload()); } }, _callee5); })); _context6.n = 2; return Promise.all([(0, _dataFetcher.fetchComparisonData)(chart), (0, _dataFetcher.fetchComparisonData)(chart)]); case 2: _yield$Promise$all = _context6.v; _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2); first = _yield$Promise$all2[0]; second = _yield$Promise$all2[1]; expect(first).toBe(second); expect(calls).toBe(customPeriods.length); _context6.n = 3; return (0, _dataFetcher.fetchComparisonData)(chart); case 3: expect(calls).toBe(customPeriods.length * 2); case 4: return _context6.a(2); } }, _callee6); }))); it("includes complete period definitions in batch identity and keeps latest results", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8() { var calls, first, second; return _regenerator().w(function (_context8) { while (1) switch (_context8.n) { case 0: _context8.n = 1; return loadChart(chart); case 1: calls = 0; chart.getChart = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7() { return _regenerator().w(function (_context7) { while (1) switch (_context7.n) { case 0: calls++; _context7.n = 1; return new Promise(function (resolve) { return setTimeout(resolve, 5); }); case 1: return _context7.a(2, makeRawPayload({ value: calls })); } }, _callee7); })); first = (0, _dataFetcher.fetchComparisonData)(chart); chart.updateAttribute("customPeriods", customPeriods.map(function (period) { return period.id === "24h" ? _objectSpread(_objectSpread({}, period), {}, { label: "Previous day" }) : period; })); second = (0, _dataFetcher.fetchComparisonData)(chart); _context8.n = 2; return Promise.all([first, second]); case 2: expect(calls).toBe(customPeriods.length * 2); expect(chart.getAttribute("comparePeriods")[1].label).toBe("Previous day"); expect(chart.getAttribute("compareLoading")).toBe(false); case 3: return _context8.a(2); } }, _callee8); }))); it("keeps transport and malformed-response failures local to each period", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0() { var calls, result; return _regenerator().w(function (_context0) { while (1) switch (_context0.n) { case 0: _context0.n = 1; return loadChart(chart); case 1: calls = 0; chart.getChart = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9() { return _regenerator().w(function (_context9) { while (1) switch (_context9.n) { case 0: calls++; if (!(calls === 1)) { _context9.n = 1; break; } throw new Error("Network error"); case 1: return _context9.a(2, { result: {} }); } }, _callee9); })); _context0.n = 2; return (0, _dataFetcher.fetchComparisonData)(chart); case 2: result = _context0.v; expect(result[0].error).toBeNull(); expect(result[1]).toMatchObject({ payload: null, error: "Network error" }); expect(result[2]).toMatchObject({ payload: null, error: "Invalid comparison response" }); expect(chart.getAttribute("compareError")).toBeNull(); expect(chart.getAttribute("compareLoading")).toBe(false); case 3: return _context0.a(2); } }, _callee0); }))); }); });