Commit 75e14aa1 by Zoltán Bedi Committed by GitHub

Chore: Let kbn util infer types (#26907)

* Chore: Let kbn util infer types

Type fixes where needed

* Address review comments + test fix

* Modify kbn method and property names to pascalCase
parent 6b1b52b7
......@@ -43,7 +43,7 @@ export interface QueryResultMeta {
* Legacy data source specific, should be moved to custom
* */
gmdMeta?: any[]; // used by cloudwatch
alignmentPeriod?: string; // used by cloud monitoring
alignmentPeriod?: number; // used by cloud monitoring
searchWords?: string[]; // used by log models and loki
limit?: number; // used by log models and loki
json?: boolean; // used to keep track of old json doc values
......
......@@ -32,7 +32,7 @@ export interface ValueFormatCategory {
formats: ValueFormat[];
}
interface ValueFormatterIndex {
export interface ValueFormatterIndex {
[id: string]: ValueFormatter;
}
......
......@@ -14,7 +14,7 @@ function tip($compile: any) {
'<i class="grafana-tip fa fa-' +
(attrs.icon || 'question-circle') +
'" bs-tooltip="\'' +
kbn.addslashes(elem.text()) +
kbn.addSlashes(elem.text()) +
'\'"></i>';
_t = _t.replace(/{/g, '\\{').replace(/}/g, '\\}');
elem.replaceWith($compile(angular.element(_t))(scope));
......
......@@ -61,7 +61,7 @@ export class ContextSrv {
if (!config.minRefreshInterval) {
return true;
}
return kbn.interval_to_ms(interval) >= kbn.interval_to_ms(config.minRefreshInterval);
return kbn.intervalToMs(interval) >= kbn.intervalToMs(config.minRefreshInterval);
}
getValidInterval(interval: string) {
......
......@@ -53,7 +53,7 @@ describe('Chcek KBN value formats', () => {
describe('describe_interval', () => {
it('falls back to seconds if input is a number', () => {
expect(kbn.describe_interval('123')).toEqual({
expect(kbn.describeInterval('123')).toEqual({
sec: 1,
type: 's',
count: 123,
......@@ -61,7 +61,7 @@ describe('describe_interval', () => {
});
it('parses a valid time unt string correctly', () => {
expect(kbn.describe_interval('123h')).toEqual({
expect(kbn.describeInterval('123h')).toEqual({
sec: 3600,
type: 'h',
count: 123,
......@@ -69,7 +69,7 @@ describe('describe_interval', () => {
});
it('fails if input is invalid', () => {
expect(() => kbn.describe_interval('123xyz')).toThrow();
expect(() => kbn.describe_interval('xyz')).toThrow();
expect(() => kbn.describeInterval('123xyz')).toThrow();
expect(() => kbn.describeInterval('xyz')).toThrow();
});
});
......@@ -253,7 +253,7 @@ export class AlertTabCtrl {
this.frequencyWarning = '';
try {
const frequencySecs = kbn.interval_to_seconds(this.alert.frequency);
const frequencySecs = kbn.intervalToSeconds(this.alert.frequency);
if (frequencySecs < this.alertingMinIntervalSecs) {
this.frequencyWarning =
'A minimum evaluation interval of ' +
......
......@@ -37,7 +37,7 @@ const timeRangeValidationEvents: ValidationEvents = {
return true;
}
try {
kbn.interval_to_seconds(value);
kbn.intervalToSeconds(value);
return true;
} catch {
return false;
......@@ -125,7 +125,7 @@ export class ApiKeysPage extends PureComponent<Props, any> {
// make sure that secondsToLive is number or null
const secondsToLive = this.state.newApiKey['secondsToLive'];
this.state.newApiKey['secondsToLive'] = secondsToLive ? kbn.interval_to_seconds(secondsToLive) : null;
this.state.newApiKey['secondsToLive'] = secondsToLive ? kbn.intervalToSeconds(secondsToLive) : null;
this.props.addApiKey(this.state.newApiKey, openModal, this.props.includeExpired);
this.setState((prevState: State) => {
return {
......
......@@ -39,7 +39,7 @@ export class TimePickerSettings extends PureComponent<Props, State> {
if (config.minRefreshInterval) {
intervals = intervals.filter(rate => {
return kbn.interval_to_ms(rate) >= kbn.interval_to_ms(config.minRefreshInterval);
return kbn.intervalToMs(rate) >= kbn.intervalToMs(config.minRefreshInterval);
});
}
......
......@@ -115,7 +115,7 @@ export class TimeSrv {
// when time window specified in ms
timeWindowMs = parseInt(timeWindow, 10);
} else {
timeWindowMs = kbn.interval_to_ms(timeWindow);
timeWindowMs = kbn.intervalToMs(timeWindow);
}
return {
......@@ -181,7 +181,7 @@ export class TimeSrv {
if (interval) {
const validInterval = this.contextSrv.getValidInterval(interval);
const intervalMs = kbn.interval_to_ms(validInterval);
const intervalMs = kbn.intervalToMs(validInterval);
this.refreshTimer = this.timer.register(
this.$timeout(() => {
......
......@@ -97,7 +97,7 @@ export class PlaylistSrv {
.get(`/api/playlists/${playlistId}/dashboards`)
.then((dashboards: any) => {
this.dashboards = dashboards;
this.interval = kbn.interval_to_ms(playlist.interval);
this.interval = kbn.intervalToMs(playlist.interval);
this.next();
});
});
......
......@@ -81,7 +81,7 @@ describe('interval actions', () => {
expect(appEventMock.emit).toHaveBeenCalledWith(AppEvents.alertError, [
'Templating',
`Invalid interval string, has to be either unit-less or end with one of the following units: "${Object.keys(
kbn.intervals_in_seconds
kbn.intervalsInSeconds
).join(', ')}"`,
]);
setTimeSrv(originalTimeSrv);
......@@ -99,7 +99,7 @@ describe('interval actions', () => {
const dependencies: UpdateAutoValueDependencies = {
kbn: {
calculateInterval: jest.fn(),
},
} as any,
getTimeSrv: () => {
return ({
timeRange: jest.fn().mockReturnValue({
......@@ -152,7 +152,7 @@ describe('interval actions', () => {
const dependencies: UpdateAutoValueDependencies = {
kbn: {
calculateInterval: jest.fn().mockReturnValue({ interval: '10s' }),
},
} as any,
getTimeSrv: () => {
return ({
timeRange: timeRangeMock,
......
......@@ -13,7 +13,7 @@ export interface Props {
templateVariableOptions: Array<SelectableValue<string>>;
alignmentPeriod: string;
perSeriesAligner: string;
usedAlignmentPeriod: string;
usedAlignmentPeriod?: number;
}
export const AlignmentPeriods: FC<Props> = ({
......@@ -25,7 +25,9 @@ export const AlignmentPeriods: FC<Props> = ({
usedAlignmentPeriod,
}) => {
const alignment = alignOptions.find(ap => ap.value === templateSrv.replace(perSeriesAligner));
const formatAlignmentText = `${kbn.secondsToHms(usedAlignmentPeriod)} interval (${alignment ? alignment.text : ''})`;
const formatAlignmentText = usedAlignmentPeriod
? `${kbn.secondsToHms(usedAlignmentPeriod)} interval (${alignment ? alignment.text : ''})`
: '';
const options = alignmentPeriods.map(ap => ({
...ap,
label: ap.text,
......
......@@ -7,7 +7,7 @@ import { SelectableValue } from '@grafana/data';
export interface Props {
refId: string;
usedAlignmentPeriod: string;
usedAlignmentPeriod?: number;
variableOptionGroup: SelectableValue<string>;
onChange: (query: MetricQuery) => void;
onRunQuery: () => void;
......
......@@ -67,7 +67,7 @@ export class QueryEditor extends PureComponent<Props, State> {
const sloQuery = { ...defaultSLOQuery, ...query.sloQuery, projectName: datasource.getDefaultProject() };
const queryType = query.queryType || QueryType.METRICS;
const meta = this.props.data?.series.length ? this.props.data?.series[0].meta : {};
const usedAlignmentPeriod = meta?.alignmentPeriod as string;
const usedAlignmentPeriod = meta?.alignmentPeriod;
const variableOptionGroup = {
label: 'Template Variables',
expanded: false,
......
......@@ -7,7 +7,7 @@ import { SLOQuery } from '../types';
import CloudMonitoringDatasource from '../datasource';
export interface Props {
usedAlignmentPeriod: string;
usedAlignmentPeriod?: number;
variableOptionGroup: SelectableValue<string>;
onChange: (query: SLOQuery) => void;
onRunQuery: () => void;
......
......@@ -419,7 +419,7 @@ export class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery, CloudWa
if (/^\d+$/.test(period)) {
period = parseInt(period, 10);
} else {
period = kbn.interval_to_seconds(period);
period = kbn.intervalToSeconds(period);
}
if (period < 1) {
......
......@@ -490,7 +490,7 @@ export class AzureMonitorQueryCtrl extends QueryCtrl {
const allowedTimeGrainsMs: number[] = [];
timeGrains.forEach((tg: any) => {
if (tg.value !== 'auto') {
allowedTimeGrainsMs.push(kbn.interval_to_ms(TimegrainConverter.createKbnUnitFromISO8601Duration(tg.value)));
allowedTimeGrainsMs.push(kbn.intervalToMs(TimegrainConverter.createKbnUnitFromISO8601Duration(tg.value)));
}
});
return allowedTimeGrainsMs;
......
......@@ -36,11 +36,11 @@ export default class TimeGrainConverter {
const timeGrains = _.filter(allowedTimeGrains, o => o !== 'auto');
let closest = timeGrains[0];
const intervalMs = kbn.interval_to_ms(interval);
const intervalMs = kbn.intervalToMs(interval);
for (let i = 0; i < timeGrains.length; i++) {
// abs (num - val) < abs (num - curr):
if (intervalMs > kbn.interval_to_ms(timeGrains[i])) {
if (intervalMs > kbn.intervalToMs(timeGrains[i])) {
if (i + 1 < timeGrains.length) {
closest = timeGrains[i + 1];
} else {
......
......@@ -22,11 +22,10 @@ export class MetricTankMetaInspector extends PureComponent<Props, State> {
const runtimeNotice = getRuntimeConsolidationNotice([meta]);
const normFunc = (meta['consolidator-normfetch'] ?? '').replace('Consolidator', '');
let totalSeconds = 0;
for (const bucket of buckets) {
totalSeconds += kbn.interval_to_seconds(bucket.retention);
}
const totalSeconds = buckets.reduce(
(acc, bucket) => acc + (bucket.retention ? kbn.intervalToSeconds(bucket.retention) : 0),
0
);
return (
<div className={styles.metaItem} key={key}>
......@@ -46,7 +45,7 @@ export class MetricTankMetaInspector extends PureComponent<Props, State> {
<div>
{buckets.map((bucket, index) => {
const bucketLength = kbn.interval_to_seconds(bucket.retention);
const bucketLength = bucket.retention ? kbn.intervalToSeconds(bucket.retention) : 0;
const lengthPercent = (bucketLength / totalSeconds) * 100;
const isActive = index === meta['archive-read'];
......
......@@ -205,7 +205,7 @@ export class OpenTsQueryCtrl extends QueryCtrl {
if (this.target.shouldDownsample) {
try {
if (this.target.downsampleInterval) {
kbn.describe_interval(this.target.downsampleInterval);
kbn.describeInterval(this.target.downsampleInterval);
} else {
errs.downsampleInterval = "You must supply a downsample interval (e.g. '1m' or '1h').";
}
......
......@@ -327,9 +327,9 @@ export class PrometheusDatasource extends DataSourceApi<PromQuery, PromOptions>
const range = Math.ceil(end - start);
// options.interval is the dynamically calculated interval
let interval: number = kbn.interval_to_seconds(options.interval);
let interval: number = kbn.intervalToSeconds(options.interval);
// Minimum interval ("Min step"), if specified for the query or datasource. or same as interval otherwise
const minInterval = kbn.interval_to_seconds(
const minInterval = kbn.intervalToSeconds(
templateSrv.replace(target.interval || options.interval, options.scopedVars)
);
const intervalFactor = target.intervalFactor || 1;
......@@ -495,7 +495,7 @@ export class PrometheusDatasource extends DataSourceApi<PromQuery, PromOptions>
const scopedVars = {
__interval: { text: this.interval, value: this.interval },
__interval_ms: { text: kbn.interval_to_ms(this.interval), value: kbn.interval_to_ms(this.interval) },
__interval_ms: { text: kbn.intervalToMs(this.interval), value: kbn.intervalToMs(this.interval) },
...this.getRangeScopedVars(getTimeSrv().timeRange()),
};
const interpolated = templateSrv.replace(query, scopedVars, this.interpolateQueryExpr);
......
......@@ -180,9 +180,9 @@ export class HeatmapCtrl extends MetricsPanelCtrl {
const xBucketSizeByNumber = Math.floor((this.range.to.valueOf() - this.range.from.valueOf()) / xBucketNumber);
// Parse X bucket size (number or interval)
const isIntervalString = kbn.interval_regex.test(this.panel.xBucketSize);
const isIntervalString = kbn.intervalRegex.test(this.panel.xBucketSize);
if (isIntervalString) {
xBucketSize = kbn.interval_to_ms(this.panel.xBucketSize);
xBucketSize = kbn.intervalToMs(this.panel.xBucketSize);
} else if (
isNaN(Number(this.panel.xBucketSize)) ||
this.panel.xBucketSize === '' ||
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment