@perses-dev/prometheus-plugin 0.49.0 → 0.50.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/cjs/components/PromQLEditor.js +72 -99
  2. package/dist/cjs/components/parse.js +2 -2
  3. package/dist/cjs/plugins/prometheus-datasource.js +3 -3
  4. package/dist/cjs/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.js +1 -1
  5. package/dist/cjs/plugins/prometheus-time-series-query/get-time-series-data.js +4 -9
  6. package/dist/cjs/plugins/prometheus-time-series-query/replace-prom-builtin-variables.js +33 -0
  7. package/dist/components/PromQLEditor.d.ts +2 -1
  8. package/dist/components/PromQLEditor.d.ts.map +1 -1
  9. package/dist/components/PromQLEditor.js +72 -99
  10. package/dist/components/PromQLEditor.js.map +1 -1
  11. package/dist/components/parse.d.ts +2 -1
  12. package/dist/components/parse.d.ts.map +1 -1
  13. package/dist/components/parse.js +2 -2
  14. package/dist/components/parse.js.map +1 -1
  15. package/dist/components/promql/utils.d.ts.map +1 -1
  16. package/dist/components/promql/utils.js.map +1 -1
  17. package/dist/model/prometheus-client.d.ts +4 -12
  18. package/dist/model/prometheus-client.d.ts.map +1 -1
  19. package/dist/model/prometheus-client.js.map +1 -1
  20. package/dist/model/prometheus-selectors.d.ts.map +1 -1
  21. package/dist/model/prometheus-selectors.js.map +1 -1
  22. package/dist/model/time.d.ts.map +1 -1
  23. package/dist/model/time.js.map +1 -1
  24. package/dist/plugins/MatcherEditor.d.ts +2 -1
  25. package/dist/plugins/MatcherEditor.d.ts.map +1 -1
  26. package/dist/plugins/MatcherEditor.js.map +1 -1
  27. package/dist/plugins/PrometheusDatasourceEditor.d.ts +2 -1
  28. package/dist/plugins/PrometheusDatasourceEditor.d.ts.map +1 -1
  29. package/dist/plugins/PrometheusDatasourceEditor.js.map +1 -1
  30. package/dist/plugins/prometheus-datasource.d.ts.map +1 -1
  31. package/dist/plugins/prometheus-datasource.js +3 -3
  32. package/dist/plugins/prometheus-datasource.js.map +1 -1
  33. package/dist/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.d.ts +2 -1
  34. package/dist/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.d.ts.map +1 -1
  35. package/dist/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.js +1 -1
  36. package/dist/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.js.map +1 -1
  37. package/dist/plugins/prometheus-time-series-query/get-time-series-data.d.ts.map +1 -1
  38. package/dist/plugins/prometheus-time-series-query/get-time-series-data.js +6 -11
  39. package/dist/plugins/prometheus-time-series-query/get-time-series-data.js.map +1 -1
  40. package/dist/plugins/prometheus-time-series-query/query-editor-model.d.ts +1 -1
  41. package/dist/plugins/prometheus-time-series-query/query-editor-model.d.ts.map +1 -1
  42. package/dist/plugins/prometheus-time-series-query/query-editor-model.js.map +1 -1
  43. package/dist/plugins/prometheus-time-series-query/replace-prom-builtin-variables.d.ts +2 -0
  44. package/dist/plugins/prometheus-time-series-query/replace-prom-builtin-variables.d.ts.map +1 -0
  45. package/dist/plugins/prometheus-time-series-query/replace-prom-builtin-variables.js +33 -0
  46. package/dist/plugins/prometheus-time-series-query/replace-prom-builtin-variables.js.map +1 -0
  47. package/dist/plugins/prometheus-variables.d.ts.map +1 -1
  48. package/dist/plugins/prometheus-variables.js.map +1 -1
  49. package/dist/plugins/variable.d.ts.map +1 -1
  50. package/dist/plugins/variable.js.map +1 -1
  51. package/dist/utils/utils.d.ts.map +1 -1
  52. package/dist/utils/utils.js.map +1 -1
  53. package/package.json +6 -5
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { produce } from 'immer';\nimport { DatasourceSelect, DatasourceSelectProps, useDatasource, useDatasourceClient } from '@perses-dev/plugin-system';\nimport { FormControl, InputLabel, Stack, TextField } from '@mui/material';\nimport {\n DEFAULT_PROM,\n DurationString,\n isDefaultPromSelector,\n isPrometheusDatasourceSelector,\n PROM_DATASOURCE_KIND,\n PrometheusClient,\n} from '../../model';\nimport { DEFAULT_SCRAPE_INTERVAL, PrometheusDatasourceSpec } from '../types';\nimport { PromQLEditor } from '../../components';\nimport {\n PrometheusTimeSeriesQueryEditorProps,\n useQueryState,\n useFormatState,\n useMinStepState,\n} from './query-editor-model';\n\n/**\n * The options editor component for editing a PrometheusTimeSeriesQuery's spec.\n */\nexport function PrometheusTimeSeriesQueryEditor(props: PrometheusTimeSeriesQueryEditorProps) {\n const { onChange, value } = props;\n const { datasource } = value;\n const selectedDatasource = datasource ?? DEFAULT_PROM;\n const datasourceSelectLabelID = `prom-datasource-label-${selectedDatasource.name || 'default'}`;\n\n const { data: client } = useDatasourceClient<PrometheusClient>(selectedDatasource);\n const promURL = client?.options.datasourceUrl;\n const { data: datasourceResource } = useDatasource(selectedDatasource);\n\n const { handleQueryChange, handleQueryBlur } = useQueryState(props);\n const { format, handleFormatChange, handleFormatBlur } = useFormatState(props);\n const { minStep, handleMinStepChange, handleMinStepBlur } = useMinStepState(props);\n const minStepPlaceholder =\n minStep ??\n (datasourceResource && (datasourceResource?.plugin.spec as PrometheusDatasourceSpec).scrapeInterval) ??\n DEFAULT_SCRAPE_INTERVAL;\n\n const handleDatasourceChange: DatasourceSelectProps['onChange'] = (next) => {\n if (isPrometheusDatasourceSelector(next)) {\n onChange(\n produce(value, (draft) => {\n // If they're using the default, just omit the datasource prop (i.e. set to undefined)\n const nextDatasource = isDefaultPromSelector(next) ? undefined : next;\n draft.datasource = nextDatasource;\n })\n );\n return;\n }\n\n throw new Error('Got unexpected non-Prometheus datasource selector');\n };\n\n return (\n <Stack spacing={2}>\n <FormControl margin=\"dense\" fullWidth={false}>\n <InputLabel id={datasourceSelectLabelID}>Prometheus Datasource</InputLabel>\n <DatasourceSelect\n datasourcePluginKind={PROM_DATASOURCE_KIND}\n value={selectedDatasource}\n onChange={handleDatasourceChange}\n labelId={datasourceSelectLabelID}\n label=\"Prometheus Datasource\"\n />\n </FormControl>\n <PromQLEditor\n completeConfig={{ remote: { url: promURL } }}\n value={value.query} // here we are passing `value.query` and not `query` from useQueryState in order to get updates only on onBlur events\n datasource={selectedDatasource}\n onChange={handleQueryChange}\n onBlur={handleQueryBlur}\n />\n <Stack direction=\"row\" spacing={2}>\n <TextField\n fullWidth\n label=\"Legend\"\n placeholder=\"Example: '{{instance}}' will generate series names like 'webserver-123', 'webserver-456'...\"\n helperText=\"Text to be displayed in the legend and the tooltip. Use {{label_name}} to interpolate label values.\"\n value={format ?? ''}\n onChange={(e) => handleFormatChange(e.target.value)}\n onBlur={handleFormatBlur}\n />\n <TextField\n label=\"Min Step\"\n placeholder={minStepPlaceholder}\n helperText=\"Step parameter of the query. Used by $__interval and $__rate_interval too.\"\n value={minStep}\n onChange={(e) => handleMinStepChange(e.target.value as DurationString)}\n onBlur={handleMinStepBlur}\n sx={{ width: '250px' }}\n />\n </Stack>\n </Stack>\n );\n}\n"],"names":["produce","DatasourceSelect","useDatasource","useDatasourceClient","FormControl","InputLabel","Stack","TextField","DEFAULT_PROM","isDefaultPromSelector","isPrometheusDatasourceSelector","PROM_DATASOURCE_KIND","DEFAULT_SCRAPE_INTERVAL","PromQLEditor","useQueryState","useFormatState","useMinStepState","PrometheusTimeSeriesQueryEditor","props","onChange","value","datasource","selectedDatasource","datasourceSelectLabelID","name","data","client","promURL","options","datasourceUrl","datasourceResource","handleQueryChange","handleQueryBlur","format","handleFormatChange","handleFormatBlur","minStep","handleMinStepChange","handleMinStepBlur","minStepPlaceholder","plugin","spec","scrapeInterval","handleDatasourceChange","next","draft","nextDatasource","undefined","Error","spacing","margin","fullWidth","id","datasourcePluginKind","labelId","label","completeConfig","remote","url","query","onBlur","direction","placeholder","helperText","e","target","sx","width"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,OAAO,QAAQ,QAAQ;AAChC,SAASC,gBAAgB,EAAyBC,aAAa,EAAEC,mBAAmB,QAAQ,4BAA4B;AACxH,SAASC,WAAW,EAAEC,UAAU,EAAEC,KAAK,EAAEC,SAAS,QAAQ,gBAAgB;AAC1E,SACEC,YAAY,EAEZC,qBAAqB,EACrBC,8BAA8B,EAC9BC,oBAAoB,QAEf,cAAc;AACrB,SAASC,uBAAuB,QAAkC,WAAW;AAC7E,SAASC,YAAY,QAAQ,mBAAmB;AAChD,SAEEC,aAAa,EACbC,cAAc,EACdC,eAAe,QACV,uBAAuB;AAE9B;;CAEC,GACD,OAAO,SAASC,gCAAgCC,KAA2C;IACzF,MAAM,EAAEC,QAAQ,EAAEC,KAAK,EAAE,GAAGF;IAC5B,MAAM,EAAEG,UAAU,EAAE,GAAGD;IACvB,MAAME,qBAAqBD,uBAAAA,wBAAAA,aAAcb;IACzC,MAAMe,0BAA0B,CAAC,sBAAsB,EAAED,mBAAmBE,IAAI,IAAI,UAAU,CAAC;IAE/F,MAAM,EAAEC,MAAMC,MAAM,EAAE,GAAGvB,oBAAsCmB;IAC/D,MAAMK,UAAUD,mBAAAA,6BAAAA,OAAQE,OAAO,CAACC,aAAa;IAC7C,MAAM,EAAEJ,MAAMK,kBAAkB,EAAE,GAAG5B,cAAcoB;IAEnD,MAAM,EAAES,iBAAiB,EAAEC,e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,KAAC5B;wBACCgD,OAAM;wBACNO,aAAavB;wBACbwB,YAAW;wBACX3C,OAAOgB;wBACPjB,UAAU,CAAC6C,IAAM3B,oBAAoB2B,EAAEC,MAAM,CAAC7C,KAAK;wBACnDwC,QAAQtB;wBACR4B,IAAI;4BAAEC,OAAO;wBAAQ;;;;;;AAK/B"}
1
+ {"version":3,"sources":["../../../src/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { produce } from 'immer';\nimport { DatasourceSelect, DatasourceSelectProps, useDatasource, useDatasourceClient } from '@perses-dev/plugin-system';\nimport { FormControl, InputLabel, Stack, TextField } from '@mui/material';\nimport { ReactElement } from 'react';\nimport {\n DEFAULT_PROM,\n DurationString,\n isDefaultPromSelector,\n isPrometheusDatasourceSelector,\n PROM_DATASOURCE_KIND,\n PrometheusClient,\n} from '../../model';\nimport { DEFAULT_SCRAPE_INTERVAL, PrometheusDatasourceSpec } from '../types';\nimport { PromQLEditor } from '../../components';\nimport {\n PrometheusTimeSeriesQueryEditorProps,\n useQueryState,\n useFormatState,\n useMinStepState,\n} from './query-editor-model';\n\n/**\n * The options editor component for editing a PrometheusTimeSeriesQuery's spec.\n */\nexport function PrometheusTimeSeriesQueryEditor(props: PrometheusTimeSeriesQueryEditorProps): ReactElement {\n const { onChange, value } = props;\n const { datasource } = value;\n const selectedDatasource = datasource ?? DEFAULT_PROM;\n const datasourceSelectLabelID = `prom-datasource-label-${selectedDatasource.name || 'default'}`;\n\n const { data: client } = useDatasourceClient<PrometheusClient>(selectedDatasource);\n const promURL = client?.options.datasourceUrl;\n const { data: datasourceResource } = useDatasource(selectedDatasource);\n\n const { handleQueryChange, handleQueryBlur } = useQueryState(props);\n const { format, handleFormatChange, handleFormatBlur } = useFormatState(props);\n const { minStep, handleMinStepChange, handleMinStepBlur } = useMinStepState(props);\n const minStepPlaceholder =\n minStep ??\n (datasourceResource && (datasourceResource?.plugin.spec as PrometheusDatasourceSpec).scrapeInterval) ??\n DEFAULT_SCRAPE_INTERVAL;\n\n const handleDatasourceChange: DatasourceSelectProps['onChange'] = (next) => {\n if (isPrometheusDatasourceSelector(next)) {\n onChange(\n produce(value, (draft) => {\n // If they're using the default, just omit the datasource prop (i.e. set to undefined)\n const nextDatasource = isDefaultPromSelector(next) ? undefined : next;\n draft.datasource = nextDatasource;\n })\n );\n return;\n }\n\n throw new Error('Got unexpected non-Prometheus datasource selector');\n };\n\n return (\n <Stack spacing={2}>\n <FormControl margin=\"dense\" fullWidth={false}>\n <InputLabel id={datasourceSelectLabelID}>Prometheus Datasource</InputLabel>\n <DatasourceSelect\n datasourcePluginKind={PROM_DATASOURCE_KIND}\n value={selectedDatasource}\n onChange={handleDatasourceChange}\n labelId={datasourceSelectLabelID}\n label=\"Prometheus Datasource\"\n />\n </FormControl>\n <PromQLEditor\n completeConfig={{ remote: { url: promURL } }}\n value={value.query} // here we are passing `value.query` and not `query` from useQueryState in order to get updates only on onBlur events\n datasource={selectedDatasource}\n onChange={handleQueryChange}\n onBlur={handleQueryBlur}\n />\n <Stack direction=\"row\" spacing={2}>\n <TextField\n fullWidth\n label=\"Legend\"\n placeholder=\"Example: '{{instance}}' will generate series names like 'webserver-123', 'webserver-456'...\"\n helperText=\"Text to be displayed in the legend and the tooltip. Use {{label_name}} to interpolate label values.\"\n value={format ?? ''}\n onChange={(e) => handleFormatChange(e.target.value)}\n onBlur={handleFormatBlur}\n />\n <TextField\n label=\"Min Step\"\n placeholder={minStepPlaceholder}\n helperText=\"Lower bound for the step. If not provided, the scrape interval of the datasource is used.\"\n value={minStep}\n onChange={(e) => handleMinStepChange(e.target.value as DurationString)}\n onBlur={handleMinStepBlur}\n sx={{ width: '250px' }}\n />\n </Stack>\n </Stack>\n );\n}\n"],"names":["produce","DatasourceSelect","useDatasource","useDatasourceClient","FormControl","InputLabel","Stack","TextField","DEFAULT_PROM","isDefaultPromSelector","isPrometheusDatasourceSelector","PROM_DATASOURCE_KIND","DEFAULT_SCRAPE_INTERVAL","PromQLEditor","useQueryState","useFormatState","useMinStepState","PrometheusTimeSeriesQueryEditor","props","onChange","value","datasource","selectedDatasource","datasourceSelectLabelID","name","data","client","promURL","options","datasourceUrl","datasourceResource","handleQueryChange","handleQueryBlur","format","handleFormatChange","handleFormatBlur","minStep","handleMinStepChange","handleMinStepBlur","minStepPlaceholder","plugin","spec","scrapeInterval","handleDatasourceChange","next","draft","nextDatasource","undefined","Error","spacing","margin","fullWidth","id","datasourcePluginKind","labelId","label","completeConfig","remote","url","query","onBlur","direction","placeholder","helperText","e","target","sx","width"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,OAAO,QAAQ,QAAQ;AAChC,SAASC,gBAAgB,EAAyBC,aAAa,EAAEC,mBAAmB,QAAQ,4BAA4B;AACxH,SAASC,WAAW,EAAEC,UAAU,EAAEC,KAAK,EAAEC,SAAS,QAAQ,gBAAgB;AAE1E,SACEC,YAAY,EAEZC,qBAAqB,EACrBC,8BAA8B,EAC9BC,oBAAoB,QAEf,cAAc;AACrB,SAASC,uBAAuB,QAAkC,WAAW;AAC7E,SAASC,YAAY,QAAQ,mBAAmB;AAChD,SAEEC,aAAa,EACbC,cAAc,EACdC,eAAe,QACV,uBAAuB;AAE9B;;CAEC,GACD,OAAO,SAASC,gCAAgCC,KAA2C;IAC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ACTgC,OAAM;;;;0BAGV,KAAC1C;gBACC2C,gBAAgB;oBAAEC,QAAQ;wBAAEC,KAAK/B;oBAAQ;gBAAE;gBAC3CP,OAAOA,MAAMuC,KAAK;gBAClBtC,YAAYC;gBACZH,UAAUY;gBACV6B,QAAQ5B;;0BAEV,MAAC1B;gBAAMuD,WAAU;gBAAMZ,SAAS;;kCAC9B,KAAC1C;wBACC4C,SAAS;wBACTI,OAAM;wBACNO,aAAY;wBACZC,YAAW;wBACX3C,OAAOa,mBAAAA,oBAAAA,SAAU;wBACjBd,UAAU,CAAC6C,IAAM9B,mBAAmB8B,EAAEC,MAAM,CAAC7C,KAAK;wBAClDwC,QAAQzB;;kCAEV,KAAC5B;wBACCgD,OAAM;wBACNO,aAAavB;wBACbwB,YAAW;wBACX3C,OAAOgB;wBACPjB,UAAU,CAAC6C,IAAM3B,oBAAoB2B,EAAEC,MAAM,CAAC7C,KAAK;wBACnDwC,QAAQtB;wBACR4B,IAAI;4BAAEC,OAAO;wBAAQ;;;;;;AAK/B"}
@@ -1 +1 @@
1
- {"version":3,"file":"get-time-series-data.d.ts","sourceRoot":"","sources":["../../../src/plugins/prometheus-time-series-query/get-time-series-data.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,qBAAqB,EAAqC,MAAM,2BAA2B,CAAC;AAerG,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAE1E,eAAO,MAAM,iBAAiB,EAAE,qBAAqB,CAAC,6BAA6B,CAAC,CAAC,mBAAmB,CA4GvG,CAAC"}
1
+ {"version":3,"file":"get-time-series-data.d.ts","sourceRoot":"","sources":["../../../src/plugins/prometheus-time-series-query/get-time-series-data.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,qBAAqB,EAAoB,MAAM,2BAA2B,CAAC;AAepF,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAG1E,eAAO,MAAM,iBAAiB,EAAE,qBAAqB,CAAC,6BAA6B,CAAC,CAAC,mBAAmB,CAqGvG,CAAC"}
@@ -10,12 +10,13 @@
10
10
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  // See the License for the specific language governing permissions and
12
12
  // limitations under the License.
13
- import { formatDuration, msToPrometheusDuration, parseDurationString } from '@perses-dev/core';
14
- import { replaceVariables, replaceVariable } from '@perses-dev/plugin-system';
13
+ import { parseDurationString } from '@perses-dev/core';
14
+ import { replaceVariables } from '@perses-dev/plugin-system';
15
15
  import { fromUnixTime, milliseconds } from 'date-fns';
16
16
  import { parseValueTuple, getDurationStringSeconds, getPrometheusTimeRange, getRangeStep, DEFAULT_PROM } from '../../model';
17
17
  import { getFormattedPrometheusSeriesName } from '../../utils';
18
18
  import { DEFAULT_SCRAPE_INTERVAL } from '../types';
19
+ import { replacePromBuiltinVariables } from './replace-prom-builtin-variables';
19
20
  export const getTimeSeriesData = async (spec, context)=>{
20
21
  if (spec.query === undefined || spec.query === null || spec.query === '') {
21
22
  // Do not make a request to the backend, instead return an empty TimeSeriesData
@@ -43,15 +44,9 @@ export const getTimeSeriesData = async (spec, context)=>{
43
44
  start = alignedStart;
44
45
  end = alignedEnd;
45
46
  // Replace variable placeholders in PromQL query
46
- const intervalMs = step * 1000; // step is in seconds
47
- let query = replaceVariable(spec.query, '__interval_ms', intervalMs.toString());
48
- query = replaceVariable(spec.query, '__interval', formatDuration(msToPrometheusDuration(intervalMs)));
49
- const scrapeIntervalMs = minStep * 1000;
50
- // The $__rate_interval variable is meant to be used in the rate function.
51
- // It is defined as max($__interval + Scrape interval, 4 * Scrape interval), where Scrape interval is the Min step setting (a setting per PromQL query),
52
- // if any is set, and otherwise the Scrape interval as set in the Prometheus datasource
53
- const rateIntervalMs = Math.max(intervalMs + scrapeIntervalMs, 4 * scrapeIntervalMs);
54
- query = replaceVariable(query, '__rate_interval', formatDuration(msToPrometheusDuration(rateIntervalMs)));
47
+ const intervalMs = step * 1000;
48
+ const minStepMs = minStep * 1000;
49
+ let query = replacePromBuiltinVariables(spec.query, minStepMs, intervalMs);
55
50
  query = replaceVariables(query, context.variableState);
56
51
  let seriesNameFormat = spec.seriesNameFormat;
57
52
  // if series name format is defined, replace variable placeholders in series name format
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/plugins/prometheus-time-series-query/get-time-series-data.ts"],"sourcesContent":["// Copyright 2024 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport {\n DatasourceSpec,\n DurationString,\n formatDuration,\n msToPrometheusDuration,\n Notice,\n parseDurationString,\n TimeSeries,\n TimeSeriesData,\n} from '@perses-dev/core';\nimport { TimeSeriesQueryPlugin, replaceVariables, replaceVariable } from '@perses-dev/plugin-system';\nimport { fromUnixTime, milliseconds } from 'date-fns';\nimport {\n parseValueTuple,\n PrometheusClient,\n getDurationStringSeconds,\n getPrometheusTimeRange,\n getRangeStep,\n DEFAULT_PROM,\n MatrixData,\n VectorData,\n ScalarData,\n} from '../../model';\nimport { getFormattedPrometheusSeriesName } from '../../utils';\nimport { DEFAULT_SCRAPE_INTERVAL, PrometheusDatasourceSpec } from '../types';\nimport { PrometheusTimeSeriesQuerySpec } from './time-series-query-model';\n\nexport const getTimeSeriesData: TimeSeriesQueryPlugin<PrometheusTimeSeriesQuerySpec>['getTimeSeriesData'] = async (\n spec,\n context\n) => {\n if (spec.query === undefined || spec.query === null || spec.query === '') {\n // Do not make a request to the backend, instead return an empty TimeSeriesData\n return { series: [] };\n }\n\n const datasource = (await context.datasourceStore.getDatasource(\n spec.datasource ?? DEFAULT_PROM\n )) as DatasourceSpec<PrometheusDatasourceSpec>;\n const datasourceScrapeInterval = Math.trunc(\n milliseconds(parseDurationString(datasource.plugin.spec.scrapeInterval ?? DEFAULT_SCRAPE_INTERVAL)) / 1000\n );\n\n // Min step is the lower bound of the interval between data points\n // If no value is provided for it, it should default to the scrape interval of the datasource\n const minStep =\n getDurationStringSeconds(\n // resolve any variable that may have been provided\n // TODO add a validation check to make sure the variable is a DurationString, to avoid the back & forth cast here\n replaceVariables(spec.minStep as string, context.variableState) as DurationString\n ) ?? datasourceScrapeInterval;\n const timeRange = getPrometheusTimeRange(context.timeRange);\n const step = getRangeStep(timeRange, minStep, undefined, context.suggestedStepMs); // TODO: resolution\n\n // Align the time range so that it's a multiple of the step\n let { start, end } = timeRange;\n const utcOffsetSec = new Date().getTimezoneOffset() * 60;\n\n const alignedEnd = Math.floor((end + utcOffsetSec) / step) * step - utcOffsetSec;\n const alignedStart = Math.floor((start + utcOffsetSec) / step) * step - utcOffsetSec;\n start = alignedStart;\n end = alignedEnd;\n\n // Replace variable placeholders in PromQL query\n const intervalMs = step * 1000; // step is in seconds\n let query = replaceVariable(spec.query, '__interval_ms', intervalMs.toString());\n query = replaceVariable(spec.query, '__interval', formatDuration(msToPrometheusDuration(intervalMs)));\n\n const scrapeIntervalMs = minStep * 1000;\n // The $__rate_interval variable is meant to be used in the rate function.\n // It is defined as max($__interval + Scrape interval, 4 * Scrape interval), where Scrape interval is the Min step setting (a setting per PromQL query),\n // if any is set, and otherwise the Scrape interval as set in the Prometheus datasource\n const rateIntervalMs = Math.max(intervalMs + scrapeIntervalMs, 4 * scrapeIntervalMs);\n query = replaceVariable(query, '__rate_interval', formatDuration(msToPrometheusDuration(rateIntervalMs)));\n query = replaceVariables(query, context.variableState);\n\n let seriesNameFormat = spec.seriesNameFormat;\n // if series name format is defined, replace variable placeholders in series name format\n if (seriesNameFormat) {\n seriesNameFormat = replaceVariables(seriesNameFormat, context.variableState);\n }\n\n // Get the datasource, using the default Prom Datasource if one isn't specified in the query\n const client: PrometheusClient = await context.datasourceStore.getDatasourceClient(spec.datasource ?? DEFAULT_PROM);\n\n // Make the request to Prom\n let response;\n switch (context.mode) {\n case 'instant':\n response = await client.instantQuery({\n query,\n time: end,\n });\n break;\n case 'range':\n default:\n response = await client.rangeQuery({\n query,\n start,\n end,\n step,\n });\n break;\n }\n\n // TODO: What about error responses from Prom that have a response body?\n const result = response.data;\n\n // Custom display for response header warnings, configurable error responses display coming next\n const notices: Notice[] = [];\n if (response.status === 'success') {\n const warnings = response.warnings ?? [];\n const warningMessage = warnings[0] ?? '';\n if (warningMessage !== '') {\n notices.push({\n type: 'warning',\n message: warningMessage,\n });\n }\n }\n\n // Transform response\n const chartData: TimeSeriesData = {\n // Return the time range and step we actually used for the query\n timeRange: { start: fromUnixTime(start), end: fromUnixTime(end) },\n stepMs: step * 1000,\n\n series: buildTimeSeries(result, query, seriesNameFormat),\n metadata: {\n notices,\n executedQueryString: query,\n },\n };\n\n return chartData;\n};\n\nfunction buildVectorData(data: VectorData, query: string, seriesNameFormat: string | undefined): TimeSeries[] {\n return data.result.map((res) => {\n const { metric, value } = res;\n\n // Account for seriesNameFormat from query editor when determining name to show in legend, tooltip, etc.\n const { name, formattedName } = getFormattedPrometheusSeriesName(query, metric, seriesNameFormat);\n\n return {\n name,\n values: [parseValueTuple(value)],\n formattedName,\n labels: metric,\n };\n });\n}\n\nfunction buildMatrixData(data: MatrixData, query: string, seriesNameFormat: string | undefined): TimeSeries[] {\n return data.result.map((res) => {\n const { metric, values } = res;\n\n // Account for seriesNameFormat from query editor when determining name to show in legend, tooltip, etc.\n const { name, formattedName } = getFormattedPrometheusSeriesName(query, metric, seriesNameFormat);\n\n return {\n name,\n values: values.map(parseValueTuple),\n formattedName,\n labels: metric,\n };\n });\n}\n\nfunction buildScalarData(data: ScalarData, query: string, seriesNameFormat: string | undefined): TimeSeries[] {\n const { name, formattedName } = getFormattedPrometheusSeriesName(query, {}, seriesNameFormat);\n return [\n {\n name,\n values: [parseValueTuple(data.result)],\n formattedName,\n },\n ];\n}\n\nfunction buildTimeSeries(\n data: MatrixData | VectorData | ScalarData | undefined,\n query: string,\n seriesNameFormat?: string\n): TimeSeries[] {\n if (!data) {\n return [];\n }\n\n const resultType = data.resultType;\n\n switch (resultType) {\n case 'vector':\n return buildVectorData(data, query, seriesNameFormat);\n case 'matrix':\n return buildMatrixData(data, query, seriesNameFormat);\n case 'scalar':\n return buildScalarData(data, query, seriesNameFormat);\n default:\n console.warn('Unknown result type', resultType, data);\n return [];\n }\n}\n"],"names":["formatDuration","msToPrometheusDuration","parseDurationString","replaceVariables","replaceVariable","fromUnixTime","milliseconds","parseValueTuple","getDurationStringSeconds","getPrometheusTimeRange","getRangeStep","DEFAULT_PROM","getFormattedPrometheusSeriesName","DEFAULT_SCRAPE_INTERVAL","getTimeSeriesData","spec","context","query","undefined","series","datasource","datasourceStore","getDatasource","datasourceScrapeInterval","Math","trunc","plugin","scrapeInterval","minStep","variableState","timeRange","step","suggestedStepMs","start","end","utcOffsetSec","Date","getTimezoneOffset","alignedEnd","floor","alignedStart","intervalMs","toString","scrapeIntervalMs","rateIntervalMs","max","seriesNameFormat","client","getDatasourceClient","response","mode","instantQuery","time","rangeQuery","result","data","notices","status","warnings","warningMessage","push","type","message","chartData","stepMs","buildTimeSeries","metadata","executedQueryString","buildVectorData","map","res","metric","value","name","formattedName","values","labels","buildMatrixData","buildScalarData","resultType","console","warn"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAGEA,cAAc,EACdC,sBAAsB,EAEtBC,mBAAmB,QAGd,mBAAmB;AAC1B,SAAgCC,gBAAgB,EAAEC,eAAe,QAAQ,4BAA4B;AACrG,SAASC,YAAY,EAAEC,YAAY,QAAQ,WAAW;AACtD,SACEC,eAAe,EAEfC,wBAAwB,EACxBC,sBAAsB,EACtBC,YAAY,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5E,OAAO;QACL;YACE2B;YACAE,QAAQ;gBAACpE,gBAAgBgD,KAAKD,MAAM;aAAE;YACtCoB;QACF;KACD;AACH;AAEA,SAAST,gBACPV,IAAsD,EACtDtC,KAAa,EACb6B,gBAAyB;IAEzB,IAAI,CAACS,MAAM;QACT,OAAO,EAAE;IACX;IAEA,MAAMwB,aAAaxB,KAAKwB,UAAU;IAElC,OAAQA;QACN,KAAK;YACH,OAAOX,gBAAgBb,MAAMtC,OAAO6B;QACtC,KAAK;YACH,OAAO+B,gBAAgBtB,MAAMtC,OAAO6B;QACtC,KAAK;YACH,OAAOgC,gBAAgBvB,MAAMtC,OAAO6B;QACtC;YACEkC,QAAQC,IAAI,CAAC,uBAAuBF,YAAYxB;YAChD,OAAO,EAAE;IACb;AACF"}
1
+ {"version":3,"sources":["../../../src/plugins/prometheus-time-series-query/get-time-series-data.ts"],"sourcesContent":["// Copyright 2024 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport {\n DatasourceSpec,\n DurationString,\n Notice,\n parseDurationString,\n TimeSeries,\n TimeSeriesData,\n} from '@perses-dev/core';\nimport { TimeSeriesQueryPlugin, replaceVariables } from '@perses-dev/plugin-system';\nimport { fromUnixTime, milliseconds } from 'date-fns';\nimport {\n parseValueTuple,\n PrometheusClient,\n getDurationStringSeconds,\n getPrometheusTimeRange,\n getRangeStep,\n DEFAULT_PROM,\n MatrixData,\n VectorData,\n ScalarData,\n} from '../../model';\nimport { getFormattedPrometheusSeriesName } from '../../utils';\nimport { DEFAULT_SCRAPE_INTERVAL, PrometheusDatasourceSpec } from '../types';\nimport { PrometheusTimeSeriesQuerySpec } from './time-series-query-model';\nimport { replacePromBuiltinVariables } from './replace-prom-builtin-variables';\n\nexport const getTimeSeriesData: TimeSeriesQueryPlugin<PrometheusTimeSeriesQuerySpec>['getTimeSeriesData'] = async (\n spec,\n context\n) => {\n if (spec.query === undefined || spec.query === null || spec.query === '') {\n // Do not make a request to the backend, instead return an empty TimeSeriesData\n return { series: [] };\n }\n\n const datasource = (await context.datasourceStore.getDatasource(\n spec.datasource ?? DEFAULT_PROM\n )) as DatasourceSpec<PrometheusDatasourceSpec>;\n const datasourceScrapeInterval = Math.trunc(\n milliseconds(parseDurationString(datasource.plugin.spec.scrapeInterval ?? DEFAULT_SCRAPE_INTERVAL)) / 1000\n );\n\n // Min step is the lower bound of the interval between data points\n // If no value is provided for it, it should default to the scrape interval of the datasource\n const minStep =\n getDurationStringSeconds(\n // resolve any variable that may have been provided\n // TODO add a validation check to make sure the variable is a DurationString, to avoid the back & forth cast here\n replaceVariables(spec.minStep as string, context.variableState) as DurationString\n ) ?? datasourceScrapeInterval;\n const timeRange = getPrometheusTimeRange(context.timeRange);\n const step = getRangeStep(timeRange, minStep, undefined, context.suggestedStepMs); // TODO: resolution\n\n // Align the time range so that it's a multiple of the step\n let { start, end } = timeRange;\n const utcOffsetSec = new Date().getTimezoneOffset() * 60;\n\n const alignedEnd = Math.floor((end + utcOffsetSec) / step) * step - utcOffsetSec;\n const alignedStart = Math.floor((start + utcOffsetSec) / step) * step - utcOffsetSec;\n start = alignedStart;\n end = alignedEnd;\n\n // Replace variable placeholders in PromQL query\n const intervalMs = step * 1000;\n const minStepMs = minStep * 1000;\n let query = replacePromBuiltinVariables(spec.query, minStepMs, intervalMs);\n query = replaceVariables(query, context.variableState);\n\n let seriesNameFormat = spec.seriesNameFormat;\n // if series name format is defined, replace variable placeholders in series name format\n if (seriesNameFormat) {\n seriesNameFormat = replaceVariables(seriesNameFormat, context.variableState);\n }\n\n // Get the datasource, using the default Prom Datasource if one isn't specified in the query\n const client: PrometheusClient = await context.datasourceStore.getDatasourceClient(spec.datasource ?? DEFAULT_PROM);\n\n // Make the request to Prom\n let response;\n switch (context.mode) {\n case 'instant':\n response = await client.instantQuery({\n query,\n time: end,\n });\n break;\n case 'range':\n default:\n response = await client.rangeQuery({\n query,\n start,\n end,\n step,\n });\n break;\n }\n\n // TODO: What about error responses from Prom that have a response body?\n const result = response.data;\n\n // Custom display for response header warnings, configurable error responses display coming next\n const notices: Notice[] = [];\n if (response.status === 'success') {\n const warnings = response.warnings ?? [];\n const warningMessage = warnings[0] ?? '';\n if (warningMessage !== '') {\n notices.push({\n type: 'warning',\n message: warningMessage,\n });\n }\n }\n\n // Transform response\n const chartData: TimeSeriesData = {\n // Return the time range and step we actually used for the query\n timeRange: { start: fromUnixTime(start), end: fromUnixTime(end) },\n stepMs: step * 1000,\n\n series: buildTimeSeries(result, query, seriesNameFormat),\n metadata: {\n notices,\n executedQueryString: query,\n },\n };\n\n return chartData;\n};\n\nfunction buildVectorData(data: VectorData, query: string, seriesNameFormat: string | undefined): TimeSeries[] {\n return data.result.map((res) => {\n const { metric, value } = res;\n\n // Account for seriesNameFormat from query editor when determining name to show in legend, tooltip, etc.\n const { name, formattedName } = getFormattedPrometheusSeriesName(query, metric, seriesNameFormat);\n\n return {\n name,\n values: [parseValueTuple(value)],\n formattedName,\n labels: metric,\n };\n });\n}\n\nfunction buildMatrixData(data: MatrixData, query: string, seriesNameFormat: string | undefined): TimeSeries[] {\n return data.result.map((res) => {\n const { metric, values } = res;\n\n // Account for seriesNameFormat from query editor when determining name to show in legend, tooltip, etc.\n const { name, formattedName } = getFormattedPrometheusSeriesName(query, metric, seriesNameFormat);\n\n return {\n name,\n values: values.map(parseValueTuple),\n formattedName,\n labels: metric,\n };\n });\n}\n\nfunction buildScalarData(data: ScalarData, query: string, seriesNameFormat: string | undefined): TimeSeries[] {\n const { name, formattedName } = getFormattedPrometheusSeriesName(query, {}, seriesNameFormat);\n return [\n {\n name,\n values: [parseValueTuple(data.result)],\n formattedName,\n },\n ];\n}\n\nfunction buildTimeSeries(\n data: MatrixData | VectorData | ScalarData | undefined,\n query: string,\n seriesNameFormat?: string\n): TimeSeries[] {\n if (!data) {\n return [];\n }\n\n const resultType = data.resultType;\n\n switch (resultType) {\n case 'vector':\n return buildVectorData(data, query, seriesNameFormat);\n case 'matrix':\n return buildMatrixData(data, query, seriesNameFormat);\n case 'scalar':\n return buildScalarData(data, query, seriesNameFormat);\n default:\n console.warn('Unknown result type', resultType, data);\n return [];\n }\n}\n"],"names":["parseDurationString","replaceVariables","fromUnixTime","milliseconds","parseValueTuple","getDurationStringSeconds","getPrometheusTimeRange","getRangeStep","DEFAULT_PROM","getFormattedPrometheusSeriesName","DEFAULT_SCRAPE_INTERVAL","replacePromBuiltinVariables","getTimeSeriesData","spec","context","query","undefined","series","datasource","datasourceStore","getDatasource","datasourceScrapeInterval","Math","trunc","plugin","scrapeInterval","minStep","variableState","timeRange","step","suggestedStepMs","start","end","utcOffsetSec","Date","getTimezoneOffset","alignedEnd","floor","alignedStart","intervalMs","minStepMs","seriesNameFormat","client","getDatasourceClient","response","mode","instantQuery","time","rangeQuery","result","data","notices","status","warnings","warningMessage","push","type","message","chartData","stepMs","buildTimeSeries","metadata","executedQueryString","buildVectorData","map","res","metric","value","name","formattedName","values","labels","buildMatrixData","buildScalarData","resultType","console","warn"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAIEA,mBAAmB,QAGd,mBAAmB;AAC1B,SAAgCC,gBAAgB,QAAQ,4BAA4B;AACpF,SAASC,YAAY,EAAEC,YAAY,QAAQ,WAAW;AACtD,SACEC,eAAe,EAEfC,wBAAwB,EACxBC,sBAAsB,EACtBC,YAAY,EACZC,YAAY,QAIP,cAAc;AACrB,SAASC,gCAAgC,QAA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,MAAMnC,OAAO0B;QACtC,KAAK;YACH,OAAO+B,gBAAgBtB,MAAMnC,OAAO0B;QACtC,KAAK;YACH,OAAOgC,gBAAgBvB,MAAMnC,OAAO0B;QACtC;YACEkC,QAAQC,IAAI,CAAC,uBAAuBF,YAAYxB;YAChD,OAAO,EAAE;IACb;AACF"}
@@ -25,7 +25,7 @@ export declare function useFormatState(props: PrometheusTimeSeriesQueryEditorPro
25
25
  * Hook to manage `minStep` state to ensure panel preview does not rerender until text input is blurred
26
26
  */
27
27
  export declare function useMinStepState(props: PrometheusTimeSeriesQueryEditorProps): {
28
- minStep: `${number}y` | `${number}w` | `${number}d` | `${number}h` | `${number}m` | `${number}s` | `${number}ms` | `${number}s${number}ms` | `${number}m${number}ms` | `${number}m${number}s` | `${number}m${number}s${number}ms` | `${number}h${number}ms` | `${number}h${number}s` | `${number}h${number}s${number}ms` | `${number}h${number}m` | `${number}h${number}m${number}ms` | `${number}h${number}m${number}s` | `${number}h${number}m${number}s${number}ms` | `${number}d${number}ms` | `${number}d${number}s` | `${number}d${number}s${number}ms` | `${number}d${number}m` | `${number}d${number}m${number}ms` | `${number}d${number}m${number}s` | `${number}d${number}m${number}s${number}ms` | `${number}d${number}h` | `${number}d${number}h${number}ms` | `${number}d${number}h${number}s` | `${number}d${number}h${number}s${number}ms` | `${number}d${number}h${number}m` | `${number}d${number}h${number}m${number}ms` | `${number}d${number}h${number}m${number}s` | `${number}d${number}h${number}m${number}s${number}ms` | `${number}w${number}ms` | `${number}w${number}s` | `${number}w${number}s${number}ms` | `${number}w${number}m` | `${number}w${number}m${number}ms` | `${number}w${number}m${number}s` | `${number}w${number}m${number}s${number}ms` | `${number}w${number}h` | `${number}w${number}h${number}ms` | `${number}w${number}h${number}s` | `${number}w${number}h${number}s${number}ms` | `${number}w${number}h${number}m` | `${number}w${number}h${number}m${number}ms` | `${number}w${number}h${number}m${number}s` | `${number}w${number}h${number}m${number}s${number}ms` | `${number}w${number}d` | `${number}w${number}d${number}ms` | `${number}w${number}d${number}s` | `${number}w${number}d${number}s${number}ms` | `${number}w${number}d${number}m` | `${number}w${number}d${number}m${number}ms` | `${number}w${number}d${number}m${number}s` | `${number}w${number}d${number}m${number}s${number}ms` | `${number}w${number}d${number}h` | `${number}w${number}d${number}h${number}ms` | `${number}w${number}d${number}h${number}s` | `${number}w${number}d${number}h${number}s${number}ms` | `${number}w${number}d${number}h${number}m` | `${number}w${number}d${number}h${number}m${number}ms` | `${number}w${number}d${number}h${number}m${number}s` | `${number}w${number}d${number}h${number}m${number}s${number}ms` | `${number}y${number}ms` | `${number}y${number}s` | `${number}y${number}s${number}ms` | `${number}y${number}m` | `${number}y${number}m${number}ms` | `${number}y${number}m${number}s` | `${number}y${number}m${number}s${number}ms` | `${number}y${number}h` | `${number}y${number}h${number}ms` | `${number}y${number}h${number}s` | `${number}y${number}h${number}s${number}ms` | `${number}y${number}h${number}m` | `${number}y${number}h${number}m${number}ms` | `${number}y${number}h${number}m${number}s` | `${number}y${number}h${number}m${number}s${number}ms` | `${number}y${number}d` | `${number}y${number}d${number}ms` | `${number}y${number}d${number}s` | `${number}y${number}d${number}s${number}ms` | `${number}y${number}d${number}m` | `${number}y${number}d${number}m${number}ms` | `${number}y${number}d${number}m${number}s` | `${number}y${number}d${number}m${number}s${number}ms` | `${number}y${number}d${number}h` | `${number}y${number}d${number}h${number}ms` | `${number}y${number}d${number}h${number}s` | `${number}y${number}d${number}h${number}s${number}ms` | `${number}y${number}d${number}h${number}m` | `${number}y${number}d${number}h${number}m${number}ms` | `${number}y${number}d${number}h${number}m${number}s` | `${number}y${number}d${number}h${number}m${number}s${number}ms` | `${number}y${number}w` | `${number}y${number}w${number}ms` | `${number}y${number}w${number}s` | `${number}y${number}w${number}s${number}ms` | `${number}y${number}w${number}m` | `${number}y${number}w${number}m${number}ms` | `${number}y${number}w${number}m${number}s` | `${number}y${number}w${number}m${number}s${number}ms` | `${number}y${number}w${number}h` | `${number}y${number}w${number}h${number}ms` | `${number}y${number}w${number}h${number}s` | `${number}y${number}w${number}h${number}s${number}ms` | `${number}y${number}w${number}h${number}m` | `${number}y${number}w${number}h${number}m${number}ms` | `${number}y${number}w${number}h${number}m${number}s` | `${number}y${number}w${number}h${number}m${number}s${number}ms` | `${number}y${number}w${number}d` | `${number}y${number}w${number}d${number}ms` | `${number}y${number}w${number}d${number}s` | `${number}y${number}w${number}d${number}s${number}ms` | `${number}y${number}w${number}d${number}m` | `${number}y${number}w${number}d${number}m${number}ms` | `${number}y${number}w${number}d${number}m${number}s` | `${number}y${number}w${number}d${number}m${number}s${number}ms` | `${number}y${number}w${number}d${number}h` | `${number}y${number}w${number}d${number}h${number}ms` | `${number}y${number}w${number}d${number}h${number}s` | `${number}y${number}w${number}d${number}h${number}s${number}ms` | `${number}y${number}w${number}d${number}h${number}m` | `${number}y${number}w${number}d${number}h${number}m${number}ms` | `${number}y${number}w${number}d${number}h${number}m${number}s` | `${number}y${number}w${number}d${number}h${number}m${number}s${number}ms` | undefined;
28
+ minStep: string | undefined;
29
29
  handleMinStepChange: (e: DurationString) => void;
30
30
  handleMinStepBlur: () => void;
31
31
  };
@@ -1 +1 @@
1
- {"version":3,"file":"query-editor-model.d.ts","sourceRoot":"","sources":["../../../src/plugins/prometheus-time-series-query/query-editor-model.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAE1E,MAAM,MAAM,oCAAoC,GAAG,kBAAkB,CAAC,6BAA6B,CAAC,CAAC;AAErG;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,oCAAoC;;2BAezC,MAAM;;EAgBrC;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,oCAAoC;;4BAYzC,MAAM;;EAetC;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,oCAAoC;;6BAYzC,cAAc;;EAe/C"}
1
+ {"version":3,"file":"query-editor-model.d.ts","sourceRoot":"","sources":["../../../src/plugins/prometheus-time-series-query/query-editor-model.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAE1E,MAAM,MAAM,oCAAoC,GAAG,kBAAkB,CAAC,6BAA6B,CAAC,CAAC;AAErG;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,oCAAoC,GAAG;IAC1E,KAAK,EAAE,MAAM,CAAC;IACd,iBAAiB,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,eAAe,EAAE,MAAM,IAAI,CAAC;CAC7B,CA+BA;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,oCAAoC,GAAG;IAC3E,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,kBAAkB,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IACxC,gBAAgB,EAAE,MAAM,IAAI,CAAC;CAC9B,CA2BA;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,oCAAoC,GAAG;IAC5E,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,mBAAmB,EAAE,CAAC,CAAC,EAAE,cAAc,KAAK,IAAI,CAAC;IACjD,iBAAiB,EAAE,MAAM,IAAI,CAAC;CAC/B,CA2BA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/plugins/prometheus-time-series-query/query-editor-model.ts"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { useState } from 'react';\nimport { produce } from 'immer';\nimport { OptionsEditorProps } from '@perses-dev/plugin-system';\nimport { DurationString } from '@perses-dev/core';\nimport { PrometheusTimeSeriesQuerySpec } from './time-series-query-model';\n\nexport type PrometheusTimeSeriesQueryEditorProps = OptionsEditorProps<PrometheusTimeSeriesQuerySpec>;\n\n/**\n * A hook for managing the `query` state in PrometheusTimeSeriesQuerySpec. Returns the `query` value, along with\n * `onChange` and `onBlur` event handlers to the input. Keeps a local copy of the user's input and only syncs those\n * changes with the overall spec value once the input is blurred to prevent re-running queries in the panel's preview\n * every time the user types.\n */\nexport function useQueryState(props: PrometheusTimeSeriesQueryEditorProps) {\n const { onChange, value } = props;\n\n // Local copy of the query's value\n const [query, setQuery] = useState(value.query);\n\n // This is basically \"getDerivedStateFromProps\" to make sure if spec's value changes external to this component,\n // we render with the latest value\n const [lastSyncedQuery, setLastSyncedQuery] = useState(value.query);\n if (value.query !== lastSyncedQuery) {\n setQuery(value.query);\n setLastSyncedQuery(value.query);\n }\n\n // Update our local state's copy as the user types\n const handleQueryChange = (e: string) => {\n setQuery(e);\n };\n\n // Propagate changes to the query's value when the input is blurred to avoid constantly re-running queries in the\n // PanelPreview\n const handleQueryBlur = () => {\n setLastSyncedQuery(query);\n onChange(\n produce(value, (draft) => {\n draft.query = query;\n })\n );\n };\n\n return { query, handleQueryChange, handleQueryBlur };\n}\n\n/**\n * Hook to manage `seriesNameFormat` state to ensure panel preview does not rerender until text input is blurred\n */\nexport function useFormatState(props: PrometheusTimeSeriesQueryEditorProps) {\n const { onChange, value } = props;\n\n // TODO: reusable hook or helper util instead of duplicating from useQueryState\n const [format, setFormat] = useState(value.seriesNameFormat);\n const [lastSyncedFormat, setLastSyncedFormat] = useState(value.seriesNameFormat);\n if (value.seriesNameFormat !== lastSyncedFormat) {\n setFormat(value.seriesNameFormat);\n setLastSyncedFormat(value.seriesNameFormat);\n }\n\n // Update our local state as the user types\n const handleFormatChange = (e: string) => {\n setFormat(e);\n };\n\n // Propagate changes to the panel preview component when seriesNameFormat TextField is blurred\n const handleFormatBlur = () => {\n setLastSyncedFormat(format);\n onChange(\n produce(value, (draft) => {\n draft.seriesNameFormat = format;\n })\n );\n };\n\n return { format, handleFormatChange, handleFormatBlur };\n}\n\n/**\n * Hook to manage `minStep` state to ensure panel preview does not rerender until text input is blurred\n */\nexport function useMinStepState(props: PrometheusTimeSeriesQueryEditorProps) {\n const { onChange, value } = props;\n\n // TODO: reusable hook or helper util instead of duplicating from useQueryState\n const [minStep, setMinStep] = useState(value.minStep);\n const [lastSyncedMinStep, setLastSyncedMinStep] = useState(value.minStep);\n if (value.minStep !== lastSyncedMinStep) {\n setMinStep(value.minStep);\n setLastSyncedMinStep(value.minStep);\n }\n\n // Update our local state as the user types\n const handleMinStepChange = (e: DurationString) => {\n setMinStep(e);\n };\n\n // Propagate changes to the panel preview component when minStep TextField is blurred\n const handleMinStepBlur = () => {\n setLastSyncedMinStep(minStep);\n onChange(\n produce(value, (draft) => {\n draft.minStep = minStep;\n })\n );\n };\n\n return { minStep, handleMinStepChange, handleMinStepBlur };\n}\n"],"names":["useState","produce","useQueryState","props","onChange","value","query","setQuery","lastSyncedQuery","setLastSyncedQuery","handleQueryChange","e","handleQueryBlur","draft","useFormatState","format","setFormat","seriesNameFormat","lastSyncedFormat","setLastSyncedFormat","handleFormatChange","handleFormatBlur","useMinStepState","minStep","setMinStep","lastSyncedMinStep","setLastSyncedMinStep","handleMinStepChange","handleMinStepBlur"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAs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gBAAgB,GAAGF;QAC3B;IAEJ;IAEA,OAAO;QAAEA;QAAQK;QAAoBC;IAAiB;AACxD;AAEA;;CAEC,GACD,OAAO,SAASC,gBAAgBnB,KAA2C;IACzE,MAAM,EAAEC,QAAQ,EAAEC,KAAK,EAAE,GAAGF;IAE5B,+EAA+E;IAC/E,MAAM,CAACoB,SAASC,WAAW,GAAGxB,SAASK,MAAMkB,OAAO;IACpD,MAAM,CAACE,mBAAmBC,qBAAqB,GAAG1B,SAASK,MAAMkB,OAAO;IACxE,IAAIlB,MAAMkB,OAAO,KAAKE,mBAAmB;QACvCD,WAAWnB,MAAMkB,OAAO;QACxBG,qBAAqBrB,MAAMkB,OAAO;IACpC;IAEA,2CAA2C;IAC3C,MAAMI,sBAAsB,CAAChB;QAC3Ba,WAAWb;IACb;IAEA,qFAAqF;IACrF,MAAMiB,oBAAoB;QACxBF,qBAAqBH;QACrBnB,SACEH,QAAQI,OAAO,CAACQ;YACdA,MAAMU,OAAO,GAAGA;QAClB;IAEJ;IAEA,OAAO;QAAEA;QAASI;QAAqBC;IAAkB;AAC3D"}
1
+ {"version":3,"sources":["../../../src/plugins/prometheus-time-series-query/query-editor-model.ts"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { useState } from 'react';\nimport { produce } from 'immer';\nimport { OptionsEditorProps } from '@perses-dev/plugin-system';\nimport { DurationString } from '@perses-dev/core';\nimport { PrometheusTimeSeriesQuerySpec } from './time-series-query-model';\n\nexport type PrometheusTimeSeriesQueryEditorProps = OptionsEditorProps<PrometheusTimeSeriesQuerySpec>;\n\n/**\n * A hook for managing the `query` state in PrometheusTimeSeriesQuerySpec. Returns the `query` value, along with\n * `onChange` and `onBlur` event handlers to the input. Keeps a local copy of the user's input and only syncs those\n * changes with the overall spec value once the input is blurred to prevent re-running queries in the panel's preview\n * every time the user types.\n */\nexport function useQueryState(props: PrometheusTimeSeriesQueryEditorProps): {\n query: string;\n handleQueryChange: (e: string) => void;\n handleQueryBlur: () => void;\n} {\n const { onChange, value } = props;\n\n // Local copy of the query's value\n const [query, setQuery] = useState(value.query);\n\n // This is basically \"getDerivedStateFromProps\" to make sure if spec's value changes external to this component,\n // we render with the latest value\n const [lastSyncedQuery, setLastSyncedQuery] = useState(value.query);\n if (value.query !== lastSyncedQuery) {\n setQuery(value.query);\n setLastSyncedQuery(value.query);\n }\n\n // Update our local state's copy as the user types\n const handleQueryChange = (e: string): void => {\n setQuery(e);\n };\n\n // Propagate changes to the query's value when the input is blurred to avoid constantly re-running queries in the\n // PanelPreview\n const handleQueryBlur = (): void => {\n setLastSyncedQuery(query);\n onChange(\n produce(value, (draft) => {\n draft.query = query;\n })\n );\n };\n\n return { query, handleQueryChange, handleQueryBlur };\n}\n\n/**\n * Hook to manage `seriesNameFormat` state to ensure panel preview does not rerender until text input is blurred\n */\nexport function useFormatState(props: PrometheusTimeSeriesQueryEditorProps): {\n format: string | undefined;\n handleFormatChange: (e: string) => void;\n handleFormatBlur: () => void;\n} {\n const { onChange, value } = props;\n\n // TODO: reusable hook or helper util instead of duplicating from useQueryState\n const [format, setFormat] = useState(value.seriesNameFormat);\n const [lastSyncedFormat, setLastSyncedFormat] = useState(value.seriesNameFormat);\n if (value.seriesNameFormat !== lastSyncedFormat) {\n setFormat(value.seriesNameFormat);\n setLastSyncedFormat(value.seriesNameFormat);\n }\n\n // Update our local state as the user types\n const handleFormatChange = (e: string): void => {\n setFormat(e);\n };\n\n // Propagate changes to the panel preview component when seriesNameFormat TextField is blurred\n const handleFormatBlur = (): void => {\n setLastSyncedFormat(format);\n onChange(\n produce(value, (draft) => {\n draft.seriesNameFormat = format;\n })\n );\n };\n\n return { format, handleFormatChange, handleFormatBlur };\n}\n\n/**\n * Hook to manage `minStep` state to ensure panel preview does not rerender until text input is blurred\n */\nexport function useMinStepState(props: PrometheusTimeSeriesQueryEditorProps): {\n minStep: string | undefined;\n handleMinStepChange: (e: DurationString) => void;\n handleMinStepBlur: () => void;\n} {\n const { onChange, value } = props;\n\n // TODO: reusable hook or helper util instead of duplicating from useQueryState\n const [minStep, setMinStep] = useState(value.minStep);\n const [lastSyncedMinStep, setLastSyncedMinStep] = useState(value.minStep);\n if (value.minStep !== lastSyncedMinStep) {\n setMinStep(value.minStep);\n setLastSyncedMinStep(value.minStep);\n }\n\n // Update our local state as the user types\n const handleMinStepChange = (e: DurationString): void => {\n setMinStep(e);\n };\n\n // Propagate changes to the panel preview component when minStep TextField is blurred\n const handleMinStepBlur = (): void => {\n setLastSyncedMinStep(minStep);\n onChange(\n produce(value, (draft) => {\n draft.minStep = minStep;\n })\n );\n };\n\n return { minStep, handleMinStepChange, handleMinStepBlur };\n}\n"],"names":["useState","produce","useQueryState","props","onChange","value","query","setQuery","lastSyncedQuery","setLastSyncedQuery","handleQueryChange","e","handleQueryBlur","draft","useFormatState","format","setFormat","seriesNameFormat","lastSyncedFormat","setLastSyncedFormat","handleFormatChange","handleFormatBlur","useMinStepState","minStep","setMinStep","lastSyncedMinStep","setLastSyncedMinStep","handleMinStepChange","handleMinStepBlur"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,QAAQ,QAAQ,QAAQ;AACjC,SAASC,OAAO,QAAQ,QAAQ;AAOhC;;;;;CAKC,GACD,OAAO,SAASC,cAAcC,KAA2C;IAKvE,MAAM,EAAEC,QAAQ,EAAEC,KAAK,EAAE,GA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IAE5B,+EAA+E;IAC/E,MAAM,CAACoB,SAASC,WAAW,GAAGxB,SAASK,MAAMkB,OAAO;IACpD,MAAM,CAACE,mBAAmBC,qBAAqB,GAAG1B,SAASK,MAAMkB,OAAO;IACxE,IAAIlB,MAAMkB,OAAO,KAAKE,mBAAmB;QACvCD,WAAWnB,MAAMkB,OAAO;QACxBG,qBAAqBrB,MAAMkB,OAAO;IACpC;IAEA,2CAA2C;IAC3C,MAAMI,sBAAsB,CAAChB;QAC3Ba,WAAWb;IACb;IAEA,qFAAqF;IACrF,MAAMiB,oBAAoB;QACxBF,qBAAqBH;QACrBnB,SACEH,QAAQI,OAAO,CAACQ;YACdA,MAAMU,OAAO,GAAGA;QAClB;IAEJ;IAEA,OAAO;QAAEA;QAASI;QAAqBC;IAAkB;AAC3D"}
@@ -0,0 +1,2 @@
1
+ export declare function replacePromBuiltinVariables(query: string, minStepMs: number, intervalMs: number): string;
2
+ //# sourceMappingURL=replace-prom-builtin-variables.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replace-prom-builtin-variables.d.ts","sourceRoot":"","sources":["../../../src/plugins/prometheus-time-series-query/replace-prom-builtin-variables.ts"],"names":[],"mappings":"AAyBA,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAcxG"}
@@ -0,0 +1,33 @@
1
+ // Copyright 2024 The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ import { replaceVariable } from '@perses-dev/plugin-system';
14
+ import { formatDuration, msToPrometheusDuration } from '@perses-dev/core';
15
+ /*
16
+ * Replace variable placeholders in a PromQL query
17
+
18
+ * @param query The base promQL expression that contains variable placeholders
19
+ * @param minStepMs the lower bound of the interval between data points, in milliseconds
20
+ * @param intervalMs the actual interval between data points, in milliseconds
21
+ *
22
+ * @returns a PromQL expression with variable placeholders replaced by their values
23
+ */ export function replacePromBuiltinVariables(query, minStepMs, intervalMs) {
24
+ let updatedQuery = replaceVariable(query, '__interval_ms', intervalMs.toString());
25
+ updatedQuery = replaceVariable(updatedQuery, '__interval', formatDuration(msToPrometheusDuration(intervalMs)));
26
+ // The $__rate_interval variable is meant to be used with the rate() promQL function.
27
+ // It is defined as max($__interval + Min step, 4 * Min step)
28
+ const rateIntervalMs = Math.max(intervalMs + minStepMs, 4 * minStepMs);
29
+ updatedQuery = replaceVariable(updatedQuery, '__rate_interval', formatDuration(msToPrometheusDuration(rateIntervalMs)));
30
+ return updatedQuery;
31
+ }
32
+
33
+ //# sourceMappingURL=replace-prom-builtin-variables.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/plugins/prometheus-time-series-query/replace-prom-builtin-variables.ts"],"sourcesContent":["// Copyright 2024 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { replaceVariable } from '@perses-dev/plugin-system';\nimport { formatDuration, msToPrometheusDuration } from '@perses-dev/core';\n\n/*\n * Replace variable placeholders in a PromQL query\n\n * @param query The base promQL expression that contains variable placeholders\n * @param minStepMs the lower bound of the interval between data points, in milliseconds\n * @param intervalMs the actual interval between data points, in milliseconds\n * \n * @returns a PromQL expression with variable placeholders replaced by their values\n */\nexport function replacePromBuiltinVariables(query: string, minStepMs: number, intervalMs: number): string {\n let updatedQuery = replaceVariable(query, '__interval_ms', intervalMs.toString());\n updatedQuery = replaceVariable(updatedQuery, '__interval', formatDuration(msToPrometheusDuration(intervalMs)));\n\n // The $__rate_interval variable is meant to be used with the rate() promQL function.\n // It is defined as max($__interval + Min step, 4 * Min step)\n const rateIntervalMs = Math.max(intervalMs + minStepMs, 4 * minStepMs);\n updatedQuery = replaceVariable(\n updatedQuery,\n '__rate_interval',\n formatDuration(msToPrometheusDuration(rateIntervalMs))\n );\n\n return updatedQuery;\n}\n"],"names":["replaceVariable","formatDuration","msToPrometheusDuration","replacePromBuiltinVariables","query","minStepMs","intervalMs","updatedQuery","toString","rateIntervalMs","Math","max"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,eAAe,QAAQ,4BAA4B;AAC5D,SAASC,cAAc,EAAEC,sBAAsB,QAAQ,mBAAmB;AAE1E;;;;;;;;CAQC,GACD,OAAO,SAASC,4BAA4BC,KAAa,EAAEC,SAAiB,EAAEC,UAAkB;IAC9F,IAAIC,eAAeP,gBAAgBI,OAAO,iBAAiBE,WAAWE,QAAQ;IAC9ED,eAAeP,gBAAgBO,cAAc,cAAcN,eAAeC,uBAAuBI;IAEjG,qFAAqF;IACrF,6DAA6D;IAC7D,MAAMG,iBAAiBC,KAAKC,GAAG,CAACL,aAAaD,WAAW,IAAIA;IAC5DE,eAAeP,gBACbO,cACA,mBACAN,eAAeC,uBAAuBO;IAGxC,OAAOF;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"prometheus-variables.d.ts","sourceRoot":"","sources":["../../src/plugins/prometheus-variables.tsx"],"names":[],"mappings":"AAYA,OAAO,EAML,cAAc,EAIf,MAAM,2BAA2B,CAAC;AAcnC,OAAO,EACL,mCAAmC,EACnC,oCAAoC,EACpC,+BAA+B,EAChC,MAAM,SAAS,CAAC;AAgMjB,eAAO,MAAM,4BAA4B,EAAE,cAAc,CAAC,mCAAmC,CAgB5F,CAAC;AAEF,eAAO,MAAM,6BAA6B,EAAE,cAAc,CAAC,oCAAoC,CA4B9F,CAAC;AAEF,eAAO,MAAM,wBAAwB,EAAE,cAAc,CAAC,+BAA+B,CAwBpF,CAAC"}
1
+ {"version":3,"file":"prometheus-variables.d.ts","sourceRoot":"","sources":["../../src/plugins/prometheus-variables.tsx"],"names":[],"mappings":"AAYA,OAAO,EAML,cAAc,EAIf,MAAM,2BAA2B,CAAC;AAenC,OAAO,EACL,mCAAmC,EACnC,oCAAoC,EACpC,+BAA+B,EAChC,MAAM,SAAS,CAAC;AAoMjB,eAAO,MAAM,4BAA4B,EAAE,cAAc,CAAC,mCAAmC,CAgB5F,CAAC;AAEF,eAAO,MAAM,6BAA6B,EAAE,cAAc,CAAC,oCAAoC,CA4B9F,CAAC;AAEF,eAAO,MAAM,wBAAwB,EAAE,cAAc,CAAC,+BAA+B,CAwBpF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/prometheus-variables.tsx"],"sourcesContent":["// Copyright 2024 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport {\n DatasourceSelect,\n DatasourceSelectProps,\n OptionsEditorProps,\n useDatasourceClient,\n VariableOption,\n VariablePlugin,\n parseVariables,\n replaceVariables,\n GetVariableOptionsContext,\n} from '@perses-dev/plugin-system';\nimport { FormControl, InputLabel, Stack, TextField } from '@mui/material';\nimport { produce } from 'immer';\nimport {\n DEFAULT_PROM,\n getPrometheusTimeRange,\n isDefaultPromSelector,\n isPrometheusDatasourceSelector,\n MatrixData,\n PROM_DATASOURCE_KIND,\n PrometheusClient,\n VectorData,\n} from '../model';\nimport { PromQLEditor } from '../components';\nimport {\n PrometheusLabelNamesVariableOptions,\n PrometheusLabelValuesVariableOptions,\n PrometheusPromQLVariableOptions,\n} from './types';\nimport { MatcherEditor } from './MatcherEditor';\n\nfunction PrometheusLabelValuesVariableEditor(props: OptionsEditorProps<PrometheusLabelValuesVariableOptions>) {\n const { onChange, value } = props;\n const { datasource } = value;\n const selectedDatasource = datasource ?? DEFAULT_PROM;\n\n const handleDatasourceChange: DatasourceSelectProps['onChange'] = (next) => {\n if (isPrometheusDatasourceSelector(next)) {\n onChange(\n produce(value, (draft) => {\n // If they're using the default, just omit the datasource prop (i.e. set to undefined)\n draft.datasource = isDefaultPromSelector(next) ? undefined : next;\n })\n );\n return;\n }\n\n throw new Error('Got unexpected non-Prometheus datasource selector');\n };\n\n return (\n <Stack spacing={2}>\n <FormControl margin=\"dense\">\n <InputLabel id=\"prom-datasource-label\">Prometheus Datasource</InputLabel>\n <DatasourceSelect\n datasourcePluginKind=\"PrometheusDatasource\"\n value={selectedDatasource}\n onChange={handleDatasourceChange}\n readOnly={props.isReadonly}\n labelId=\"prom-datasource-label\"\n label=\"Prometheus Datasource\"\n />\n </FormControl>\n <TextField\n label=\"Label Name\"\n required\n value={props.value.labelName}\n onChange={(e) => {\n props.onChange({ ...props.value, labelName: e.target.value });\n }}\n InputProps={{\n readOnly: props.isReadonly,\n }}\n />\n <MatcherEditor\n matchers={props.value.matchers ?? []}\n onChange={(e) => {\n props.onChange({ ...props.value, matchers: e });\n }}\n isReadonly={props.isReadonly}\n />\n </Stack>\n );\n}\n\nfunction PrometheusLabelNamesVariableEditor(props: OptionsEditorProps<PrometheusLabelNamesVariableOptions>) {\n const { onChange, value } = props;\n const { datasource } = value;\n const selectedDatasource = datasource ?? DEFAULT_PROM;\n\n const handleDatasourceChange: DatasourceSelectProps['onChange'] = (next) => {\n if (isPrometheusDatasourceSelector(next)) {\n onChange(\n produce(value, (draft) => {\n // If they're using the default, just omit the datasource prop (i.e. set to undefined)\n draft.datasource = isDefaultPromSelector(next) ? undefined : next;\n })\n );\n return;\n }\n\n throw new Error('Got unexpected non-Prometheus datasource selector');\n };\n\n return (\n <Stack spacing={2}>\n <FormControl margin=\"dense\">\n <InputLabel id=\"prom-datasource-label\">Prometheus Datasource</InputLabel>\n <DatasourceSelect\n datasourcePluginKind=\"PrometheusDatasource\"\n value={selectedDatasource}\n onChange={handleDatasourceChange}\n disabled={props.isReadonly}\n labelId=\"prom-datasource-label\"\n label=\"Prometheus Datasource\"\n />\n </FormControl>\n <MatcherEditor\n matchers={props.value.matchers ?? []}\n isReadonly={props.isReadonly}\n onChange={(e) => {\n props.onChange({ ...props.value, matchers: e });\n }}\n />\n </Stack>\n );\n}\n\nfunction PrometheusPromQLVariableEditor(props: OptionsEditorProps<PrometheusPromQLVariableOptions>) {\n const { onChange, value } = props;\n const { datasource } = value;\n const selectedDatasource = datasource ?? DEFAULT_PROM;\n\n const { data: client } = useDatasourceClient<PrometheusClient>(selectedDatasource);\n const promURL = client?.options.datasourceUrl;\n\n const handleDatasourceChange: DatasourceSelectProps['onChange'] = (next) => {\n if (isPrometheusDatasourceSelector(next)) {\n onChange(\n produce(value, (draft) => {\n // If they're using the default, just omit the datasource prop (i.e. set to undefined)\n draft.datasource = isDefaultPromSelector(next) ? undefined : next;\n })\n );\n return;\n }\n\n throw new Error('Got unexpected non-Prometheus datasource selector');\n };\n\n return (\n <Stack spacing={2}>\n <FormControl margin=\"dense\">\n <InputLabel id=\"prom-datasource-label\">Prometheus Datasource</InputLabel>\n <DatasourceSelect\n datasourcePluginKind={PROM_DATASOURCE_KIND}\n value={selectedDatasource}\n onChange={handleDatasourceChange}\n labelId=\"prom-datasource-label\"\n label=\"Prometheus Datasource\"\n disabled={props.isReadonly}\n />\n </FormControl>\n <PromQLEditor\n completeConfig={{ remote: { url: promURL } }}\n value={value.expr}\n datasource={selectedDatasource}\n onBlur={(event) => {\n props.onChange({ ...props.value, expr: event.target.textContent ?? '' });\n }}\n readOnly={props.isReadonly}\n width=\"100%\"\n />\n <TextField\n label=\"Label Name\"\n value={props.value.labelName}\n InputProps={{\n readOnly: props.isReadonly,\n }}\n onChange={(e) => {\n props.onChange({ ...props.value, labelName: e.target.value });\n }}\n />\n </Stack>\n );\n}\n\nfunction capturingMatrix(matrix: MatrixData, labelName: string): string[] {\n const captured = new Set<string>();\n for (const sample of matrix.result) {\n const value = sample.metric[labelName];\n if (value !== undefined) {\n captured.add(value);\n }\n }\n return Array.from(captured.values());\n}\n\nfunction capturingVector(vector: VectorData, labelName: string): string[] {\n const captured = new Set<string>();\n for (const sample of vector.result) {\n const value = sample.metric[labelName];\n if (value !== undefined) {\n captured.add(value);\n }\n }\n return Array.from(captured.values());\n}\n\n/**\n * Takes a list of strings and returns a list of VariableOptions\n */\nconst stringArrayToVariableOptions = (values?: string[]): VariableOption[] => {\n if (!values) return [];\n return values.map((value) => ({\n value,\n label: value,\n }));\n};\n\nexport const PrometheusLabelNamesVariable: VariablePlugin<PrometheusLabelNamesVariableOptions> = {\n getVariableOptions: async (spec: PrometheusLabelNamesVariableOptions, ctx: GetVariableOptionsContext) => {\n const client: PrometheusClient = await ctx.datasourceStore.getDatasourceClient(spec.datasource ?? DEFAULT_PROM);\n const match = spec.matchers ? spec.matchers.map((m) => replaceVariables(m, ctx.variables)) : undefined;\n const timeRange = getPrometheusTimeRange(ctx.timeRange);\n\n const { data: options } = await client.labelNames({ 'match[]': match, ...timeRange });\n return {\n data: stringArrayToVariableOptions(options),\n };\n },\n dependsOn: (spec: PrometheusLabelNamesVariableOptions) => {\n return { variables: spec.matchers?.map((m) => parseVariables(m)).flat() || [] };\n },\n OptionsEditorComponent: PrometheusLabelNamesVariableEditor,\n createInitialOptions: () => ({}),\n};\n\nexport const PrometheusLabelValuesVariable: VariablePlugin<PrometheusLabelValuesVariableOptions> = {\n getVariableOptions: async (spec: PrometheusLabelValuesVariableOptions, ctx: GetVariableOptionsContext) => {\n const pluginDef = spec;\n const client: PrometheusClient = await ctx.datasourceStore.getDatasourceClient(spec.datasource ?? DEFAULT_PROM);\n const match = pluginDef.matchers ? pluginDef.matchers.map((m) => replaceVariables(m, ctx.variables)) : undefined;\n\n const timeRange = getPrometheusTimeRange(ctx.timeRange);\n\n const { data: options } = await client.labelValues({\n labelName: replaceVariables(pluginDef.labelName, ctx.variables),\n 'match[]': match,\n ...timeRange,\n });\n return {\n data: stringArrayToVariableOptions(options),\n };\n },\n dependsOn: (spec: PrometheusLabelValuesVariableOptions) => {\n return {\n variables:\n spec.matchers\n ?.map((m) => parseVariables(m))\n .flat()\n .concat(parseVariables(spec.labelName)) || [],\n };\n },\n OptionsEditorComponent: PrometheusLabelValuesVariableEditor,\n createInitialOptions: () => ({ labelName: '' }),\n};\n\nexport const PrometheusPromQLVariable: VariablePlugin<PrometheusPromQLVariableOptions> = {\n getVariableOptions: async (spec: PrometheusPromQLVariableOptions, ctx: GetVariableOptionsContext) => {\n const client: PrometheusClient = await ctx.datasourceStore.getDatasourceClient(spec.datasource ?? DEFAULT_PROM);\n // TODO we may want to manage a range query as well.\n const { data: options } = await client.instantQuery({\n query: replaceVariables(spec.expr, ctx.variables),\n });\n const labelName = replaceVariables(spec.labelName, ctx.variables);\n let values: string[] = [];\n if (options?.resultType === 'matrix') {\n values = capturingMatrix(options, labelName);\n } else if (options?.resultType === 'vector') {\n values = capturingVector(options, labelName);\n }\n\n return {\n data: stringArrayToVariableOptions(values),\n };\n },\n dependsOn: (spec: PrometheusPromQLVariableOptions) => {\n return { variables: parseVariables(spec.expr).concat(parseVariables(spec.labelName)) };\n },\n OptionsEditorComponent: PrometheusPromQLVariableEditor,\n createInitialOptions: () => ({ expr: '', labelName: '' }),\n};\n"],"names":["DatasourceSelect","useDatasourceClient","parseVariables","replaceVariables","FormControl","InputLabel","Stack","TextField","produce","DEFAULT_PROM","getPrometheusTimeRange","isDefaultPromSelector","isPrometheusDatasourceSelector","PROM_DATASOURCE_KIND","PromQLEditor","MatcherEditor","PrometheusLabelValuesVariableEditor","props","onChange","value","datasource","selectedDatasource","handleDatasourceChange","next","draft","undefined","Error","spacing","margin","id","datasourcePluginKind","readOnly","isReadonly","labelId","label","required","labelName","e","target","InputProps","matchers","PrometheusLabelNamesVariableEditor","disabled","PrometheusPromQLVariableEditor","data","client","promURL","options","datasourceUrl","completeConfig","remote","url","expr","onBlur","event","textContent","width","capturingMatrix","matrix","captured","Set","sample","result","metric","add","Array","from","values","capturingVector","vector","stringArrayToVariableOptions","map","PrometheusLabelNamesVariable","getVariableOptions","spec","ctx","datasourceStore","getDatasourceClient","match","m","variables","timeRange","labelNames","dependsOn","flat","OptionsEditorComponent","createInitialOptions","PrometheusLabelValuesVariable","pluginDef","labelValues","concat","PrometheusPromQLVariable","instantQuery","query","resultType"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AACjC,SACEA,gBAAgB,EAGhBC,mBAAmB,EAGnBC,cAAc,EACdC,gBAAgB,QAEX,4BAA4B;AACnC,SAASC,WAAW,EAAEC,UAAU,EAAEC,KAAK,EAAEC,SAAS,QAAQ,gBAAgB;AAC1E,SAASC,OAAO,QAAQ,QAAQ;AAChC,SACEC,YAAY,EACZC,sBAAsB,EACtBC,qBAAqB,EACrBC,8BAA8B,EAE9BC,oBAAoB,QAGf,WAAW;AAClB,SAASC,YAAY,QAAQ,gBAAgB;AAM7C,SAASC,aAAa,QAAQ,kBAAkB;AAEhD,SAASC,oCAAoCC,KAA+D;IAC1G,MAAM,EAAEC,QAAQ,EAAEC,KAAK,EAAE,G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C,IAAIK,SAAS;QAChE,IAAIb,SAAmB,EAAE;QACzB,IAAIpB,CAAAA,oBAAAA,8BAAAA,QAAS+C,UAAU,MAAK,UAAU;YACpC3B,SAASV,gBAAgBV,SAASX;QACpC,OAAO,IAAIW,CAAAA,oBAAAA,8BAAAA,QAAS+C,UAAU,MAAK,UAAU;YAC3C3B,SAASC,gBAAgBrB,SAASX;QACpC;QAEA,OAAO;YACLQ,MAAM0B,6BAA6BH;QACrC;IACF;IACAgB,WAAW,CAACT;QACV,OAAO;YAAEM,WAAW9E,eAAewE,KAAKtB,IAAI,EAAEsC,MAAM,CAACxF,eAAewE,KAAKtC,SAAS;QAAG;IACvF;IACAiD,wBAAwB1C;IACxB2C,sBAAsB,IAAO,CAAA;YAAElC,MAAM;YAAIhB,WAAW;QAAG,CAAA;AACzD,EAAE"}
1
+ {"version":3,"sources":["../../src/plugins/prometheus-variables.tsx"],"sourcesContent":["// Copyright 2024 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport {\n DatasourceSelect,\n DatasourceSelectProps,\n OptionsEditorProps,\n useDatasourceClient,\n VariableOption,\n VariablePlugin,\n parseVariables,\n replaceVariables,\n GetVariableOptionsContext,\n} from '@perses-dev/plugin-system';\nimport { FormControl, InputLabel, Stack, TextField } from '@mui/material';\nimport { produce } from 'immer';\nimport { ReactElement } from 'react';\nimport {\n DEFAULT_PROM,\n getPrometheusTimeRange,\n isDefaultPromSelector,\n isPrometheusDatasourceSelector,\n MatrixData,\n PROM_DATASOURCE_KIND,\n PrometheusClient,\n VectorData,\n} from '../model';\nimport { PromQLEditor } from '../components';\nimport {\n PrometheusLabelNamesVariableOptions,\n PrometheusLabelValuesVariableOptions,\n PrometheusPromQLVariableOptions,\n} from './types';\nimport { MatcherEditor } from './MatcherEditor';\n\nfunction PrometheusLabelValuesVariableEditor(\n props: OptionsEditorProps<PrometheusLabelValuesVariableOptions>\n): ReactElement {\n const { onChange, value } = props;\n const { datasource } = value;\n const selectedDatasource = datasource ?? DEFAULT_PROM;\n\n const handleDatasourceChange: DatasourceSelectProps['onChange'] = (next) => {\n if (isPrometheusDatasourceSelector(next)) {\n onChange(\n produce(value, (draft) => {\n // If they're using the default, just omit the datasource prop (i.e. set to undefined)\n draft.datasource = isDefaultPromSelector(next) ? undefined : next;\n })\n );\n return;\n }\n\n throw new Error('Got unexpected non-Prometheus datasource selector');\n };\n\n return (\n <Stack spacing={2}>\n <FormControl margin=\"dense\">\n <InputLabel id=\"prom-datasource-label\">Prometheus Datasource</InputLabel>\n <DatasourceSelect\n datasourcePluginKind=\"PrometheusDatasource\"\n value={selectedDatasource}\n onChange={handleDatasourceChange}\n readOnly={props.isReadonly}\n labelId=\"prom-datasource-label\"\n label=\"Prometheus Datasource\"\n />\n </FormControl>\n <TextField\n label=\"Label Name\"\n required\n value={props.value.labelName}\n onChange={(e) => {\n props.onChange({ ...props.value, labelName: e.target.value });\n }}\n InputProps={{\n readOnly: props.isReadonly,\n }}\n />\n <MatcherEditor\n matchers={props.value.matchers ?? []}\n onChange={(e) => {\n props.onChange({ ...props.value, matchers: e });\n }}\n isReadonly={props.isReadonly}\n />\n </Stack>\n );\n}\n\nfunction PrometheusLabelNamesVariableEditor(\n props: OptionsEditorProps<PrometheusLabelNamesVariableOptions>\n): ReactElement {\n const { onChange, value } = props;\n const { datasource } = value;\n const selectedDatasource = datasource ?? DEFAULT_PROM;\n\n const handleDatasourceChange: DatasourceSelectProps['onChange'] = (next) => {\n if (isPrometheusDatasourceSelector(next)) {\n onChange(\n produce(value, (draft) => {\n // If they're using the default, just omit the datasource prop (i.e. set to undefined)\n draft.datasource = isDefaultPromSelector(next) ? undefined : next;\n })\n );\n return;\n }\n\n throw new Error('Got unexpected non-Prometheus datasource selector');\n };\n\n return (\n <Stack spacing={2}>\n <FormControl margin=\"dense\">\n <InputLabel id=\"prom-datasource-label\">Prometheus Datasource</InputLabel>\n <DatasourceSelect\n datasourcePluginKind=\"PrometheusDatasource\"\n value={selectedDatasource}\n onChange={handleDatasourceChange}\n disabled={props.isReadonly}\n labelId=\"prom-datasource-label\"\n label=\"Prometheus Datasource\"\n />\n </FormControl>\n <MatcherEditor\n matchers={props.value.matchers ?? []}\n isReadonly={props.isReadonly}\n onChange={(e) => {\n props.onChange({ ...props.value, matchers: e });\n }}\n />\n </Stack>\n );\n}\n\nfunction PrometheusPromQLVariableEditor(props: OptionsEditorProps<PrometheusPromQLVariableOptions>): ReactElement {\n const { onChange, value } = props;\n const { datasource } = value;\n const selectedDatasource = datasource ?? DEFAULT_PROM;\n\n const { data: client } = useDatasourceClient<PrometheusClient>(selectedDatasource);\n const promURL = client?.options.datasourceUrl;\n\n const handleDatasourceChange: DatasourceSelectProps['onChange'] = (next) => {\n if (isPrometheusDatasourceSelector(next)) {\n onChange(\n produce(value, (draft) => {\n // If they're using the default, just omit the datasource prop (i.e. set to undefined)\n draft.datasource = isDefaultPromSelector(next) ? undefined : next;\n })\n );\n return;\n }\n\n throw new Error('Got unexpected non-Prometheus datasource selector');\n };\n\n return (\n <Stack spacing={2}>\n <FormControl margin=\"dense\">\n <InputLabel id=\"prom-datasource-label\">Prometheus Datasource</InputLabel>\n <DatasourceSelect\n datasourcePluginKind={PROM_DATASOURCE_KIND}\n value={selectedDatasource}\n onChange={handleDatasourceChange}\n labelId=\"prom-datasource-label\"\n label=\"Prometheus Datasource\"\n disabled={props.isReadonly}\n />\n </FormControl>\n <PromQLEditor\n completeConfig={{ remote: { url: promURL } }}\n value={value.expr}\n datasource={selectedDatasource}\n onBlur={(event) => {\n props.onChange({ ...props.value, expr: event.target.textContent ?? '' });\n }}\n readOnly={props.isReadonly}\n width=\"100%\"\n />\n <TextField\n label=\"Label Name\"\n value={props.value.labelName}\n InputProps={{\n readOnly: props.isReadonly,\n }}\n onChange={(e) => {\n props.onChange({ ...props.value, labelName: e.target.value });\n }}\n />\n </Stack>\n );\n}\n\nfunction capturingMatrix(matrix: MatrixData, labelName: string): string[] {\n const captured = new Set<string>();\n for (const sample of matrix.result) {\n const value = sample.metric[labelName];\n if (value !== undefined) {\n captured.add(value);\n }\n }\n return Array.from(captured.values());\n}\n\nfunction capturingVector(vector: VectorData, labelName: string): string[] {\n const captured = new Set<string>();\n for (const sample of vector.result) {\n const value = sample.metric[labelName];\n if (value !== undefined) {\n captured.add(value);\n }\n }\n return Array.from(captured.values());\n}\n\n/**\n * Takes a list of strings and returns a list of VariableOptions\n */\nconst stringArrayToVariableOptions = (values?: string[]): VariableOption[] => {\n if (!values) return [];\n return values.map((value) => ({\n value,\n label: value,\n }));\n};\n\nexport const PrometheusLabelNamesVariable: VariablePlugin<PrometheusLabelNamesVariableOptions> = {\n getVariableOptions: async (spec: PrometheusLabelNamesVariableOptions, ctx: GetVariableOptionsContext) => {\n const client: PrometheusClient = await ctx.datasourceStore.getDatasourceClient(spec.datasource ?? DEFAULT_PROM);\n const match = spec.matchers ? spec.matchers.map((m) => replaceVariables(m, ctx.variables)) : undefined;\n const timeRange = getPrometheusTimeRange(ctx.timeRange);\n\n const { data: options } = await client.labelNames({ 'match[]': match, ...timeRange });\n return {\n data: stringArrayToVariableOptions(options),\n };\n },\n dependsOn: (spec: PrometheusLabelNamesVariableOptions) => {\n return { variables: spec.matchers?.map((m) => parseVariables(m)).flat() || [] };\n },\n OptionsEditorComponent: PrometheusLabelNamesVariableEditor,\n createInitialOptions: () => ({}),\n};\n\nexport const PrometheusLabelValuesVariable: VariablePlugin<PrometheusLabelValuesVariableOptions> = {\n getVariableOptions: async (spec: PrometheusLabelValuesVariableOptions, ctx: GetVariableOptionsContext) => {\n const pluginDef = spec;\n const client: PrometheusClient = await ctx.datasourceStore.getDatasourceClient(spec.datasource ?? DEFAULT_PROM);\n const match = pluginDef.matchers ? pluginDef.matchers.map((m) => replaceVariables(m, ctx.variables)) : undefined;\n\n const timeRange = getPrometheusTimeRange(ctx.timeRange);\n\n const { data: options } = await client.labelValues({\n labelName: replaceVariables(pluginDef.labelName, ctx.variables),\n 'match[]': match,\n ...timeRange,\n });\n return {\n data: stringArrayToVariableOptions(options),\n };\n },\n dependsOn: (spec: PrometheusLabelValuesVariableOptions) => {\n return {\n variables:\n spec.matchers\n ?.map((m) => parseVariables(m))\n .flat()\n .concat(parseVariables(spec.labelName)) || [],\n };\n },\n OptionsEditorComponent: PrometheusLabelValuesVariableEditor,\n createInitialOptions: () => ({ labelName: '' }),\n};\n\nexport const PrometheusPromQLVariable: VariablePlugin<PrometheusPromQLVariableOptions> = {\n getVariableOptions: async (spec: PrometheusPromQLVariableOptions, ctx: GetVariableOptionsContext) => {\n const client: PrometheusClient = await ctx.datasourceStore.getDatasourceClient(spec.datasource ?? DEFAULT_PROM);\n // TODO we may want to manage a range query as well.\n const { data: options } = await client.instantQuery({\n query: replaceVariables(spec.expr, ctx.variables),\n });\n const labelName = replaceVariables(spec.labelName, ctx.variables);\n let values: string[] = [];\n if (options?.resultType === 'matrix') {\n values = capturingMatrix(options, labelName);\n } else if (options?.resultType === 'vector') {\n values = capturingVector(options, labelName);\n }\n\n return {\n data: stringArrayToVariableOptions(values),\n };\n },\n dependsOn: (spec: PrometheusPromQLVariableOptions) => {\n return { variables: parseVariables(spec.expr).concat(parseVariables(spec.labelName)) };\n },\n OptionsEditorComponent: PrometheusPromQLVariableEditor,\n createInitialOptions: () => ({ expr: '', labelName: '' }),\n};\n"],"names":["DatasourceSelect","useDatasourceClient","parseVariables","replaceVariables","FormControl","InputLabel","Stack","TextField","produce","DEFAULT_PROM","getPrometheusTimeRange","isDefaultPromSelector","isPrometheusDatasourceSelector","PROM_DATASOURCE_KIND","PromQLEditor","MatcherEditor","PrometheusLabelValuesVariableEditor","props","onChange","value","datasource","selectedDatasource","handleDatasourceChange","next","draft","undefined","Error","spacing","margin","id","datasourcePluginKind","readOnly","isReadonly","labelId","label","required","labelName","e","target","InputProps","matchers","PrometheusLabelNamesVariableEditor","disabled","PrometheusPromQLVariableEditor","data","client","promURL","options","datasourceUrl","completeConfig","remote","url","expr","onBlur","event","textContent","width","capturingMatrix","matrix","captured","Set","sample","result","metric","add","Array","from","values","capturingVector","vector","stringArrayToVariableOptions","map","PrometheusLabelNamesVariable","getVariableOptions","spec","ctx","datasourceStore","getDatasourceClient","match","m","variables","timeRange","labelNames","dependsOn","flat","OptionsEditorComponent","createInitialOptions","PrometheusLabelValuesVariable","pluginDef","labelValues","concat","PrometheusPromQLVariable","instantQuery","query","resultType"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AACjC,SACEA,gBAAgB,EAGhBC,mBAAmB,EAGnBC,cAAc,EACdC,gBAAgB,QAEX,4BAA4B;AACnC,SAASC,WAAW,EAAEC,UAAU,EAAEC,KAAK,EAAEC,SAAS,QAAQ,gBAAgB;AAC1E,SAASC,OAAO,QAAQ,QAAQ;AAEhC,SACEC,YAAY,EACZC,sBAAsB,EACtBC,qBAAqB,EACrBC,8BAA8B,EAE9BC,oBAAoB,QAGf,WAAW;AAClB,SAASC,YAAY,QAAQ,gBAAgB;AAM7C,SAASC,aAAa,QAAQ,kBAAkB;AAEhD,SAASC,oCACPC,KAA+D;IAE/D,MAAM,EAAEC,QAAQ,EAAEC,KAAK,EAAE,GAAGF;IAC5B,MAAM,EAAEG,UAAU,EAAE,GAAGD;IACvB,MAAME,qBAAqBD,uBAAAA,wBAAAA,aAAcX;IAEzC,MAAMa,yBAA4D,CAACC;QACjE,IAAIX,+BAA+BW,OAAO;YACxCL,SACEV,QAAQW,OAAO,CAACK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AAS+C,UAAU,MAAK,UAAU;YAC3C3B,SAASC,gBAAgBrB,SAASX;QACpC;QAEA,OAAO;YACLQ,MAAM0B,6BAA6BH;QACrC;IACF;IACAgB,WAAW,CAACT;QACV,OAAO;YAAEM,WAAW9E,eAAewE,KAAKtB,IAAI,EAAEsC,MAAM,CAACxF,eAAewE,KAAKtC,SAAS;QAAG;IACvF;IACAiD,wBAAwB1C;IACxB2C,sBAAsB,IAAO,CAAA;YAAElC,MAAM;YAAIhB,WAAW;QAAG,CAAA;AACzD,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"variable.d.ts","sourceRoot":"","sources":["../../src/plugins/variable.tsx"],"names":[],"mappings":"AAaA,OAAO,EAAE,cAAc,EAAE,cAAc,EAAsB,MAAM,2BAA2B,CAAC;AAG/F,KAAK,gBAAgB,GAAG,MAAM,GAAG,cAAc,CAAC;AAEhD,KAAK,yBAAyB,GAAG;IAC/B,MAAM,EAAE,gBAAgB,EAAE,CAAC;CAC5B,CAAC;AAmDF,eAAO,MAAM,kBAAkB,EAAE,cAAc,CAAC,yBAAyB,CAiBxE,CAAC"}
1
+ {"version":3,"file":"variable.d.ts","sourceRoot":"","sources":["../../src/plugins/variable.tsx"],"names":[],"mappings":"AAaA,OAAO,EAAE,cAAc,EAAE,cAAc,EAAsB,MAAM,2BAA2B,CAAC;AAI/F,KAAK,gBAAgB,GAAG,MAAM,GAAG,cAAc,CAAC;AAEhD,KAAK,yBAAyB,GAAG;IAC/B,MAAM,EAAE,gBAAgB,EAAE,CAAC;CAC5B,CAAC;AAmDF,eAAO,MAAM,kBAAkB,EAAE,cAAc,CAAC,yBAAyB,CAiBxE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/variable.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { VariablePlugin, VariableOption, OptionsEditorProps } from '@perses-dev/plugin-system';\nimport { Autocomplete, TextField } from '@mui/material';\n\ntype StaticListOption = string | VariableOption;\n\ntype StaticListVariableOptions = {\n values: StaticListOption[];\n};\n\nfunction StaticListVariableOptionEditor(props: OptionsEditorProps<StaticListVariableOptions>) {\n const value = props.value.values.map((v) => {\n if (typeof v === 'string') {\n return v;\n } else {\n return v.value;\n }\n });\n\n const onChange = (__: unknown, value: string[]) => {\n props.onChange({\n values: value.map((v) => {\n return { value: v, label: v };\n }),\n });\n };\n\n return (\n <div>\n <Autocomplete\n onPaste={(e) => {\n // Append new values on paste\n const v = e.clipboardData.getData('text/plain');\n if (v) {\n const values = v.split(',');\n onChange(null, value.concat(values));\n e.preventDefault();\n }\n }}\n multiple\n value={value}\n onChange={onChange}\n options={[]}\n freeSolo\n clearOnBlur\n readOnly={props.isReadonly}\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Values\"\n placeholder=\"Values\"\n helperText='Type new value then press \"Enter\" to add.'\n />\n )}\n />\n </div>\n );\n}\n\nexport const StaticListVariable: VariablePlugin<StaticListVariableOptions> = {\n getVariableOptions: async (spec) => {\n const values = spec.values?.map((v) => {\n if (typeof v === 'string') {\n return { label: v, value: v };\n }\n return v;\n });\n return {\n data: values,\n };\n },\n dependsOn: () => {\n return { variables: [] };\n },\n OptionsEditorComponent: StaticListVariableOptionEditor,\n createInitialOptions: () => ({ values: [] }),\n};\n"],"names":["Autocomplete","TextField","StaticListVariableOptionEditor","props","value","values","map","v","onChange","__","label","div","onPaste","e","clipboardData","getData","split","concat","preventDefault","multiple","options","freeSolo","clearOnBlur","readOnly","isReadonly","renderInput","params","placeholder","helperText","StaticListVariable","getVariableOptions","spec","data","dependsOn","variables","OptionsEdit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B,IAAI,OAAOA,MAAM,UAAU;gBACzB,OAAO;oBAAEG,OAAOH;oBAAGH,OAAOG;gBAAE;YAC9B;YACA,OAAOA;QACT;QACA,OAAO;YACLyB,MAAM3B;QACR;IACF;IACA4B,WAAW;QACT,OAAO;YAAEC,WAAW,EAAE;QAAC;IACzB;IACAC,wBAAwBjC;IACxBkC,sBAAsB,IAAO,CAAA;YAAE/B,QAAQ,EAAE;QAAC,CAAA;AAC5C,EAAE"}
1
+ {"version":3,"sources":["../../src/plugins/variable.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { VariablePlugin, VariableOption, OptionsEditorProps } from '@perses-dev/plugin-system';\nimport { Autocomplete, TextField } from '@mui/material';\nimport { ReactElement } from 'react';\n\ntype StaticListOption = string | VariableOption;\n\ntype StaticListVariableOptions = {\n values: StaticListOption[];\n};\n\nfunction StaticListVariableOptionEditor(props: OptionsEditorProps<StaticListVariableOptions>): ReactElement {\n const value = props.value.values.map((v) => {\n if (typeof v === 'string') {\n return v;\n } else {\n return v.value;\n }\n });\n\n const onChange = (__: unknown, value: string[]): void => {\n props.onChange({\n values: value.map((v) => {\n return { value: v, label: v };\n }),\n });\n };\n\n return (\n <div>\n <Autocomplete\n onPaste={(e) => {\n // Append new values on paste\n const v = e.clipboardData.getData('text/plain');\n if (v) {\n const values = v.split(',');\n onChange(null, value.concat(values));\n e.preventDefault();\n }\n }}\n multiple\n value={value}\n onChange={onChange}\n options={[]}\n freeSolo\n clearOnBlur\n readOnly={props.isReadonly}\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Values\"\n placeholder=\"Values\"\n helperText='Type new value then press \"Enter\" to add.'\n />\n )}\n />\n </div>\n );\n}\n\nexport const StaticListVariable: VariablePlugin<StaticListVariableOptions> = {\n getVariableOptions: async (spec) => {\n const values = spec.values?.map((v) => {\n if (typeof v === 'string') {\n return { label: v, value: v };\n }\n return v;\n });\n return {\n data: values,\n };\n },\n dependsOn: () => {\n return { variables: [] };\n },\n OptionsEditorComponent: StaticListVariableOptionEditor,\n createInitialOptions: () => ({ values: [] }),\n};\n"],"names":["Autocomplete","TextField","StaticListVariableOptionEditor","props","value","values","map","v","onChange","__","label","div","onPaste","e","clipboardData","getData","split","concat","preventDefault","multiple","options","freeSolo","clearOnBlur","readOnly","isReadonly","renderInput","params","placeholder","helperText","StaticListVariable","getVariableOptions","spec","data","dependsOn","variables","OptionsEditorComponent","createInitialOptions"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAGjC,SAASA,YAAY,EAAEC,SAAS,QAAQ,gBAAgB;AASxD,SAASC,+BAA+BC,KAAoD;IAC1F,MAAMC,QAAQD,MAAMC,KAAK,CAACC,MAAM,CAACC,GAAG,CAAC,CAACC;QACpC,IAAI,OAAOA,MAAM,UAAU;YACzB,OAAOA;QACT,OAAO;YACL,OAAOA,EAAEH,KAAK;QAChB;IACF;IAEA,MAAMI,WAAW,CAACC,IAAaL;QAC7BD,MAAMK,QAAQ,CAAC;YACbH,QAAQD,MAAME,GAAG,CAAC,CAACC;gBACjB,OAAO;oBAAEH,OAAOG;oBAAGG,OAAOH;gBAAE;YAC9B;QACF;IACF;IAEA,qBACE,KAACI;kBACC,cAAA,KAACX;YACCY,SAAS,CAACC;gBACR,6BAA6B;gBAC7B,MAAMN,IAAIM,EAAEC,aAAa,CAACC,OAAO,CAAC;gBACl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AAE,cAAc,CAAC,EAAE,OAAO,CAAA;CAAO,UAkBtD;AAKD,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM;;;EAQjG"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAOlD,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,EAAE,YAAY,EAAE,YAAY,GAAG,MAAM,CAMxF;AAyBD,wBAAgB,+BAA+B,CAC7C,YAAY,EAAE;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB,EACD,EAAE,cAAc,EAAE,GAAE;IAAE,cAAc,CAAC,EAAE,OAAO,CAAA;CAAO,GACpD,MAAM,CAiBR;AAKD,wBAAgB,gCAAgC,CAC9C,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,GACjB;IACD,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;CACvB,CAQA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/utils.ts"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { Metric } from '../model/api-types';\n\n/**\n * Types for metric labels, used in seriesNameFormat implementation\n */\nexport type SeriesLabels = Record<string, string>;\n\n/*\n * Formatter used for series name display in legends and tooltips.\n * Regex replaces label {{ name }} with resolved label value.\n * If no resolved value, return empty string instead of the token inside double curly braces.\n */\nexport function formatSeriesName(inputFormat: string, seriesLabels: SeriesLabels): string {\n const resolveLabelsRegex = /\\{\\{\\s*(.+?)\\s*\\}\\}/g;\n return inputFormat.replace(resolveLabelsRegex, (_match, token) => {\n const resolvedValue = seriesLabels[token] ?? '';\n return resolvedValue;\n });\n}\n\n/*\n * Stringifies object of labels into valid PromQL for querying metric by label\n */\nfunction stringifyPrometheusMetricLabels(labels: { [key: string]: unknown }, removeExprWrap?: boolean) {\n const labelStrings: string[] = [];\n Object.keys(labels)\n .sort()\n .forEach((labelName) => {\n const labelValue = labels[labelName];\n if (labelValue !== undefined) {\n if (removeExprWrap) {\n labelStrings.push(`\"${labelName}\":\"${labelValue}\"`);\n } else {\n labelStrings.push(`${labelName}=\"${labelValue}\"`);\n }\n }\n });\n return `{${labelStrings.join(',')}}`;\n}\n\n/*\n * Metric labels formatter which checks for __name__ and outputs valid PromQL for series name\n */\nexport function getUniqueKeyForPrometheusResult(\n metricLabels: {\n [key: string]: string;\n },\n { removeExprWrap }: { removeExprWrap?: boolean } = {}\n) {\n const metricNameKey = '__name__';\n if (Object.prototype.hasOwnProperty.call(metricLabels, metricNameKey)) {\n const stringifiedLabels = stringifyPrometheusMetricLabels(\n {\n ...metricLabels,\n [metricNameKey]: undefined,\n },\n removeExprWrap\n );\n if (removeExprWrap) {\n return `${stringifiedLabels}`;\n } else {\n return `${metricLabels[metricNameKey]}${stringifiedLabels}`;\n }\n }\n return stringifyPrometheusMetricLabels(metricLabels, removeExprWrap);\n}\n\n/*\n * Determine human-readable series name to be used in legend and tooltip\n */\nexport function getFormattedPrometheusSeriesName(query: string, metric: Metric, formatter?: string) {\n // Name the series after the metric labels by default.\n const name = getUniqueKeyForPrometheusResult(metric);\n\n // Query editor allows you to define an optional seriesNameFormat property.\n // This controls the regex used to customize legend and tooltip display.\n const formattedName = formatter ? formatSeriesName(formatter, metric) : name;\n return { name, formattedName };\n}\n"],"names":["formatSeriesName","inputFormat","seriesLabels","resolveLabelsRegex","replace","_match","token","resolvedValue","stringifyPrometheusMetricLabels","labels","removeExprWrap","labelStrings","Object","keys","sort","forEach","labelName","labelValue","undefined","push","join","getUniqueKeyForPrometheusResult","metricLabels","metricNameKey","prototype","hasOwnProperty","call","stringifiedLabels","getFormattedPrometheusSeriesName","query","metric","formatter","name","formattedName"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AASjC;;;;CAIC,GACD,OAAO,SAASA,iBAAiBC,WAAmB,EAAEC,YAA0B;IAC9E,MAAMC,qBAAqB;IAC3B,OAAOF,YAAYG,OAAO,CAACD,oBAAoB,CAACE,QAAQC;YAChCJ;QAAtB,MAAMK,gBAAgBL,CAAAA,sBAAAA,YAAY,CAACI,MAAM,cAAnBJ,iCAAAA,sBAAuB;QAC7C,OAAOK;IACT;AACF;AAEA;;CAEC,GACD,SAASC,gCAAgCC,MAAkC,EAAEC,cAAwB;IACnG,MAAMC,eAAyB,EAAE;IACjCC,OAAOC,IAAI,CAACJ,QACTK,IAAI,GACJC,OAAO,CAAC,CAACC;QACR,MAAMC,aAAaR,MAAM,CAACO,UAAU;QACpC,IAAIC,eAAeC,WAAW;YAC5B,IAAIR,gBAAgB;gBAClBC,aAAaQ,IAAI,CAAC,CAAC,CAAC,EAAEH,UAAU,GAAG,EAAEC,WAAW,CAAC,CAAC;YACpD,OAAO;gBACLN,aAAaQ,IAAI,CAAC,CAAC,EAAEH,UAAU,EAAE,EAAEC,WAAW,CAAC,CAAC;YAClD;QACF;IACF;IACF,OAAO,CAAC,CAAC,EAAEN,aAAaS,IAAI,CAAC,KAAK,CAAC,CAAC;AACtC;AAEA;;CAEC,GACD,OAAO,SAASC,gCACdC,YAEC,EACD,EAAEZ,cAAc,EAAgC,GAAG,CAAC,CAAC;IAErD,MAAMa,gBAAgB;IACtB,IAAIX,OAAOY,SAAS,CAACC,cAAc,CAACC,IAAI,CAACJ,cAAcC,gBAAgB;QACrE,MAAMI,oBAAoBnB,gCACxB;YACE,GAAGc,YAAY;YACf,CAACC,cAAc,EAAEL;QACnB,GACAR;QAEF,IAAIA,gBAAgB;YAClB,OAAO,CAAC,EAAEiB,kBAAkB,CAAC;QAC/B,OAAO;YACL,OAAO,CAAC,EAAEL,YAAY,CAACC,cAAc,CAAC,EAAEI,kBAAkB,CAAC;QAC7D;IACF;IACA,OAAOnB,gCAAgCc,cAAcZ;AACvD;AAEA;;CAEC,GACD,OAAO,SAASkB,iCAAiCC,KAAa,EAAEC,MAAc,EAAEC,SAAkB;IAChG,sDAAsD;IACtD,MAAMC,OAAOX,gCAAgCS;IAE7C,2EAA2E;IAC3E,wEAAwE;IACxE,MAAMG,gBAAgBF,YAAY/B,iBAAiB+B,WAAWD,UAAUE;IACxE,OAAO;QAAEA;QAAMC;IAAc;AAC/B"}
1
+ {"version":3,"sources":["../../src/utils/utils.ts"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { Metric } from '../model/api-types';\n\n/**\n * Types for metric labels, used in seriesNameFormat implementation\n */\nexport type SeriesLabels = Record<string, string>;\n\n/*\n * Formatter used for series name display in legends and tooltips.\n * Regex replaces label {{ name }} with resolved label value.\n * If no resolved value, return empty string instead of the token inside double curly braces.\n */\nexport function formatSeriesName(inputFormat: string, seriesLabels: SeriesLabels): string {\n const resolveLabelsRegex = /\\{\\{\\s*(.+?)\\s*\\}\\}/g;\n return inputFormat.replace(resolveLabelsRegex, (_match, token) => {\n const resolvedValue = seriesLabels[token] ?? '';\n return resolvedValue;\n });\n}\n\n/*\n * Stringifies object of labels into valid PromQL for querying metric by label\n */\nfunction stringifyPrometheusMetricLabels(labels: { [key: string]: unknown }, removeExprWrap?: boolean): string {\n const labelStrings: string[] = [];\n Object.keys(labels)\n .sort()\n .forEach((labelName) => {\n const labelValue = labels[labelName];\n if (labelValue !== undefined) {\n if (removeExprWrap) {\n labelStrings.push(`\"${labelName}\":\"${labelValue}\"`);\n } else {\n labelStrings.push(`${labelName}=\"${labelValue}\"`);\n }\n }\n });\n return `{${labelStrings.join(',')}}`;\n}\n\n/*\n * Metric labels formatter which checks for __name__ and outputs valid PromQL for series name\n */\nexport function getUniqueKeyForPrometheusResult(\n metricLabels: {\n [key: string]: string;\n },\n { removeExprWrap }: { removeExprWrap?: boolean } = {}\n): string {\n const metricNameKey = '__name__';\n if (Object.prototype.hasOwnProperty.call(metricLabels, metricNameKey)) {\n const stringifiedLabels = stringifyPrometheusMetricLabels(\n {\n ...metricLabels,\n [metricNameKey]: undefined,\n },\n removeExprWrap\n );\n if (removeExprWrap) {\n return `${stringifiedLabels}`;\n } else {\n return `${metricLabels[metricNameKey]}${stringifiedLabels}`;\n }\n }\n return stringifyPrometheusMetricLabels(metricLabels, removeExprWrap);\n}\n\n/*\n * Determine human-readable series name to be used in legend and tooltip\n */\nexport function getFormattedPrometheusSeriesName(\n query: string,\n metric: Metric,\n formatter?: string\n): {\n name: string;\n formattedName: string;\n} {\n // Name the series after the metric labels by default.\n const name = getUniqueKeyForPrometheusResult(metric);\n\n // Query editor allows you to define an optional seriesNameFormat property.\n // This controls the regex used to customize legend and tooltip display.\n const formattedName = formatter ? formatSeriesName(formatter, metric) : name;\n return { name, formattedName };\n}\n"],"names":["formatSeriesName","inputFormat","seriesLabels","resolveLabelsRegex","replace","_match","token","resolvedValue","stringifyPrometheusMetricLabels","labels","removeExprWrap","labelStrings","Object","keys","sort","forEach","labelName","labelValue","undefined","push","join","getUniqueKeyForPrometheusResult","metricLabels","metricNameKey","prototype","hasOwnProperty","call","stringifiedLabels","getFormattedPrometheusSeriesName","query","metric","formatter","name","formattedName"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AASjC;;;;CAIC,GACD,OAAO,SAASA,iBAAiBC,WAAmB,EAAEC,YAA0B;IAC9E,MAAMC,qBAAqB;IAC3B,OAAOF,YAAYG,OAAO,CAACD,oBAAoB,CAACE,QAAQC;YAChCJ;QAAtB,MAAMK,gBAAgBL,CAAAA,sBAAAA,YAAY,CAACI,MAAM,cAAnBJ,iCAAAA,sBAAuB;QAC7C,OAAOK;IACT;AACF;AAEA;;CAEC,GACD,SAASC,gCAAgCC,MAAkC,EAAEC,cAAwB;IACnG,MAAMC,eAAyB,EAAE;IACjCC,OAAOC,IAAI,CAACJ,QACTK,IAAI,GACJC,OAAO,CAAC,CAACC;QACR,MAAMC,aAAaR,MAAM,CAACO,UAAU;QACpC,IAAIC,eAAeC,WAAW;YAC5B,IAAIR,gBAAgB;gBAClBC,aAAaQ,IAAI,CAAC,CAAC,CAAC,EAAEH,UAAU,GAAG,EAAEC,WAAW,CAAC,CAAC;YACpD,OAAO;gBACLN,aAAaQ,IAAI,CAAC,CAAC,EAAEH,UAAU,EAAE,EAAEC,WAAW,CAAC,CAAC;YAClD;QACF;IACF;IACF,OAAO,CAAC,CAAC,EAAEN,aAAaS,IAAI,CAAC,KAAK,CAAC,CAAC;AACtC;AAEA;;CAEC,GACD,OAAO,SAASC,gCACdC,YAEC,EACD,EAAEZ,cAAc,EAAgC,GAAG,CAAC,CAAC;IAErD,MAAMa,gBAAgB;IACtB,IAAIX,OAAOY,SAAS,CAACC,cAAc,CAACC,IAAI,CAACJ,cAAcC,gBAAgB;QACrE,MAAMI,oBAAoBnB,gCACxB;YACE,GAAGc,YAAY;YACf,CAACC,cAAc,EAAEL;QACnB,GACAR;QAEF,IAAIA,gBAAgB;YAClB,OAAO,CAAC,EAAEiB,kBAAkB,CAAC;QAC/B,OAAO;YACL,OAAO,CAAC,EAAEL,YAAY,CAACC,cAAc,CAAC,EAAEI,kBAAkB,CAAC;QAC7D;IACF;IACA,OAAOnB,gCAAgCc,cAAcZ;AACvD;AAEA;;CAEC,GACD,OAAO,SAASkB,iCACdC,KAAa,EACbC,MAAc,EACdC,SAAkB;IAKlB,sDAAsD;IACtD,MAAMC,OAAOX,gCAAgCS;IAE7C,2EAA2E;IAC3E,wEAAwE;IACxE,MAAMG,gBAAgBF,YAAY/B,iBAAiB+B,WAAWD,UAAUE;IACxE,OAAO;QAAEA;QAAMC;IAAc;AAC/B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@perses-dev/prometheus-plugin",
3
- "version": "0.49.0",
3
+ "version": "0.50.0-rc.0",
4
4
  "description": "Prometheus plugin for Perses",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/perses/perses/blob/main/README.md",
@@ -31,9 +31,9 @@
31
31
  "dependencies": {
32
32
  "@lezer/highlight": "^1.0.0",
33
33
  "@lezer/lr": "^1.2.0",
34
- "@perses-dev/components": "0.49.0",
35
- "@perses-dev/core": "0.49.0",
36
- "@perses-dev/plugin-system": "0.49.0",
34
+ "@perses-dev/components": "0.50.0-rc.0",
35
+ "@perses-dev/core": "0.50.0-rc.0",
36
+ "@perses-dev/plugin-system": "0.50.0-rc.0",
37
37
  "@prometheus-io/codemirror-promql": "^0.43.0",
38
38
  "@uiw/react-codemirror": "^4.19.1",
39
39
  "date-fns": "^2.28.0",
@@ -41,7 +41,8 @@
41
41
  "react-hook-form": "^7.46.1"
42
42
  },
43
43
  "peerDependencies": {
44
- "react": "^17.0.2 || ^18.0.0"
44
+ "react": "^17.0.2 || ^18.0.0",
45
+ "@tanstack/react-query": "^4.7.1"
45
46
  },
46
47
  "files": [
47
48
  "dist",