open-nomad/ui/app/utils/classes/abstract-stats-tracker.js

84 lines
2.3 KiB
JavaScript
Raw Normal View History

import Ember from 'ember';
import Mixin from '@ember/object/mixin';
import { assert } from '@ember/debug';
import { task, timeout } from 'ember-concurrency';
import jsonWithDefault from 'nomad-ui/utils/json-with-default';
// eslint-disable-next-line ember/no-new-mixins
export default Mixin.create({
url: '',
// The max number of data points tracked. Once the max is reached,
// data points at the head of the list are removed in favor of new
// data appended at the tail
bufferSize: 500,
// The number of consecutive request failures that can occur before an
// empty frame is appended
maxFrameMisses: 5,
fetch() {
2018-08-31 02:57:28 +00:00
assert('StatsTrackers need a fetch method, which should have an interface like window.fetch');
},
append(/* frame */) {
assert(
2018-08-31 02:57:28 +00:00
'StatsTrackers need an append method, which takes the JSON response from a request to url as an argument'
);
},
pause() {
assert(
'StatsTrackers need a pause method, which takes no arguments but adds a frame of data at the current timestamp with null as the value'
);
},
frameMisses: 0,
handleResponse(frame) {
if (frame.error) {
this.incrementProperty('frameMisses');
2019-03-26 07:46:44 +00:00
if (this.frameMisses >= this.maxFrameMisses) {
// Missing enough data consecutively is effectively a pause
this.pause();
this.set('frameMisses', 0);
}
return;
} else {
this.set('frameMisses', 0);
// Only append non-error frames
this.append(frame);
}
},
// Uses EC as a form of debounce to prevent multiple
// references to the same tracker from flooding the tracker,
// but also avoiding the issue where different places where the
// same tracker is used needs to coordinate.
poll: task(function*() {
// Interrupt any pause attempt
2019-03-26 07:46:44 +00:00
this.signalPause.cancelAll();
2018-09-20 02:30:18 +00:00
try {
2019-03-26 07:46:44 +00:00
const url = this.url;
2018-09-20 02:30:18 +00:00
assert('Url must be defined', url);
2019-03-26 07:46:44 +00:00
yield this.fetch(url)
.then(jsonWithDefault({ error: true }))
.then(frame => this.handleResponse(frame));
2018-09-20 02:30:18 +00:00
} catch (error) {
throw new Error(error);
}
yield timeout(Ember.testing ? 0 : 2000);
}).drop(),
signalPause: task(function*() {
// wait 2 seconds
yield timeout(Ember.testing ? 0 : 2000);
// if no poll called in 2 seconds, pause
this.pause();
}).drop(),
});