query_hints.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 monotonic = datapoints.filter(dp => dp[0] !== null).every((dp, index) => {
  31. if (index === 0) {
  32. return true;
  33. }
  34. increasing = increasing || dp[0] > datapoints[index - 1][0];
  35. // monotonic?
  36. return dp[0] >= datapoints[index - 1][0];
  37. });
  38. if (increasing && monotonic) {
  39. const simpleMetric = query.trim().match(/^\w+$/);
  40. let label = 'Time series is monotonously increasing.';
  41. let fix;
  42. if (simpleMetric) {
  43. fix = {
  44. label: 'Fix by adding rate().',
  45. action: {
  46. type: 'ADD_RATE',
  47. query,
  48. index,
  49. },
  50. };
  51. } else {
  52. label = `${label} Try applying a rate() function.`;
  53. }
  54. return {
  55. label,
  56. index,
  57. fix,
  58. };
  59. }
  60. }
  61. // Check for recording rules expansion
  62. if (datasource && datasource.ruleMappings) {
  63. const mapping = datasource.ruleMappings;
  64. const mappingForQuery = Object.keys(mapping).reduce((acc, ruleName) => {
  65. if (query.search(ruleName) > -1) {
  66. return {
  67. ...acc,
  68. [ruleName]: mapping[ruleName],
  69. };
  70. }
  71. return acc;
  72. }, {});
  73. if (_.size(mappingForQuery) > 0) {
  74. const label = 'Query contains recording rules.';
  75. return {
  76. label,
  77. index,
  78. fix: {
  79. label: 'Expand rules',
  80. action: {
  81. type: 'EXPAND_RULES',
  82. query,
  83. index,
  84. mapping: mappingForQuery,
  85. },
  86. },
  87. };
  88. }
  89. }
  90. // No hint found
  91. return null;
  92. });
  93. return hints;
  94. }