query_hints.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import _ from 'lodash';
  2. export function getQueryHints(series: any[], datasource?: any): any[] {
  3. const hints = series.map((s, i) => {
  4. const query: string = s.query;
  5. const index: number = s.responseIndex;
  6. if (query === undefined || index === undefined) {
  7. return null;
  8. }
  9. // ..._bucket metric needs a histogram_quantile()
  10. const histogramMetric = query.trim().match(/^\w+_bucket$/);
  11. if (histogramMetric) {
  12. const label = 'Time series has buckets, you probably wanted a histogram.';
  13. return {
  14. index,
  15. label,
  16. fix: {
  17. label: 'Fix by adding histogram_quantile().',
  18. action: {
  19. type: 'ADD_HISTOGRAM_QUANTILE',
  20. query,
  21. index,
  22. },
  23. },
  24. };
  25. }
  26. // Check for monotony
  27. const datapoints: number[][] = s.datapoints;
  28. if (query.indexOf('rate(') === -1 && datapoints.length > 1) {
  29. let increasing = false;
  30. const nonNullData = datapoints.filter(dp => dp[0] !== null);
  31. const monotonic = nonNullData.every((dp, index) => {
  32. if (index === 0) {
  33. return true;
  34. }
  35. increasing = increasing || dp[0] > nonNullData[index - 1][0];
  36. // monotonic?
  37. return dp[0] >= nonNullData[index - 1][0];
  38. });
  39. if (increasing && monotonic) {
  40. const simpleMetric = query.trim().match(/^\w+$/);
  41. let label = 'Time series is monotonously increasing.';
  42. let fix;
  43. if (simpleMetric) {
  44. fix = {
  45. label: 'Fix by adding rate().',
  46. action: {
  47. type: 'ADD_RATE',
  48. query,
  49. index,
  50. },
  51. };
  52. } else {
  53. label = `${label} Try applying a rate() function.`;
  54. }
  55. return {
  56. label,
  57. index,
  58. fix,
  59. };
  60. }
  61. }
  62. // Check for recording rules expansion
  63. if (datasource && datasource.ruleMappings) {
  64. const mapping = datasource.ruleMappings;
  65. const mappingForQuery = Object.keys(mapping).reduce((acc, ruleName) => {
  66. if (query.search(ruleName) > -1) {
  67. return {
  68. ...acc,
  69. [ruleName]: mapping[ruleName],
  70. };
  71. }
  72. return acc;
  73. }, {});
  74. if (_.size(mappingForQuery) > 0) {
  75. const label = 'Query contains recording rules.';
  76. return {
  77. label,
  78. index,
  79. fix: {
  80. label: 'Expand rules',
  81. action: {
  82. type: 'EXPAND_RULES',
  83. query,
  84. index,
  85. mapping: mappingForQuery,
  86. },
  87. },
  88. };
  89. }
  90. }
  91. // No hint found
  92. return null;
  93. });
  94. return hints;
  95. }