Alerting: Fix invalid duration that causes Grafana to crash (#63753)

* Alerting: fix invalid alert duration

* Return empty string from intervalToAbbreviatedDurationString

* Alerting: add tests for invalid duration

* tests intervalToAbbreviatedDurationString

* Alerting: add missing isAfter import 

* durationutils.ts
pull/64067/head
Fábio Silva 2 years ago committed by GitHub
parent 9160f608b4
commit afc9925dbf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      packages/grafana-data/src/datetime/durationutil.test.ts
  2. 8
      packages/grafana-data/src/datetime/durationutil.ts

@ -13,6 +13,12 @@ describe('Duration util', () => {
const endDate = addDurationToDate(startDate, { months: 1, weeks: 1, days: 1, hours: 1, minutes: 1, seconds: 1 });
expect(intervalToAbbreviatedDurationString({ start: startDate, end: endDate })).toEqual('1M 8d 1h 1m 1s');
});
it('should return an empty string if start date is after end date', () => {
const endDate = new Date();
const startDate = addDurationToDate(endDate, { minutes: 1 });
expect(intervalToAbbreviatedDurationString({ start: startDate, end: endDate })).toEqual('');
});
});
describe('parseDuration', () => {

@ -1,4 +1,4 @@
import { Duration, Interval } from 'date-fns';
import { Duration, Interval, isAfter } from 'date-fns';
import add from 'date-fns/add';
import intervalToDuration from 'date-fns/intervalToDuration';
@ -21,6 +21,12 @@ const durationMap: { [key in Required<keyof Duration>]: string[] } = {
* @public
*/
export function intervalToAbbreviatedDurationString(interval: Interval, includeSeconds = true): string {
// An edge case that causes the app to crash (e.g. browser's clock behind the rule/alert date)
// The code will again return a proper duration when the browser's clock >= rule/alert date
if (isAfter(interval.start, interval.end)) {
return '';
}
const duration = intervalToDuration(interval);
return (Object.entries(duration) as Array<[keyof Duration, number | undefined]>).reduce((str, [unit, value]) => {
if (value && value !== 0 && !(unit === 'seconds' && !includeSeconds && str)) {

Loading…
Cancel
Save