language_utils.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { TimeRange } from '@grafana/data';
  2. function roundMsToMin(milliseconds: number): number {
  3. return roundSecToMin(milliseconds / 1000);
  4. }
  5. function roundSecToMin(seconds: number): number {
  6. return Math.floor(seconds / 60);
  7. }
  8. export function shouldRefreshLabels(range?: TimeRange, prevRange?: TimeRange): boolean {
  9. if (range && prevRange) {
  10. const sameMinuteFrom = roundMsToMin(range.from.valueOf()) === roundMsToMin(prevRange.from.valueOf());
  11. const sameMinuteTo = roundMsToMin(range.to.valueOf()) === roundMsToMin(prevRange.to.valueOf());
  12. // If both are same, don't need to refresh
  13. return !(sameMinuteFrom && sameMinuteTo);
  14. }
  15. return false;
  16. }
  17. // Loki regular-expressions use the RE2 syntax (https://github.com/google/re2/wiki/Syntax),
  18. // so every character that matches something in that list has to be escaped.
  19. // the list of meta characters is: *+?()|\.[]{}^$
  20. // we make a javascript regular expression that matches those characters:
  21. const RE2_METACHARACTERS = /[*+?()|\\.\[\]{}^$]/g;
  22. function escapeLokiRegexp(value: string): string {
  23. return value.replace(RE2_METACHARACTERS, '\\$&');
  24. }
  25. // based on the openmetrics-documentation, the 3 symbols we have to handle are:
  26. // - \n ... the newline character
  27. // - \ ... the backslash character
  28. // - " ... the double-quote character
  29. export function escapeLabelValueInExactSelector(labelValue: string): string {
  30. return labelValue.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"');
  31. }
  32. export function escapeLabelValueInRegexSelector(labelValue: string): string {
  33. return escapeLabelValueInExactSelector(escapeLokiRegexp(labelValue));
  34. }
  35. export function escapeLabelValueInSelector(labelValue: string, selector?: string): string {
  36. return isRegexSelector(selector)
  37. ? escapeLabelValueInRegexSelector(labelValue)
  38. : escapeLabelValueInExactSelector(labelValue);
  39. }
  40. export function isRegexSelector(selector?: string) {
  41. if (selector && (selector.includes('=~') || selector.includes('!~'))) {
  42. return true;
  43. }
  44. return false;
  45. }