timeRange.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { RelativeTimeRange } from '@grafana/data';
  2. import { AlertQuery } from 'app/types/unified-alerting-dto';
  3. import { ExpressionQuery, ExpressionQueryType } from '../../../expressions/types';
  4. const FALL_BACK_TIME_RANGE = { from: 21600, to: 0 };
  5. export const getTimeRangeForExpression = (query: ExpressionQuery, queries: AlertQuery[]): RelativeTimeRange => {
  6. const referencedRefIds: string[] | undefined = getReferencedIds(query, queries);
  7. if (!referencedRefIds) {
  8. return FALL_BACK_TIME_RANGE;
  9. }
  10. const { from, to } = getTimeRanges(referencedRefIds, queries);
  11. if (!from.length && !to.length) {
  12. return FALL_BACK_TIME_RANGE;
  13. }
  14. return {
  15. from: Math.max(...from),
  16. to: Math.min(...to),
  17. };
  18. };
  19. const getReferencedIds = (model: ExpressionQuery, queries: AlertQuery[]): string[] | undefined => {
  20. switch (model.type) {
  21. case ExpressionQueryType.classic:
  22. return getReferencedIdsForClassicCondition(model);
  23. case ExpressionQueryType.math:
  24. return getReferencedIdsForMath(model, queries);
  25. case ExpressionQueryType.resample:
  26. case ExpressionQueryType.reduce:
  27. return getReferencedIdsForReduce(model);
  28. }
  29. };
  30. const getReferencedIdsForClassicCondition = (model: ExpressionQuery) => {
  31. return model.conditions?.map((condition) => {
  32. return condition.query.params[0];
  33. });
  34. };
  35. const getTimeRanges = (referencedRefIds: string[], queries: AlertQuery[]) => {
  36. let from: number[] = [];
  37. let to = [FALL_BACK_TIME_RANGE.to];
  38. for (const referencedRefIdsKey of referencedRefIds) {
  39. const query = queries.find((query) => query.refId === referencedRefIdsKey);
  40. if (!query || !query.relativeTimeRange) {
  41. continue;
  42. }
  43. from.push(query.relativeTimeRange.from);
  44. to.push(query.relativeTimeRange.to);
  45. }
  46. return {
  47. from,
  48. to,
  49. };
  50. };
  51. const getReferencedIdsForMath = (model: ExpressionQuery, queries: AlertQuery[]) => {
  52. return (
  53. queries
  54. // filter queries of type query and filter expression on if it includes any refIds
  55. .filter((q) => q.queryType === 'query' && model.expression?.includes(q.refId))
  56. .map((q) => {
  57. return q.refId;
  58. })
  59. );
  60. };
  61. const getReferencedIdsForReduce = (model: ExpressionQuery) => {
  62. return model.expression ? [model.expression] : undefined;
  63. };