From 76597188975da6e4abb913f89126ccb3048a6a72 Mon Sep 17 00:00:00 2001 From: Lance Ball Date: Thu, 15 Aug 2019 16:19:02 -0400 Subject: [PATCH] feat: refactor Prometheus and Hystrix metrics (#350) * feat: refactor Prometheus and Hystrix metrics Instead of continuing to add different metrics modules to the circuit breaker API, we can extract the `PrometheusMetrics` and `HystrixStats` classes as their own modules. All they need is a handle to the circuit itself so they can listen for events and/or monitor the circuit stats. This allows us to continue maintaining things like Hystrics that are deprecated upstream, without polluting our circuit breaker implementation. * squash: fix for web * squash: remove stray jsdoc * src: allow HystrixStream to accept circuits asynchronously * docs: update docs with latest changes * src: remove all hystrix and prometheus code & docs Hystrix and prometheus metrics are now handled by external modules that are in nodeshift/opossum-hystrix and nodeshift/opossum-prometheus. --- README.md | 54 +- docs/assets/split.js | 1312 ++++++++++++++++++-------------- docs/assets/style.css | 33 +- docs/index.html | 549 ++----------- docs/opossum.md | 445 +++++------ index.js | 33 +- lib/circuit.js | 50 +- lib/hystrix-formatter.js | 82 -- lib/hystrix-stats.js | 79 -- lib/prometheus-metrics.js | 56 -- test/browser/generate-index.sh | 2 +- test/browser/index.js | 1 - test/hystrix-test.js | 38 - test/prometheus-test.js | 165 ---- test/test.js | 1 - 15 files changed, 1056 insertions(+), 1844 deletions(-) delete mode 100644 lib/hystrix-formatter.js delete mode 100644 lib/hystrix-stats.js delete mode 100644 lib/prometheus-metrics.js delete mode 100644 test/hystrix-test.js delete mode 100644 test/prometheus-test.js diff --git a/README.md b/README.md index a65439e5..c70715a6 100644 --- a/README.md +++ b/README.md @@ -241,55 +241,15 @@ If you'd like to add them, run `npm install @types/opossum` in your project. ### Metrics #### Prometheus -Provide `{ usePrometheus: true }` in the options when creating a circuit to produce -metrics that are consumable by Prometheus. These metrics include information about -the circuit itself, for example how many times it has opened, as well as general Node.js -statistics, for example event loop lag. To get consolidated metrics for all circuits in your -application, use the `metrics()` function on the factory. +The [`opossum-prometheus`](https://github.com/nodeshift/opossum-prometheus) module +can be used to produce metrics that are consumable by Prometheus. +These metrics include information about the circuit itself, for example how many +times it has opened, as well as general Node.js statistics, for example event loop lag. -```js -const opossum = require('opossum'); - -// create a circuit -const circuit = opossum(functionThatMightFail, { usePrometheus: true }); - -// In an express app, expose the metrics to the Prometheus server -app.use('/metrics', (req, res) => { - res.type('text/plain'); - res.send(opossum.metrics()); -}); -``` - -The `prometheusRegistry` option allows to provide a existing -[prom-client](https://github.com/siimon/prom-client) registry. -The metrics about the circuit will be added to the provided registry instead -of the global registry. -The [default metrics](https://github.com/siimon/prom-client#default-metrics) -will not be added to the provided registry. - -```js -const opossum = require('opossum'); -const { Registry } = require('prom-client'); - -// Create a registry -const prometheusRegistry = new Registry(); - -// create a circuit -const circuit = opossum(functionThatMightFail, { - usePrometheus: true, - prometheusRegistry -}); -``` #### Hystrix - -**NOTE: Hystrix metrics are deprecated** - -A Hystrix Stream is available for use with a Hystrix Dashboard using the `circuitBreaker.hystrixStats.getHystrixStream` method. - -This method returns a [Node.js Stream](https://nodejs.org/api/stream.html), which makes it easy to create an SSE stream that will be compliant with a Hystrix Dashboard. - -Additional Reading: [Hystrix Metrics Event Stream](https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-metrics-event-stream), [Turbine](https://github.com/Netflix/Turbine/wiki), [Hystrix Dashboard](https://github.com/Netflix/Hystrix/wiki/Dashboard) +The [`opossum-hystrix`](https://github.com/nodeshift/opossum-hystrix) module can +be used to produce metrics that are consumable by the Hystrix Dashboard. ## Troubleshooting @@ -303,7 +263,7 @@ You may run into issues related to too many listeners on an `EventEmitter` like (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit ``` -This typically occurs when you have created more than ten `CircuitBreaker` instances. This is due to the fact that every circuit created is adding a listener to the stream accessed via `circuit.stats.getHystrixStream()`, and the default `EventEmitter` listener limit is 10. In some cases, seeing this error might indicate a bug in client code, where many `CircuitBreaker`s are inadvertently being created. But there are legitimate scenarios where this may not be the case. For example, it could just be that you need more than 10 `CircuitBreaker`s in your app. That's ok. +In some cases, seeing this error might indicate a bug in client code, where many `CircuitBreaker`s are inadvertently being created. But there are legitimate scenarios where this may not be the case. For example, it could just be that you need more than 10 `CircuitBreaker`s in your app. That's ok. To get around the error, you can set the number of listeners on the stream. diff --git a/docs/assets/split.js b/docs/assets/split.js index fc492d2e..71f9a60b 100644 --- a/docs/assets/split.js +++ b/docs/assets/split.js @@ -1,586 +1,782 @@ -/*! Split.js - v1.3.5 */ -// https://github.com/nathancahill/Split.js -// Copyright (c) 2017 Nathan Cahill; Licensed MIT - -(function(global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' - ? (module.exports = factory()) - : typeof define === 'function' && define.amd - ? define(factory) - : (global.Split = factory()); -})(this, function() { - 'use strict'; - // The programming goals of Split.js are to deliver readable, understandable and - // maintainable code, while at the same time manually optimizing for tiny minified file size, - // browser compatibility without additional requirements, graceful fallback (IE8 is supported) - // and very few assumptions about the user's page layout. - var global = window; - var document = global.document; - - // Save a couple long function names that are used frequently. - // This optimization saves around 400 bytes. - var addEventListener = 'addEventListener'; - var removeEventListener = 'removeEventListener'; - var getBoundingClientRect = 'getBoundingClientRect'; - var NOOP = function() { - return false; - }; - - // Figure out if we're in IE8 or not. IE8 will still render correctly, - // but will be static instead of draggable. - var isIE8 = global.attachEvent && !global[addEventListener]; - - // This library only needs two helper functions: - // - // The first determines which prefixes of CSS calc we need. - // We only need to do this once on startup, when this anonymous function is called. - // - // Tests -webkit, -moz and -o prefixes. Modified from StackOverflow: - // http://stackoverflow.com/questions/16625140/js-feature-detection-to-detect-the-usage-of-webkit-calc-over-calc/16625167#16625167 - var calc = - ['', '-webkit-', '-moz-', '-o-'] - .filter(function(prefix) { - var el = document.createElement('div'); - el.style.cssText = 'width:' + prefix + 'calc(9px)'; - - return !!el.style.length; - }) - .shift() + 'calc'; - - // The second helper function allows elements and string selectors to be used - // interchangeably. In either case an element is returned. This allows us to - // do `Split([elem1, elem2])` as well as `Split(['#id1', '#id2'])`. - var elementOrSelector = function(el) { - if (typeof el === 'string' || el instanceof String) { - return document.querySelector(el); - } - - return el; - }; - - // The main function to initialize a split. Split.js thinks about each pair - // of elements as an independant pair. Dragging the gutter between two elements - // only changes the dimensions of elements in that pair. This is key to understanding - // how the following functions operate, since each function is bound to a pair. - // - // A pair object is shaped like this: - // - // { - // a: DOM element, - // b: DOM element, - // aMin: Number, - // bMin: Number, - // dragging: Boolean, - // parent: DOM element, - // isFirst: Boolean, - // isLast: Boolean, - // direction: 'horizontal' | 'vertical' - // } - // - // The basic sequence: - // - // 1. Set defaults to something sane. `options` doesn't have to be passed at all. - // 2. Initialize a bunch of strings based on the direction we're splitting. - // A lot of the behavior in the rest of the library is paramatized down to - // rely on CSS strings and classes. - // 3. Define the dragging helper functions, and a few helpers to go with them. - // 4. Loop through the elements while pairing them off. Every pair gets an - // `pair` object, a gutter, and special isFirst/isLast properties. - // 5. Actually size the pair elements, insert gutters and attach event listeners. - var Split = function(ids, options) { - if (options === void 0) options = {}; - - var dimension; - var clientDimension; - var clientAxis; - var position; - var paddingA; - var paddingB; - var elements; - - // All DOM elements in the split should have a common parent. We can grab - // the first elements parent and hope users read the docs because the - // behavior will be whacky otherwise. - var parent = elementOrSelector(ids[0]).parentNode; - var parentFlexDirection = global.getComputedStyle(parent).flexDirection; - - // Set default options.sizes to equal percentages of the parent element. - var sizes = - options.sizes || - ids.map(function() { - return 100 / ids.length; - }); - - // Standardize minSize to an array if it isn't already. This allows minSize - // to be passed as a number. - var minSize = options.minSize !== undefined ? options.minSize : 100; - var minSizes = Array.isArray(minSize) - ? minSize - : ids.map(function() { - return minSize; - }); - var gutterSize = options.gutterSize !== undefined ? options.gutterSize : 10; - var snapOffset = options.snapOffset !== undefined ? options.snapOffset : 30; - var direction = options.direction || 'horizontal'; - var cursor = - options.cursor || - (direction === 'horizontal' ? 'ew-resize' : 'ns-resize'); - var gutter = - options.gutter || - function(i, gutterDirection) { +/*! Split.js - v1.5.11 */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.Split = factory()); +}(this, (function () { 'use strict'; + + // The programming goals of Split.js are to deliver readable, understandable and + // maintainable code, while at the same time manually optimizing for tiny minified file size, + // browser compatibility without additional requirements, graceful fallback (IE8 is supported) + // and very few assumptions about the user's page layout. + var global = window; + var document = global.document; + + // Save a couple long function names that are used frequently. + // This optimization saves around 400 bytes. + var addEventListener = 'addEventListener'; + var removeEventListener = 'removeEventListener'; + var getBoundingClientRect = 'getBoundingClientRect'; + var gutterStartDragging = '_a'; + var aGutterSize = '_b'; + var bGutterSize = '_c'; + var HORIZONTAL = 'horizontal'; + var NOOP = function () { return false; }; + + // Figure out if we're in IE8 or not. IE8 will still render correctly, + // but will be static instead of draggable. + var isIE8 = global.attachEvent && !global[addEventListener]; + + // Helper function determines which prefixes of CSS calc we need. + // We only need to do this once on startup, when this anonymous function is called. + // + // Tests -webkit, -moz and -o prefixes. Modified from StackOverflow: + // http://stackoverflow.com/questions/16625140/js-feature-detection-to-detect-the-usage-of-webkit-calc-over-calc/16625167#16625167 + var calc = (['', '-webkit-', '-moz-', '-o-'] + .filter(function (prefix) { + var el = document.createElement('div'); + el.style.cssText = "width:" + prefix + "calc(9px)"; + + return !!el.style.length + }) + .shift()) + "calc"; + + // Helper function checks if its argument is a string-like type + var isString = function (v) { return typeof v === 'string' || v instanceof String; }; + + // Helper function allows elements and string selectors to be used + // interchangeably. In either case an element is returned. This allows us to + // do `Split([elem1, elem2])` as well as `Split(['#id1', '#id2'])`. + var elementOrSelector = function (el) { + if (isString(el)) { + var ele = document.querySelector(el); + if (!ele) { + throw new Error(("Selector " + el + " did not match a DOM element")) + } + return ele + } + + return el + }; + + // Helper function gets a property from the properties object, with a default fallback + var getOption = function (options, propName, def) { + var value = options[propName]; + if (value !== undefined) { + return value + } + return def + }; + + var getGutterSize = function (gutterSize, isFirst, isLast, gutterAlign) { + if (isFirst) { + if (gutterAlign === 'end') { + return 0 + } + if (gutterAlign === 'center') { + return gutterSize / 2 + } + } else if (isLast) { + if (gutterAlign === 'start') { + return 0 + } + if (gutterAlign === 'center') { + return gutterSize / 2 + } + } + + return gutterSize + }; + + // Default options + var defaultGutterFn = function (i, gutterDirection) { var gut = document.createElement('div'); - gut.className = 'gutter gutter-' + gutterDirection; - return gut; - }; - var elementStyle = - options.elementStyle || - function(dim, size, gutSize) { + gut.className = "gutter gutter-" + gutterDirection; + return gut + }; + + var defaultElementStyleFn = function (dim, size, gutSize) { var style = {}; - if (typeof size !== 'string' && !(size instanceof String)) { - if (!isIE8) { - style[dim] = calc + '(' + size + '% - ' + gutSize + 'px)'; - } else { - style[dim] = size + '%'; - } + if (!isString(size)) { + if (!isIE8) { + style[dim] = calc + "(" + size + "% - " + gutSize + "px)"; + } else { + style[dim] = size + "%"; + } } else { - style[dim] = size; + style[dim] = size; } - return style; - }; - var gutterStyle = - options.gutterStyle || - function(dim, gutSize) { - return (obj = {}), (obj[dim] = gutSize + 'px'), obj; + return style + }; + + var defaultGutterStyleFn = function (dim, gutSize) { var obj; - }; - // 2. Initialize a bunch of strings based on the direction we're splitting. - // A lot of the behavior in the rest of the library is paramatized down to - // rely on CSS strings and classes. - if (direction === 'horizontal') { - dimension = 'width'; - clientDimension = 'clientWidth'; - clientAxis = 'clientX'; - position = 'left'; - paddingA = 'paddingLeft'; - paddingB = 'paddingRight'; - } else if (direction === 'vertical') { - dimension = 'height'; - clientDimension = 'clientHeight'; - clientAxis = 'clientY'; - position = 'top'; - paddingA = 'paddingTop'; - paddingB = 'paddingBottom'; - } + return (( obj = {}, obj[dim] = (gutSize + "px"), obj )); + }; - // 3. Define the dragging helper functions, and a few helpers to go with them. - // Each helper is bound to a pair object that contains it's metadata. This - // also makes it easy to store references to listeners that that will be - // added and removed. - // - // Even though there are no other functions contained in them, aliasing - // this to self saves 50 bytes or so since it's used so frequently. - // - // The pair object saves metadata like dragging state, position and - // event listener references. - - function setElementSize(el, size, gutSize) { - // Split.js allows setting sizes via numbers (ideally), or if you must, - // by string, like '300px'. This is less than ideal, because it breaks - // the fluid layout that `calc(% - px)` provides. You're on your own if you do that, - // make sure you calculate the gutter size by hand. - var style = elementStyle(dimension, size, gutSize); - - // eslint-disable-next-line no-param-reassign - Object.keys(style).forEach(function(prop) { - return (el.style[prop] = style[prop]); - }); - } - - function setGutterSize(gutterElement, gutSize) { - var style = gutterStyle(dimension, gutSize); - - // eslint-disable-next-line no-param-reassign - Object.keys(style).forEach(function(prop) { - return (gutterElement.style[prop] = style[prop]); - }); - } - - // Actually adjust the size of elements `a` and `b` to `offset` while dragging. - // calc is used to allow calc(percentage + gutterpx) on the whole split instance, - // which allows the viewport to be resized without additional logic. - // Element a's size is the same as offset. b's size is total size - a size. - // Both sizes are calculated from the initial parent percentage, - // then the gutter size is subtracted. - function adjust(offset) { - var a = elements[this.a]; - var b = elements[this.b]; - var percentage = a.size + b.size; - - a.size = (offset / this.size) * percentage; - b.size = percentage - (offset / this.size) * percentage; - - setElementSize(a.element, a.size, this.aGutterSize); - setElementSize(b.element, b.size, this.bGutterSize); - } - - // drag, where all the magic happens. The logic is really quite simple: + // The main function to initialize a split. Split.js thinks about each pair + // of elements as an independant pair. Dragging the gutter between two elements + // only changes the dimensions of elements in that pair. This is key to understanding + // how the following functions operate, since each function is bound to a pair. // - // 1. Ignore if the pair is not dragging. - // 2. Get the offset of the event. - // 3. Snap offset to min if within snappable range (within min + snapOffset). - // 4. Actually adjust each element in the pair to offset. + // A pair object is shaped like this: // - // --------------------------------------------------------------------- - // | | <- a.minSize || b.minSize -> | | - // | | | <- this.snapOffset || this.snapOffset -> | | | - // | | | || | | | - // | | | || | | | - // --------------------------------------------------------------------- - // | <- this.start this.size -> | - function drag(e) { - var offset; - - if (!this.dragging) { - return; - } - - // Get the offset of the event from the first side of the - // pair `this.start`. Supports touch events, but not multitouch, so only the first - // finger `touches[0]` is counted. - if ('touches' in e) { - offset = e.touches[0][clientAxis] - this.start; - } else { - offset = e[clientAxis] - this.start; - } - - // If within snapOffset of min or max, set offset to min or max. - // snapOffset buffers a.minSize and b.minSize, so logic is opposite for both. - // Include the appropriate gutter sizes to prevent overflows. - if (offset <= elements[this.a].minSize + snapOffset + this.aGutterSize) { - offset = elements[this.a].minSize + this.aGutterSize; - } else if ( - offset >= - this.size - (elements[this.b].minSize + snapOffset + this.bGutterSize) - ) { - offset = this.size - (elements[this.b].minSize + this.bGutterSize); - } - - // Actually adjust the size. - adjust.call(this, offset); - - // Call the drag callback continously. Don't do anything too intensive - // in this callback. - if (options.onDrag) { - options.onDrag(); - } - } - - // Cache some important sizes when drag starts, so we don't have to do that - // continously: + // { + // a: DOM element, + // b: DOM element, + // aMin: Number, + // bMin: Number, + // dragging: Boolean, + // parent: DOM element, + // direction: 'horizontal' | 'vertical' + // } // - // `size`: The total size of the pair. First + second + first gutter + second gutter. - // `start`: The leading side of the first element. + // The basic sequence: // - // ------------------------------------------------ - // | aGutterSize -> ||| | - // | ||| | - // | ||| | - // | ||| <- bGutterSize | - // ------------------------------------------------ - // | <- start size -> | - function calculateSizes() { - // Figure out the parent size minus padding. - var a = elements[this.a].element; - var b = elements[this.b].element; - - this.size = - a[getBoundingClientRect]()[dimension] + - b[getBoundingClientRect]()[dimension] + - this.aGutterSize + - this.bGutterSize; - this.start = a[getBoundingClientRect]()[position]; - } - - // stopDragging is very similar to startDragging in reverse. - function stopDragging() { - var self = this; - var a = elements[self.a].element; - var b = elements[self.b].element; - - if (self.dragging && options.onDragEnd) { - options.onDragEnd(); - } - - self.dragging = false; - - // Remove the stored event listeners. This is why we store them. - global[removeEventListener]('mouseup', self.stop); - global[removeEventListener]('touchend', self.stop); - global[removeEventListener]('touchcancel', self.stop); - - self.parent[removeEventListener]('mousemove', self.move); - self.parent[removeEventListener]('touchmove', self.move); - - // Delete them once they are removed. I think this makes a difference - // in memory usage with a lot of splits on one page. But I don't know for sure. - delete self.stop; - delete self.move; - - a[removeEventListener]('selectstart', NOOP); - a[removeEventListener]('dragstart', NOOP); - b[removeEventListener]('selectstart', NOOP); - b[removeEventListener]('dragstart', NOOP); - - a.style.userSelect = ''; - a.style.webkitUserSelect = ''; - a.style.MozUserSelect = ''; - a.style.pointerEvents = ''; - - b.style.userSelect = ''; - b.style.webkitUserSelect = ''; - b.style.MozUserSelect = ''; - b.style.pointerEvents = ''; - - self.gutter.style.cursor = ''; - self.parent.style.cursor = ''; - } - - // startDragging calls `calculateSizes` to store the inital size in the pair object. - // It also adds event listeners for mouse/touch events, - // and prevents selection while dragging so avoid the selecting text. - function startDragging(e) { - // Alias frequently used variables to save space. 200 bytes. - var self = this; - var a = elements[self.a].element; - var b = elements[self.b].element; - - // Call the onDragStart callback. - if (!self.dragging && options.onDragStart) { - options.onDragStart(); - } - - // Don't actually drag the element. We emulate that in the drag function. - e.preventDefault(); - - // Set the dragging property of the pair object. - self.dragging = true; - - // Create two event listeners bound to the same pair object and store - // them in the pair object. - self.move = drag.bind(self); - self.stop = stopDragging.bind(self); - - // All the binding. `window` gets the stop events in case we drag out of the elements. - global[addEventListener]('mouseup', self.stop); - global[addEventListener]('touchend', self.stop); - global[addEventListener]('touchcancel', self.stop); - - self.parent[addEventListener]('mousemove', self.move); - self.parent[addEventListener]('touchmove', self.move); - - // Disable selection. Disable! - a[addEventListener]('selectstart', NOOP); - a[addEventListener]('dragstart', NOOP); - b[addEventListener]('selectstart', NOOP); - b[addEventListener]('dragstart', NOOP); - - a.style.userSelect = 'none'; - a.style.webkitUserSelect = 'none'; - a.style.MozUserSelect = 'none'; - a.style.pointerEvents = 'none'; - - b.style.userSelect = 'none'; - b.style.webkitUserSelect = 'none'; - b.style.MozUserSelect = 'none'; - b.style.pointerEvents = 'none'; - - // Set the cursor, both on the gutter and the parent element. - // Doing only a, b and gutter causes flickering. - self.gutter.style.cursor = cursor; - self.parent.style.cursor = cursor; - - // Cache the initial sizes of the pair. - calculateSizes.call(self); - } - - // 5. Create pair and element objects. Each pair has an index reference to - // elements `a` and `b` of the pair (first and second elements). - // Loop through the elements while pairing them off. Every pair gets a - // `pair` object, a gutter, and isFirst/isLast properties. - // - // Basic logic: - // - // - Starting with the second element `i > 0`, create `pair` objects with - // `a = i - 1` and `b = i` - // - Set gutter sizes based on the _pair_ being first/last. The first and last - // pair have gutterSize / 2, since they only have one half gutter, and not two. - // - Create gutter elements and add event listeners. - // - Set the size of the elements, minus the gutter sizes. - // - // ----------------------------------------------------------------------- - // | i=0 | i=1 | i=2 | i=3 | - // | | isFirst | | isLast | - // | pair 0 pair 1 pair 2 | - // | | | | | - // ----------------------------------------------------------------------- - var pairs = []; - elements = ids.map(function(id, i) { - // Create the element object. - var element = { - element: elementOrSelector(id), - size: sizes[i], - minSize: minSizes[i] - }; - - var pair; - - if (i > 0) { - // Create the pair object with it's metadata. - pair = { - a: i - 1, - b: i, - dragging: false, - isFirst: i === 1, - isLast: i === ids.length - 1, - direction: direction, - parent: parent - }; - - // For first and last pairs, first and last gutter width is half. - pair.aGutterSize = gutterSize; - pair.bGutterSize = gutterSize; - - if (pair.isFirst) { - pair.aGutterSize = gutterSize / 2; + // 1. Set defaults to something sane. `options` doesn't have to be passed at all. + // 2. Initialize a bunch of strings based on the direction we're splitting. + // A lot of the behavior in the rest of the library is paramatized down to + // rely on CSS strings and classes. + // 3. Define the dragging helper functions, and a few helpers to go with them. + // 4. Loop through the elements while pairing them off. Every pair gets an + // `pair` object and a gutter. + // 5. Actually size the pair elements, insert gutters and attach event listeners. + var Split = function (idsOption, options) { + if ( options === void 0 ) options = {}; + + var ids = idsOption; + var dimension; + var clientAxis; + var position; + var positionEnd; + var clientSize; + var elements; + + // Allow HTMLCollection to be used as an argument when supported + if (Array.from) { + ids = Array.from(ids); + } + + // All DOM elements in the split should have a common parent. We can grab + // the first elements parent and hope users read the docs because the + // behavior will be whacky otherwise. + var firstElement = elementOrSelector(ids[0]); + var parent = firstElement.parentNode; + var parentStyle = getComputedStyle ? getComputedStyle(parent) : null; + var parentFlexDirection = parentStyle ? parentStyle.flexDirection : null; + + // Set default options.sizes to equal percentages of the parent element. + var sizes = getOption(options, 'sizes') || ids.map(function () { return 100 / ids.length; }); + + // Standardize minSize to an array if it isn't already. This allows minSize + // to be passed as a number. + var minSize = getOption(options, 'minSize', 100); + var minSizes = Array.isArray(minSize) ? minSize : ids.map(function () { return minSize; }); + + // Get other options + var expandToMin = getOption(options, 'expandToMin', false); + var gutterSize = getOption(options, 'gutterSize', 10); + var gutterAlign = getOption(options, 'gutterAlign', 'center'); + var snapOffset = getOption(options, 'snapOffset', 30); + var dragInterval = getOption(options, 'dragInterval', 1); + var direction = getOption(options, 'direction', HORIZONTAL); + var cursor = getOption( + options, + 'cursor', + direction === HORIZONTAL ? 'col-resize' : 'row-resize' + ); + var gutter = getOption(options, 'gutter', defaultGutterFn); + var elementStyle = getOption( + options, + 'elementStyle', + defaultElementStyleFn + ); + var gutterStyle = getOption(options, 'gutterStyle', defaultGutterStyleFn); + + // 2. Initialize a bunch of strings based on the direction we're splitting. + // A lot of the behavior in the rest of the library is paramatized down to + // rely on CSS strings and classes. + if (direction === HORIZONTAL) { + dimension = 'width'; + clientAxis = 'clientX'; + position = 'left'; + positionEnd = 'right'; + clientSize = 'clientWidth'; + } else if (direction === 'vertical') { + dimension = 'height'; + clientAxis = 'clientY'; + position = 'top'; + positionEnd = 'bottom'; + clientSize = 'clientHeight'; + } + + // 3. Define the dragging helper functions, and a few helpers to go with them. + // Each helper is bound to a pair object that contains its metadata. This + // also makes it easy to store references to listeners that that will be + // added and removed. + // + // Even though there are no other functions contained in them, aliasing + // this to self saves 50 bytes or so since it's used so frequently. + // + // The pair object saves metadata like dragging state, position and + // event listener references. + + function setElementSize(el, size, gutSize, i) { + // Split.js allows setting sizes via numbers (ideally), or if you must, + // by string, like '300px'. This is less than ideal, because it breaks + // the fluid layout that `calc(% - px)` provides. You're on your own if you do that, + // make sure you calculate the gutter size by hand. + var style = elementStyle(dimension, size, gutSize, i); + + Object.keys(style).forEach(function (prop) { + // eslint-disable-next-line no-param-reassign + el.style[prop] = style[prop]; + }); + } + + function setGutterSize(gutterElement, gutSize, i) { + var style = gutterStyle(dimension, gutSize, i); + + Object.keys(style).forEach(function (prop) { + // eslint-disable-next-line no-param-reassign + gutterElement.style[prop] = style[prop]; + }); } - if (pair.isLast) { - pair.bGutterSize = gutterSize / 2; + function getSizes() { + return elements.map(function (element) { return element.size; }) } - // if the parent has a reverse flex-direction, switch the pair elements. - if ( - parentFlexDirection === 'row-reverse' || - parentFlexDirection === 'column-reverse' - ) { - var temp = pair.a; - pair.a = pair.b; - pair.b = temp; + // Supports touch events, but not multitouch, so only the first + // finger `touches[0]` is counted. + function getMousePosition(e) { + if ('touches' in e) { return e.touches[0][clientAxis] } + return e[clientAxis] } - } - - // Determine the size of the current element. IE8 is supported by - // staticly assigning sizes without draggable gutters. Assigns a string - // to `size`. - // - // IE9 and above - if (!isIE8) { - // Create gutter elements for each pair. - if (i > 0) { - var gutterElement = gutter(i, direction); - setGutterSize(gutterElement, gutterSize); - - gutterElement[addEventListener]( - 'mousedown', - startDragging.bind(pair) - ); - gutterElement[addEventListener]( - 'touchstart', - startDragging.bind(pair) - ); - - parent.insertBefore(gutterElement, element.element); - - pair.gutter = gutterElement; + + // Actually adjust the size of elements `a` and `b` to `offset` while dragging. + // calc is used to allow calc(percentage + gutterpx) on the whole split instance, + // which allows the viewport to be resized without additional logic. + // Element a's size is the same as offset. b's size is total size - a size. + // Both sizes are calculated from the initial parent percentage, + // then the gutter size is subtracted. + function adjust(offset) { + var a = elements[this.a]; + var b = elements[this.b]; + var percentage = a.size + b.size; + + a.size = (offset / this.size) * percentage; + b.size = percentage - (offset / this.size) * percentage; + + setElementSize(a.element, a.size, this[aGutterSize], a.i); + setElementSize(b.element, b.size, this[bGutterSize], b.i); + } + + // drag, where all the magic happens. The logic is really quite simple: + // + // 1. Ignore if the pair is not dragging. + // 2. Get the offset of the event. + // 3. Snap offset to min if within snappable range (within min + snapOffset). + // 4. Actually adjust each element in the pair to offset. + // + // --------------------------------------------------------------------- + // | | <- a.minSize || b.minSize -> | | + // | | | <- this.snapOffset || this.snapOffset -> | | | + // | | | || | | | + // | | | || | | | + // --------------------------------------------------------------------- + // | <- this.start this.size -> | + function drag(e) { + var offset; + var a = elements[this.a]; + var b = elements[this.b]; + + if (!this.dragging) { return } + + // Get the offset of the event from the first side of the + // pair `this.start`. Then offset by the initial position of the + // mouse compared to the gutter size. + offset = + getMousePosition(e) - + this.start + + (this[aGutterSize] - this.dragOffset); + + if (dragInterval > 1) { + offset = Math.round(offset / dragInterval) * dragInterval; + } + + // If within snapOffset of min or max, set offset to min or max. + // snapOffset buffers a.minSize and b.minSize, so logic is opposite for both. + // Include the appropriate gutter sizes to prevent overflows. + if (offset <= a.minSize + snapOffset + this[aGutterSize]) { + offset = a.minSize + this[aGutterSize]; + } else if ( + offset >= + this.size - (b.minSize + snapOffset + this[bGutterSize]) + ) { + offset = this.size - (b.minSize + this[bGutterSize]); + } + + // Actually adjust the size. + adjust.call(this, offset); + + // Call the drag callback continously. Don't do anything too intensive + // in this callback. + getOption(options, 'onDrag', NOOP)(); + } + + // Cache some important sizes when drag starts, so we don't have to do that + // continously: + // + // `size`: The total size of the pair. First + second + first gutter + second gutter. + // `start`: The leading side of the first element. + // + // ------------------------------------------------ + // | aGutterSize -> ||| | + // | ||| | + // | ||| | + // | ||| <- bGutterSize | + // ------------------------------------------------ + // | <- start size -> | + function calculateSizes() { + // Figure out the parent size minus padding. + var a = elements[this.a].element; + var b = elements[this.b].element; + + var aBounds = a[getBoundingClientRect](); + var bBounds = b[getBoundingClientRect](); + + this.size = + aBounds[dimension] + + bBounds[dimension] + + this[aGutterSize] + + this[bGutterSize]; + this.start = aBounds[position]; + this.end = aBounds[positionEnd]; + } + + function innerSize(element) { + // Return nothing if getComputedStyle is not supported (< IE9) + // Or if parent element has no layout yet + if (!getComputedStyle) { return null } + + var computedStyle = getComputedStyle(element); + + if (!computedStyle) { return null } + + var size = element[clientSize]; + + if (size === 0) { return null } + + if (direction === HORIZONTAL) { + size -= + parseFloat(computedStyle.paddingLeft) + + parseFloat(computedStyle.paddingRight); + } else { + size -= + parseFloat(computedStyle.paddingTop) + + parseFloat(computedStyle.paddingBottom); + } + + return size + } + + // When specifying percentage sizes that are less than the computed + // size of the element minus the gutter, the lesser percentages must be increased + // (and decreased from the other elements) to make space for the pixels + // subtracted by the gutters. + function trimToMin(sizesToTrim) { + // Try to get inner size of parent element. + // If it's no supported, return original sizes. + var parentSize = innerSize(parent); + if (parentSize === null) { + return sizesToTrim + } + + if (minSizes.reduce(function (a, b) { return a + b; }, 0) > parentSize) { + return sizesToTrim + } + + // Keep track of the excess pixels, the amount of pixels over the desired percentage + // Also keep track of the elements with pixels to spare, to decrease after if needed + var excessPixels = 0; + var toSpare = []; + + var pixelSizes = sizesToTrim.map(function (size, i) { + // Convert requested percentages to pixel sizes + var pixelSize = (parentSize * size) / 100; + var elementGutterSize = getGutterSize( + gutterSize, + i === 0, + i === sizesToTrim.length - 1, + gutterAlign + ); + var elementMinSize = minSizes[i] + elementGutterSize; + + // If element is too smal, increase excess pixels by the difference + // and mark that it has no pixels to spare + if (pixelSize < elementMinSize) { + excessPixels += elementMinSize - pixelSize; + toSpare.push(0); + return elementMinSize + } + + // Otherwise, mark the pixels it has to spare and return it's original size + toSpare.push(pixelSize - elementMinSize); + return pixelSize + }); + + // If nothing was adjusted, return the original sizes + if (excessPixels === 0) { + return sizesToTrim + } + + return pixelSizes.map(function (pixelSize, i) { + var newPixelSize = pixelSize; + + // While there's still pixels to take, and there's enough pixels to spare, + // take as many as possible up to the total excess pixels + if (excessPixels > 0 && toSpare[i] - excessPixels > 0) { + var takenPixels = Math.min( + excessPixels, + toSpare[i] - excessPixels + ); + + // Subtract the amount taken for the next iteration + excessPixels -= takenPixels; + newPixelSize = pixelSize - takenPixels; + } + + // Return the pixel size adjusted as a percentage + return (newPixelSize / parentSize) * 100 + }) + } + + // stopDragging is very similar to startDragging in reverse. + function stopDragging() { + var self = this; + var a = elements[self.a].element; + var b = elements[self.b].element; + + if (self.dragging) { + getOption(options, 'onDragEnd', NOOP)(getSizes()); + } + + self.dragging = false; + + // Remove the stored event listeners. This is why we store them. + global[removeEventListener]('mouseup', self.stop); + global[removeEventListener]('touchend', self.stop); + global[removeEventListener]('touchcancel', self.stop); + global[removeEventListener]('mousemove', self.move); + global[removeEventListener]('touchmove', self.move); + + // Clear bound function references + self.stop = null; + self.move = null; + + a[removeEventListener]('selectstart', NOOP); + a[removeEventListener]('dragstart', NOOP); + b[removeEventListener]('selectstart', NOOP); + b[removeEventListener]('dragstart', NOOP); + + a.style.userSelect = ''; + a.style.webkitUserSelect = ''; + a.style.MozUserSelect = ''; + a.style.pointerEvents = ''; + + b.style.userSelect = ''; + b.style.webkitUserSelect = ''; + b.style.MozUserSelect = ''; + b.style.pointerEvents = ''; + + self.gutter.style.cursor = ''; + self.parent.style.cursor = ''; + document.body.style.cursor = ''; } - } - - // Set the element size to our determined size. - // Half-size gutters for first and last elements. - if (i === 0 || i === ids.length - 1) { - setElementSize(element.element, element.size, gutterSize / 2); - } else { - setElementSize(element.element, element.size, gutterSize); - } - - var computedSize = element.element[getBoundingClientRect]()[dimension]; - - if (computedSize < element.minSize) { - element.minSize = computedSize; - } - - // After the first iteration, and we have a pair object, append it to the - // list of pairs. - if (i > 0) { - pairs.push(pair); - } - - return element; - }); - - function setSizes(newSizes) { - newSizes.forEach(function(newSize, i) { - if (i > 0) { - var pair = pairs[i - 1]; - var a = elements[pair.a]; - var b = elements[pair.b]; - - a.size = newSizes[i - 1]; - b.size = newSize; - - setElementSize(a.element, a.size, pair.aGutterSize); - setElementSize(b.element, b.size, pair.bGutterSize); + + // startDragging calls `calculateSizes` to store the inital size in the pair object. + // It also adds event listeners for mouse/touch events, + // and prevents selection while dragging so avoid the selecting text. + function startDragging(e) { + // Right-clicking can't start dragging. + if ('button' in e && e.button !== 0) { + return + } + + // Alias frequently used variables to save space. 200 bytes. + var self = this; + var a = elements[self.a].element; + var b = elements[self.b].element; + + // Call the onDragStart callback. + if (!self.dragging) { + getOption(options, 'onDragStart', NOOP)(getSizes()); + } + + // Don't actually drag the element. We emulate that in the drag function. + e.preventDefault(); + + // Set the dragging property of the pair object. + self.dragging = true; + + // Create two event listeners bound to the same pair object and store + // them in the pair object. + self.move = drag.bind(self); + self.stop = stopDragging.bind(self); + + // All the binding. `window` gets the stop events in case we drag out of the elements. + global[addEventListener]('mouseup', self.stop); + global[addEventListener]('touchend', self.stop); + global[addEventListener]('touchcancel', self.stop); + global[addEventListener]('mousemove', self.move); + global[addEventListener]('touchmove', self.move); + + // Disable selection. Disable! + a[addEventListener]('selectstart', NOOP); + a[addEventListener]('dragstart', NOOP); + b[addEventListener]('selectstart', NOOP); + b[addEventListener]('dragstart', NOOP); + + a.style.userSelect = 'none'; + a.style.webkitUserSelect = 'none'; + a.style.MozUserSelect = 'none'; + a.style.pointerEvents = 'none'; + + b.style.userSelect = 'none'; + b.style.webkitUserSelect = 'none'; + b.style.MozUserSelect = 'none'; + b.style.pointerEvents = 'none'; + + // Set the cursor at multiple levels + self.gutter.style.cursor = cursor; + self.parent.style.cursor = cursor; + document.body.style.cursor = cursor; + + // Cache the initial sizes of the pair. + calculateSizes.call(self); + + // Determine the position of the mouse compared to the gutter + self.dragOffset = getMousePosition(e) - self.end; } - }); - } - - function destroy() { - pairs.forEach(function(pair) { - pair.parent.removeChild(pair.gutter); - elements[pair.a].element.style[dimension] = ''; - elements[pair.b].element.style[dimension] = ''; - }); - } - - if (isIE8) { - return { - setSizes: setSizes, - destroy: destroy - }; - } - - return { - setSizes: setSizes, - getSizes: function getSizes() { - return elements.map(function(element) { - return element.size; + + // adjust sizes to ensure percentage is within min size and gutter. + sizes = trimToMin(sizes); + + // 5. Create pair and element objects. Each pair has an index reference to + // elements `a` and `b` of the pair (first and second elements). + // Loop through the elements while pairing them off. Every pair gets a + // `pair` object and a gutter. + // + // Basic logic: + // + // - Starting with the second element `i > 0`, create `pair` objects with + // `a = i - 1` and `b = i` + // - Set gutter sizes based on the _pair_ being first/last. The first and last + // pair have gutterSize / 2, since they only have one half gutter, and not two. + // - Create gutter elements and add event listeners. + // - Set the size of the elements, minus the gutter sizes. + // + // ----------------------------------------------------------------------- + // | i=0 | i=1 | i=2 | i=3 | + // | | | | | + // | pair 0 pair 1 pair 2 | + // | | | | | + // ----------------------------------------------------------------------- + var pairs = []; + elements = ids.map(function (id, i) { + // Create the element object. + var element = { + element: elementOrSelector(id), + size: sizes[i], + minSize: minSizes[i], + i: i, + }; + + var pair; + + if (i > 0) { + // Create the pair object with its metadata. + pair = { + a: i - 1, + b: i, + dragging: false, + direction: direction, + parent: parent, + }; + + pair[aGutterSize] = getGutterSize( + gutterSize, + i - 1 === 0, + false, + gutterAlign + ); + pair[bGutterSize] = getGutterSize( + gutterSize, + false, + i === ids.length - 1, + gutterAlign + ); + + // if the parent has a reverse flex-direction, switch the pair elements. + if ( + parentFlexDirection === 'row-reverse' || + parentFlexDirection === 'column-reverse' + ) { + var temp = pair.a; + pair.a = pair.b; + pair.b = temp; + } + } + + // Determine the size of the current element. IE8 is supported by + // staticly assigning sizes without draggable gutters. Assigns a string + // to `size`. + // + // IE9 and above + if (!isIE8) { + // Create gutter elements for each pair. + if (i > 0) { + var gutterElement = gutter(i, direction, element.element); + setGutterSize(gutterElement, gutterSize, i); + + // Save bound event listener for removal later + pair[gutterStartDragging] = startDragging.bind(pair); + + // Attach bound event listener + gutterElement[addEventListener]( + 'mousedown', + pair[gutterStartDragging] + ); + gutterElement[addEventListener]( + 'touchstart', + pair[gutterStartDragging] + ); + + parent.insertBefore(gutterElement, element.element); + + pair.gutter = gutterElement; + } + } + + setElementSize( + element.element, + element.size, + getGutterSize( + gutterSize, + i === 0, + i === ids.length - 1, + gutterAlign + ), + i + ); + + // After the first iteration, and we have a pair object, append it to the + // list of pairs. + if (i > 0) { + pairs.push(pair); + } + + return element }); - }, - collapse: function collapse(i) { - if (i === pairs.length) { - var pair = pairs[i - 1]; - calculateSizes.call(pair); + function adjustToMin(element) { + var isLast = element.i === pairs.length; + var pair = isLast ? pairs[element.i - 1] : pairs[element.i]; - if (!isIE8) { - adjust.call(pair, pair.size - pair.bGutterSize); - } - } else { - var pair$1 = pairs[i]; + calculateSizes.call(pair); - calculateSizes.call(pair$1); + var size = isLast + ? pair.size - element.minSize - pair[bGutterSize] + : element.minSize + pair[aGutterSize]; - if (!isIE8) { - adjust.call(pair$1, pair$1.aGutterSize); - } + adjust.call(pair, size); + } + + elements.forEach(function (element) { + var computedSize = element.element[getBoundingClientRect]()[dimension]; + + if (computedSize < element.minSize) { + if (expandToMin) { + adjustToMin(element); + } else { + // eslint-disable-next-line no-param-reassign + element.minSize = computedSize; + } + } + }); + + function setSizes(newSizes) { + var trimmed = trimToMin(newSizes); + trimmed.forEach(function (newSize, i) { + if (i > 0) { + var pair = pairs[i - 1]; + + var a = elements[pair.a]; + var b = elements[pair.b]; + + a.size = trimmed[i - 1]; + b.size = newSize; + + setElementSize(a.element, a.size, pair[aGutterSize], a.i); + setElementSize(b.element, b.size, pair[bGutterSize], b.i); + } + }); + } + + function destroy(preserveStyles, preserveGutter) { + pairs.forEach(function (pair) { + if (preserveGutter !== true) { + pair.parent.removeChild(pair.gutter); + } else { + pair.gutter[removeEventListener]( + 'mousedown', + pair[gutterStartDragging] + ); + pair.gutter[removeEventListener]( + 'touchstart', + pair[gutterStartDragging] + ); + } + + if (preserveStyles !== true) { + var style = elementStyle( + dimension, + pair.a.size, + pair[aGutterSize] + ); + + Object.keys(style).forEach(function (prop) { + elements[pair.a].element.style[prop] = ''; + elements[pair.b].element.style[prop] = ''; + }); + } + }); + } + + if (isIE8) { + return { + setSizes: setSizes, + destroy: destroy, + } + } + + return { + setSizes: setSizes, + getSizes: getSizes, + collapse: function collapse(i) { + adjustToMin(elements[i]); + }, + destroy: destroy, + parent: parent, + pairs: pairs, } - }, - destroy: destroy }; - }; - return Split; -}); + return Split; + +}))); diff --git a/docs/assets/style.css b/docs/assets/style.css index 5265ea1f..0618f437 100644 --- a/docs/assets/style.css +++ b/docs/assets/style.css @@ -26,7 +26,7 @@ h4 { } a { - color: #1184CE; + color: #1184ce; text-decoration: none; } @@ -51,12 +51,12 @@ a:hover { } section:target h3 { - font-weight:700; + font-weight: 700; } .documentation td, .documentation th { - padding: .25rem .25rem; + padding: 0.25rem 0.25rem; } h1:hover .anchorjs-link, @@ -82,13 +82,16 @@ h4:hover .anchorjs-link { } } -.pre, pre, code, .code { - font-family: Source Code Pro,Menlo,Consolas,Liberation Mono,monospace; +.pre, +pre, +code, +.code { + font-family: Source Code Pro, Menlo, Consolas, Liberation Mono, monospace; font-size: 14px; } .fill-light { - background: #F9F9F9; + background: #f9f9f9; } .width2 { @@ -100,10 +103,10 @@ h4:hover .anchorjs-link { display: block; width: 100%; height: 2rem; - padding: .5rem; + padding: 0.5rem; margin-bottom: 1rem; border: 1px solid #ccc; - font-size: .875rem; + font-size: 0.875rem; border-radius: 3px; box-sizing: border-box; } @@ -115,15 +118,19 @@ table { .prose table th, .prose table td { text-align: left; - padding:8px; - border:1px solid #ddd; + padding: 8px; + border: 1px solid #ddd; } -.prose table th:nth-child(1) { border-right: none; } -.prose table th:nth-child(2) { border-left: none; } +.prose table th:nth-child(1) { + border-right: none; +} +.prose table th:nth-child(2) { + border-left: none; +} .prose table { - border:1px solid #ddd; + border: 1px solid #ddd; } .prose-big { diff --git a/docs/index.html b/docs/index.html index 5be1c664..f2de69ae 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,14 +1,14 @@ - + opossum 3.0.0 | Documentation - - - - + + + +
@@ -45,16 +45,6 @@

opossum

-
  • - factory.metrics - - - -
  • - -
  • @@ -161,18 +151,6 @@

    opossum

    #stats
  • -
  • - #hystrixStats -
  • - -
  • - #metrics -
  • -
  • @@ -266,6 +244,16 @@

    opossum

  • +
  • + CircuitBreaker#shutdown + + + +
  • + +
  • @@ -409,40 +397,6 @@

    opossum

  • - -
  • - HystrixStats - - - - - -
  • -
    @@ -453,15 +407,14 @@

    opossum

    -
    -
    +
    -

    - README -

    +

    + README +

    - -

    opossum CircleCI

    + +

    opossum CircleCI

    Codacy Badge Codacy Badge Greenkeeper badge @@ -562,9 +515,9 @@

    Browser

    <html>
     <head>
       <title>My Super App</title>
    -  <script type='text/javascript' src="/jquery.js"></script>
    -  <script type='text/javascript' src="/opossum.js"></script>
    -  <script type='text/javascript' src="/app.js"></script>
    +  <script type='text/javascript' src="/jquery.js"></script>
    +  <script type='text/javascript' src="/opossum.js"></script>
    +  <script type='text/javascript' src="/app.js"></script>
     <body>
     ...
     </body>
    @@ -678,43 +631,13 @@ 

    Typings

    If you'd like to add them, run npm install @types/opossum in your project.

    Metrics

    Prometheus

    -

    Provide { usePrometheus: true } in the options when creating a circuit to produce -metrics that are consumable by Prometheus. These metrics include information about -the circuit itself, for example how many times it has opened, as well as general Node.js -statistics, for example event loop lag. To get consolidated metrics for all circuits in your -application, use the metrics() function on the factory.

    -
    const opossum = require('opossum');
    -
    -// create a circuit
    -const circuit = opossum(functionThatMightFail, { usePrometheus: true });
    -
    -// In an express app, expose the metrics to the Prometheus server
    -app.use('/metrics', (req, res) => {
    -  res.type('text/plain');
    -  res.send(opossum.metrics());
    -});
    -

    The prometheusRegistry option allows to provide a existing -prom-client registry. -The metrics about the circuit will be added to the provided registry instead -of the global registry. -The default metrics -will not be added to the provided registry.

    -
    const opossum = require('opossum');
    -const { Registry } = require('prom-client');
    -
    -// Create a registry
    -const prometheusRegistry = new Registry();
    -
    -// create a circuit
    -const circuit = opossum(functionThatMightFail, {
    -  usePrometheus: true,
    -  prometheusRegistry
    -});
    +

    The opossum-prometheus module +can be used to produce metrics that are consumable by Prometheus. +These metrics include information about the circuit itself, for example how many +times it has opened, as well as general Node.js statistics, for example event loop lag.

    Hystrix

    -

    NOTE: Hystrix metrics are deprecated

    -

    A Hystrix Stream is available for use with a Hystrix Dashboard using the circuitBreaker.hystrixStats.getHystrixStream method.

    -

    This method returns a Node.js Stream, which makes it easy to create an SSE stream that will be compliant with a Hystrix Dashboard.

    -

    Additional Reading: Hystrix Metrics Event Stream, Turbine, Hystrix Dashboard

    +

    The opossum-hystrix module can +be used to produce metrics that are consumable by the Hystrix Dashboard.

    Troubleshooting

    You may run into issues related to too many listeners on an EventEmitter like this.

    (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 10 unpipe listeners added. Use emitter.setMaxListeners() to increase limit
    @@ -722,14 +645,13 @@ 

    Troubleshooting

    (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added. Use emitter.setMaxListeners() to increase limit (node:25619) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit
    -

    This typically occurs when you have created more than ten CircuitBreaker instances. This is due to the fact that every circuit created is adding a listener to the stream accessed via circuit.stats.getHystrixStream(), and the default EventEmitter listener limit is 10. In some cases, seeing this error might indicate a bug in client code, where many CircuitBreakers are inadvertently being created. But there are legitimate scenarios where this may not be the case. For example, it could just be that you need more than 10 CircuitBreakers in your app. That's ok.

    +

    In some cases, seeing this error might indicate a bug in client code, where many CircuitBreakers are inadvertently being created. But there are legitimate scenarios where this may not be the case. For example, it could just be that you need more than 10 CircuitBreakers in your app. That's ok.

    To get around the error, you can set the number of listeners on the stream.

    circuit.stats.getHystrixStream().setMaxListeners(100);

    Or it could be that you have a large test suite which exercises some code that creates CircuitBreakers and does so repeatedly. If the CircuitBreaker being created is only needed for the duration of the test, use circuit.shutdown() when the circuit is no longer in use to clean up all listeners.

    - -
    -
    + +
    @@ -989,63 +911,6 @@

    - - - - - -
    - - -
    - -

    - factory.metrics -

    - - -
    - - -

    Get the Prometheus metrics for all circuits.

    - -
    factory.metrics(): String
    - - - - - - - - - - - - - - - - -
    Returns
    - String: - the metrics for all circuits or -undefined if no circuits have been created - - - - - - - - - - - - - - - -
    @@ -1334,7 +1199,7 @@

    an optional function that will be called when the circuit's function fails (returns a rejected Promise). If -this function returns truthy, the circuit's failure statistics will not be +this function returns truthy, the circuit's failPure statistics will not be incremented. This is useful, for example, when you don't want HTTP 404 to trip the circuit, but still want to handle it as a failure case. @@ -2052,110 +1917,6 @@

    - - - - - - - - - -

    -
    - -
    -
    -
    - - hystrixStats -
    -
    - -
    - -
    -
    -
    - - metrics -
    -
    -