@perses-dev/prometheus-plugin 0.24.0 → 0.26.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.
package/dist/cjs/index.js CHANGED
@@ -32,3 +32,16 @@ const _prometheusTimeSeriesQuery = require("./plugins/prometheus-time-series-que
32
32
  const _variable = require("./plugins/variable");
33
33
  const _prometheusVariables = require("./plugins/prometheus-variables");
34
34
  const _prometheusDatasource = require("./plugins/prometheus-datasource");
35
+ _exportStar(require("./model/prometheus-client"), exports);
36
+ _exportStar(require("./model/api-types"), exports);
37
+ function _exportStar(from, to) {
38
+ Object.keys(from).forEach(function(k) {
39
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) Object.defineProperty(to, k, {
40
+ enumerable: true,
41
+ get: function() {
42
+ return from[k];
43
+ }
44
+ });
45
+ });
46
+ return from;
47
+ }
@@ -24,7 +24,8 @@ _export(exports, {
24
24
  instantQuery: ()=>instantQuery,
25
25
  rangeQuery: ()=>rangeQuery,
26
26
  labelNames: ()=>labelNames,
27
- labelValues: ()=>labelValues
27
+ labelValues: ()=>labelValues,
28
+ fetchResults: ()=>fetchResults
28
29
  });
29
30
  const _core = require("@perses-dev/core");
30
31
  function instantQuery(params, queryOptions) {
@@ -63,7 +64,7 @@ function fetchWithPost(apiURI, params, queryOptions) {
63
64
  },
64
65
  body: createSearchParams(params)
65
66
  };
66
- return (0, _core.fetchJson)(url, init);
67
+ return fetchResults(url, init);
67
68
  }
68
69
  /**
69
70
  * Creates URLSearchParams from a request params object.
@@ -86,3 +87,11 @@ function fetchWithPost(apiURI, params, queryOptions) {
86
87
  }
87
88
  return searchParams;
88
89
  }
90
+ async function fetchResults(...args) {
91
+ const response = await (0, _core.fetch)(...args);
92
+ const json = await response.json();
93
+ return {
94
+ ...json,
95
+ rawResponse: response
96
+ };
97
+ }
@@ -22,7 +22,7 @@ const _model = require("../model");
22
22
  /**
23
23
  * Creates a PrometheusClient for a specific datasource spec.
24
24
  */ const createClient = (spec, options)=>{
25
- const { direct_url , headers } = spec;
25
+ const { direct_url , headers: specHeaders } = spec;
26
26
  const { proxyUrl } = options;
27
27
  // Use the direct URL if specified, but fallback to the proxyUrl by default if not specified
28
28
  const datasourceUrl = direct_url !== null && direct_url !== void 0 ? direct_url : proxyUrl;
@@ -34,21 +34,21 @@ const _model = require("../model");
34
34
  options: {
35
35
  datasourceUrl
36
36
  },
37
- instantQuery: (params)=>(0, _model.instantQuery)(params, {
37
+ instantQuery: (params, headers)=>(0, _model.instantQuery)(params, {
38
38
  datasourceUrl,
39
- headers
39
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
40
40
  }),
41
- rangeQuery: (params)=>(0, _model.rangeQuery)(params, {
41
+ rangeQuery: (params, headers)=>(0, _model.rangeQuery)(params, {
42
42
  datasourceUrl,
43
- headers
43
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
44
44
  }),
45
- labelNames: (params)=>(0, _model.labelNames)(params, {
45
+ labelNames: (params, headers)=>(0, _model.labelNames)(params, {
46
46
  datasourceUrl,
47
- headers
47
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
48
48
  }),
49
- labelValues: (params)=>(0, _model.labelValues)(params, {
49
+ labelValues: (params, headers)=>(0, _model.labelValues)(params, {
50
50
  datasourceUrl,
51
- headers
51
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
52
52
  })
53
53
  };
54
54
  };
@@ -55,6 +55,20 @@ const getTimeSeriesData = async (spec, context)=>{
55
55
  var ref1;
56
56
  // TODO: What about error responses from Prom that have a response body?
57
57
  const result = (ref1 = (ref = response.data) === null || ref === void 0 ? void 0 : ref.result) !== null && ref1 !== void 0 ? ref1 : [];
58
+ // Custom display for response header warnings, configurable error responses display coming next
59
+ const notices = [];
60
+ if (response.status === 'success') {
61
+ var _warnings;
62
+ const warnings = (_warnings = response.warnings) !== null && _warnings !== void 0 ? _warnings : [];
63
+ var ref2;
64
+ const warningMessage = (ref2 = warnings[0]) !== null && ref2 !== void 0 ? ref2 : '';
65
+ if (warningMessage !== '') {
66
+ notices.push({
67
+ type: 'warning',
68
+ message: warningMessage
69
+ });
70
+ }
71
+ }
58
72
  // Transform response
59
73
  const chartData = {
60
74
  // Return the time range and step we actually used for the query
@@ -65,20 +79,18 @@ const getTimeSeriesData = async (spec, context)=>{
65
79
  stepMs: step * 1000,
66
80
  series: result.map((value)=>{
67
81
  const { metric , values } = value;
68
- // Name the series after the metric labels or if no metric, use the query
69
- let name = (0, _utils.getUniqueKeyForPrometheusResult)(metric);
70
- if (name === '') {
71
- name = query;
72
- }
73
- // query editor allows you to define an optional series_name_format
74
- // property to customize legend and tooltip display
75
- const formattedName = spec.series_name_format ? (0, _utils.formatSeriesName)(spec.series_name_format, metric) : name;
82
+ // Account for series_name_format from query editor when determining name to show in legend, tooltip, etc.
83
+ const { name , formattedName } = (0, _utils.getFormattedPrometheusSeriesName)(query, metric, spec.series_name_format);
76
84
  return {
77
85
  name,
78
86
  values: values.map(_model.parseValueTuple),
79
- formattedName
87
+ formattedName,
88
+ labels: metric
80
89
  };
81
- })
90
+ }),
91
+ metadata: {
92
+ notices
93
+ }
82
94
  };
83
95
  return chartData;
84
96
  };
@@ -25,8 +25,10 @@ _export(exports, {
25
25
  replaceTemplateVariable: ()=>replaceTemplateVariable,
26
26
  parseTemplateVariables: ()=>parseTemplateVariables,
27
27
  formatSeriesName: ()=>formatSeriesName,
28
- getUniqueKeyForPrometheusResult: ()=>getUniqueKeyForPrometheusResult
28
+ getUniqueKeyForPrometheusResult: ()=>getUniqueKeyForPrometheusResult,
29
+ getFormattedPrometheusSeriesName: ()=>getFormattedPrometheusSeriesName
29
30
  });
31
+ const _core = require("@perses-dev/core");
30
32
  function replaceTemplateVariables(text, variableState) {
31
33
  const variables = parseTemplateVariables(text);
32
34
  let finalText = text;
@@ -102,3 +104,22 @@ function getUniqueKeyForPrometheusResult(metricLabels, { removeExprWrap } = {})
102
104
  }
103
105
  return '';
104
106
  }
107
+ function getFormattedPrometheusSeriesName(query, metric, formatter) {
108
+ if ((0, _core.isEmptyObject)(metric)) {
109
+ return {
110
+ name: query
111
+ };
112
+ }
113
+ // Name the series after the metric labels or if no metric, use the query
114
+ let name = getUniqueKeyForPrometheusResult(metric);
115
+ if (name === '') {
116
+ name = query;
117
+ }
118
+ // Query editor allows you to define an optional series_name_format
119
+ // property to customize legend and tooltip display
120
+ const formattedName = formatter ? formatSeriesName(formatter, metric) : name;
121
+ return {
122
+ name,
123
+ formattedName
124
+ };
125
+ }
package/dist/index.d.ts CHANGED
@@ -3,4 +3,6 @@ import { StaticListVariable } from './plugins/variable';
3
3
  import { PrometheusLabelNamesVariable, PrometheusLabelValuesVariable, PrometheusPromQLVariable } from './plugins/prometheus-variables';
4
4
  import { PrometheusDatasource } from './plugins/prometheus-datasource';
5
5
  export { PrometheusTimeSeriesQuery, StaticListVariable, PrometheusLabelNamesVariable, PrometheusLabelValuesVariable, PrometheusPromQLVariable, PrometheusDatasource, };
6
+ export * from './model/prometheus-client';
7
+ export * from './model/api-types';
6
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AAEnF,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,EAC7B,wBAAwB,EACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAGvE,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,4BAA4B,EAC5B,6BAA6B,EAC7B,wBAAwB,EACxB,oBAAoB,GACrB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AAEnF,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,EAC7B,wBAAwB,EACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAGvE,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,4BAA4B,EAC5B,6BAA6B,EAC7B,wBAAwB,EACxB,oBAAoB,GACrB,CAAC;AAGF,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC"}
package/dist/index.js CHANGED
@@ -17,5 +17,8 @@ import { PrometheusLabelNamesVariable, PrometheusLabelValuesVariable, Prometheus
17
17
  import { PrometheusDatasource } from './plugins/prometheus-datasource';
18
18
  // Export plugins under the same name as the kinds they handle from the plugin.json
19
19
  export { PrometheusTimeSeriesQuery, StaticListVariable, PrometheusLabelNamesVariable, PrometheusLabelValuesVariable, PrometheusPromQLVariable, PrometheusDatasource };
20
+ // For consumers to leverage in DatasourceStoreProvider onCreate
21
+ export * from './model/prometheus-client';
22
+ export * from './model/api-types';
20
23
 
21
24
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.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 { PrometheusTimeSeriesQuery } from './plugins/prometheus-time-series-query';\n// @TODO: Move this to a more generic location;\nimport { StaticListVariable } from './plugins/variable';\nimport {\n PrometheusLabelNamesVariable,\n PrometheusLabelValuesVariable,\n PrometheusPromQLVariable,\n} from './plugins/prometheus-variables';\nimport { PrometheusDatasource } from './plugins/prometheus-datasource';\n\n// Export plugins under the same name as the kinds they handle from the plugin.json\nexport {\n PrometheusTimeSeriesQuery,\n StaticListVariable,\n PrometheusLabelNamesVariable,\n PrometheusLabelValuesVariable,\n PrometheusPromQLVariable,\n PrometheusDatasource,\n};\n"],"names":["PrometheusTimeSeriesQuery","StaticListVariable","PrometheusLabelNamesVariable","PrometheusLabelValuesVariable","PrometheusPromQLVariable","PrometheusDatasource"],"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,yBAAyB,QAAQ,wCAAwC,CAAC;AACnF,+CAA+C;AAC/C,SAASC,kBAAkB,QAAQ,oBAAoB,CAAC;AACxD,SACEC,4BAA4B,EAC5BC,6BAA6B,EAC7BC,wBAAwB,QACnB,gCAAgC,CAAC;AACxC,SAASC,oBAAoB,QAAQ,iCAAiC,CAAC;AAEvE,mFAAmF;AACnF,SACEL,yBAAyB,EACzBC,kBAAkB,EAClBC,4BAA4B,EAC5BC,6BAA6B,EAC7BC,wBAAwB,EACxBC,oBAAoB,GACpB"}
1
+ {"version":3,"sources":["../src/index.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 { PrometheusTimeSeriesQuery } from './plugins/prometheus-time-series-query';\n// @TODO: Move this to a more generic location;\nimport { StaticListVariable } from './plugins/variable';\nimport {\n PrometheusLabelNamesVariable,\n PrometheusLabelValuesVariable,\n PrometheusPromQLVariable,\n} from './plugins/prometheus-variables';\nimport { PrometheusDatasource } from './plugins/prometheus-datasource';\n\n// Export plugins under the same name as the kinds they handle from the plugin.json\nexport {\n PrometheusTimeSeriesQuery,\n StaticListVariable,\n PrometheusLabelNamesVariable,\n PrometheusLabelValuesVariable,\n PrometheusPromQLVariable,\n PrometheusDatasource,\n};\n\n// For consumers to leverage in DatasourceStoreProvider onCreate\nexport * from './model/prometheus-client';\nexport * from './model/api-types';\n"],"names":["PrometheusTimeSeriesQuery","StaticListVariable","PrometheusLabelNamesVariable","PrometheusLabelValuesVariable","PrometheusPromQLVariable","PrometheusDatasource"],"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,yBAAyB,QAAQ,wCAAwC,CAAC;AACnF,+CAA+C;AAC/C,SAASC,kBAAkB,QAAQ,oBAAoB,CAAC;AACxD,SACEC,4BAA4B,EAC5BC,6BAA6B,EAC7BC,wBAAwB,QACnB,gCAAgC,CAAC;AACxC,SAASC,oBAAoB,QAAQ,iCAAiC,CAAC;AAEvE,mFAAmF;AACnF,SACEL,yBAAyB,EACzBC,kBAAkB,EAClBC,4BAA4B,EAC5BC,6BAA6B,EAC7BC,wBAAwB,EACxBC,oBAAoB,GACpB;AAEF,gEAAgE;AAChE,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC"}
@@ -3,6 +3,7 @@ export type { DurationString };
3
3
  export interface SuccessResponse<T> {
4
4
  status: 'success';
5
5
  data: T;
6
+ rawResponse?: Response;
6
7
  warnings?: string[];
7
8
  }
8
9
  export interface ErrorResponse<T> {
@@ -1 +1 @@
1
- {"version":3,"file":"api-types.d.ts","s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AC;IAC7B,GAAG,CAAC,EAAE,oBAAoB,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;CACtB;AAED,oBAAY,mBAAmB,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC;AAExD,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,+BAA+B;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,oBAAY,sBAAsB,GAAG,WAAW,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/model/api-types.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 { DurationString } from '@perses-dev/core';\n\n// Just reuse dashboard model's type and re-export\nexport type { DurationString };\n\nexport interface SuccessResponse<T> {\n status: 'success';\n data: T;\n warnings?: string[];\n}\n\nexport interface ErrorResponse<T> {\n status: 'error';\n data?: T;\n errorType: string;\n error: string;\n}\n\nexport type ApiResponse<T> = SuccessResponse<T> | ErrorResponse<T>;\n\nexport type DurationSeconds = number;\n\nexport type UnixTimestampSeconds = number;\n\nexport type ValueTuple = [unixTimeSeconds: UnixTimestampSeconds, sampleValue: string];\n\nexport type Metric = Record<string, string>;\n\nexport interface VectorData {\n resultType: 'vector';\n result: Array<{\n metric: Metric;\n value: ValueTuple;\n }>;\n}\n\nexport interface MatrixData {\n resultType: 'matrix';\n result: Array<{\n metric: Metric;\n values: ValueTuple[];\n }>;\n}\n\nexport interface ScalarData {\n resultType: 'scalar';\n result: ValueTuple;\n}\n\nexport interface InstantQueryRequestParameters {\n query: string;\n time?: UnixTimestampSeconds;\n timeout?: DurationString;\n}\n\nexport type InstantQueryResponse = ApiResponse<MatrixData | VectorData | ScalarData>;\n\nexport interface RangeQueryRequestParameters {\n query: string;\n start: UnixTimestampSeconds;\n end: UnixTimestampSeconds;\n step: DurationSeconds;\n timeout?: DurationString;\n}\n\nexport type RangeQueryResponse = ApiResponse<MatrixData>;\n\nexport interface SeriesRequestParameters {\n 'match[]': string[];\n start: UnixTimestampSeconds;\n end: UnixTimestampSeconds;\n}\n\nexport type SeriesResponse = ApiResponse<Metric[]>;\n\nexport interface LabelNamesRequestParameters {\n start?: UnixTimestampSeconds;\n end?: UnixTimestampSeconds;\n 'match[]'?: string[];\n}\n\nexport type LabelNamesResponse = ApiResponse<string[]>;\n\nexport interface LabelValuesRequestParameters {\n labelName: string;\n start?: UnixTimestampSeconds;\n end?: UnixTimestampSeconds;\n 'match[]'?: string[];\n}\n\nexport type LabelValuesResponse = ApiResponse<string[]>;\n\nexport interface MetricMetadata {\n type: string;\n help: string;\n unit?: string;\n}\n\nexport interface MetricMetadataRequestParameters {\n limit?: number;\n metric?: string;\n}\n\nexport type MetricMetadataResponse = ApiResponse<Record<string, MetricMetadata[]>>;\n"],"names":[],"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,WAuGmF"}
1
+ {"version":3,"sources":["../../src/model/api-types.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 { DurationString } from '@perses-dev/core';\n\n// Just reuse dashboard model's type and re-export\nexport type { DurationString };\n\nexport interface SuccessResponse<T> {\n status: 'success';\n data: T;\n rawResponse?: Response;\n warnings?: string[];\n}\n\nexport interface ErrorResponse<T> {\n status: 'error';\n data?: T;\n errorType: string;\n error: string;\n}\n\nexport type ApiResponse<T> = SuccessResponse<T> | ErrorResponse<T>;\n\nexport type DurationSeconds = number;\n\nexport type UnixTimestampSeconds = number;\n\nexport type ValueTuple = [unixTimeSeconds: UnixTimestampSeconds, sampleValue: string];\n\nexport type Metric = Record<string, string>;\n\nexport interface VectorData {\n resultType: 'vector';\n result: Array<{\n metric: Metric;\n value: ValueTuple;\n }>;\n}\n\nexport interface MatrixData {\n resultType: 'matrix';\n result: Array<{\n metric: Metric;\n values: ValueTuple[];\n }>;\n}\n\nexport interface ScalarData {\n resultType: 'scalar';\n result: ValueTuple;\n}\n\nexport interface InstantQueryRequestParameters {\n query: string;\n time?: UnixTimestampSeconds;\n timeout?: DurationString;\n}\n\nexport type InstantQueryResponse = ApiResponse<MatrixData | VectorData | ScalarData>;\n\nexport interface RangeQueryRequestParameters {\n query: string;\n start: UnixTimestampSeconds;\n end: UnixTimestampSeconds;\n step: DurationSeconds;\n timeout?: DurationString;\n}\n\nexport type RangeQueryResponse = ApiResponse<MatrixData>;\n\nexport interface SeriesRequestParameters {\n 'match[]': string[];\n start: UnixTimestampSeconds;\n end: UnixTimestampSeconds;\n}\n\nexport type SeriesResponse = ApiResponse<Metric[]>;\n\nexport interface LabelNamesRequestParameters {\n start?: UnixTimestampSeconds;\n end?: UnixTimestampSeconds;\n 'match[]'?: string[];\n}\n\nexport type LabelNamesResponse = ApiResponse<string[]>;\n\nexport interface LabelValuesRequestParameters {\n labelName: string;\n start?: UnixTimestampSeconds;\n end?: UnixTimestampSeconds;\n 'match[]'?: string[];\n}\n\nexport type LabelValuesResponse = ApiResponse<string[]>;\n\nexport interface MetricMetadata {\n type: string;\n help: string;\n unit?: string;\n}\n\nexport interface MetricMetadataRequestParameters {\n limit?: number;\n metric?: string;\n}\n\nexport type MetricMetadataResponse = ApiResponse<Record<string, MetricMetadata[]>>;\n"],"names":[],"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,WAwGmF"}
@@ -1,15 +1,16 @@
1
1
  import { RequestHeaders } from '@perses-dev/core';
2
+ import { DatasourceClient } from '@perses-dev/plugin-system';
2
3
  import { InstantQueryRequestParameters, InstantQueryResponse, LabelNamesRequestParameters, LabelNamesResponse, LabelValuesRequestParameters, LabelValuesResponse, RangeQueryRequestParameters, RangeQueryResponse } from './api-types';
3
4
  interface PrometheusClientOptions {
4
5
  datasourceUrl: string;
5
6
  headers?: RequestHeaders;
6
7
  }
7
- export interface PrometheusClient {
8
+ export interface PrometheusClient extends DatasourceClient {
8
9
  options: PrometheusClientOptions;
9
- instantQuery(params: InstantQueryRequestParameters): Promise<InstantQueryResponse>;
10
- rangeQuery(params: RangeQueryRequestParameters): Promise<RangeQueryResponse>;
11
- labelNames(params: LabelNamesRequestParameters): Promise<LabelNamesResponse>;
12
- labelValues(params: LabelValuesRequestParameters): Promise<LabelValuesResponse>;
10
+ instantQuery(params: InstantQueryRequestParameters, headers?: RequestHeaders): Promise<InstantQueryResponse>;
11
+ rangeQuery(params: RangeQueryRequestParameters, headers?: RequestHeaders): Promise<RangeQueryResponse>;
12
+ labelNames(params: LabelNamesRequestParameters, headers?: RequestHeaders): Promise<LabelNamesResponse>;
13
+ labelValues(params: LabelValuesRequestParameters, headers?: RequestHeaders): Promise<LabelValuesResponse>;
13
14
  }
14
15
  export interface QueryOptions {
15
16
  datasourceUrl: string;
@@ -18,18 +19,30 @@ export interface QueryOptions {
18
19
  /**
19
20
  * Calls the `/api/v1/query` endpoint to get metrics data.
20
21
  */
21
- export declare function instantQuery(params: InstantQueryRequestParameters, queryOptions: QueryOptions): Promise<InstantQueryResponse>;
22
+ export declare function instantQuery(params: InstantQueryRequestParameters, queryOptions: QueryOptions): Promise<InstantQueryResponse & {
23
+ rawResponse: Response;
24
+ }>;
22
25
  /**
23
26
  * Calls the `/api/v1/query_range` endpoint to get metrics data.
24
27
  */
25
- export declare function rangeQuery(params: RangeQueryRequestParameters, queryOptions: QueryOptions): Promise<RangeQueryResponse>;
28
+ export declare function rangeQuery(params: RangeQueryRequestParameters, queryOptions: QueryOptions): Promise<RangeQueryResponse & {
29
+ rawResponse: Response;
30
+ }>;
26
31
  /**
27
32
  * Calls the `/api/v1/labels` endpoint to get a list of label names.
28
33
  */
29
- export declare function labelNames(params: LabelNamesRequestParameters, queryOptions: QueryOptions): Promise<LabelNamesResponse>;
34
+ export declare function labelNames(params: LabelNamesRequestParameters, queryOptions: QueryOptions): Promise<LabelNamesResponse & {
35
+ rawResponse: Response;
36
+ }>;
30
37
  /**
31
38
  * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of values for a label.
32
39
  */
33
40
  export declare function labelValues(params: LabelValuesRequestParameters, queryOptions: QueryOptions): Promise<LabelValuesResponse>;
41
+ /**
42
+ * Fetch JSON and parse warnings for query inspector
43
+ */
44
+ export declare function fetchResults<T>(...args: Parameters<typeof global.fetch>): Promise<T & {
45
+ rawResponse: Response;
46
+ }>;
34
47
  export {};
35
48
  //# sourceMappingURL=prometheus-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prometheus-client.d.ts","sourceRoot":"","sources":["../../src/model/prometheus-client.ts"],"names":[],"mappings":"AAaA,OAAO,EAAa,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W,CAAC,MAAM,EAAE,4BAA4B,EAAE,YAAY,EAAE,YAAY,gCAI3F;AA+DD;;GAEG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,MAAM,CAAC,KAAK,CAAC;;GAI7E"}
@@ -10,7 +10,7 @@
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 { fetchJson } from '@perses-dev/core';
13
+ import { fetch, fetchJson } from '@perses-dev/core';
14
14
  /**
15
15
  * Calls the `/api/v1/query` endpoint to get metrics data.
16
16
  */ export function instantQuery(params, queryOptions) {
@@ -55,7 +55,7 @@ function fetchWithPost(apiURI, params, queryOptions) {
55
55
  },
56
56
  body: createSearchParams(params)
57
57
  };
58
- return fetchJson(url, init);
58
+ return fetchResults(url, init);
59
59
  }
60
60
  /**
61
61
  * Creates URLSearchParams from a request params object.
@@ -78,5 +78,15 @@ function fetchWithPost(apiURI, params, queryOptions) {
78
78
  }
79
79
  return searchParams;
80
80
  }
81
+ /**
82
+ * Fetch JSON and parse warnings for query inspector
83
+ */ export async function fetchResults(...args) {
84
+ const response = await fetch(...args);
85
+ const json = await response.json();
86
+ return {
87
+ ...json,
88
+ rawResponse: response
89
+ };
90
+ }
81
91
 
82
92
  //# sourceMappingURL=prometheus-client.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/model/prometheus-client.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 { fetchJson, RequestHeaders } from '@perses-dev/core';\nimport {\n InstantQueryRequestParameters,\n InstantQueryResponse,\n LabelNamesRequestParameters,\n LabelNamesResponse,\n LabelValuesRequestParameters,\n LabelValuesResponse,\n RangeQueryRequestParameters,\n RangeQueryResponse,\n} from './api-types';\n\ninterface PrometheusClientOptions {\n datasourceUrl: string;\n headers?: RequestHeaders;\n}\n\nexport interface PrometheusClient {\n options: PrometheusClientOptions;\n instantQuery(params: InstantQueryRequestParameters): Promise<InstantQueryResponse>;\n rangeQuery(params: RangeQueryRequestParameters): Promise<RangeQueryResponse>;\n labelNames(params: LabelNamesRequestParameters): Promise<LabelNamesResponse>;\n labelValues(params: LabelValuesRequestParameters): Promise<LabelValuesResponse>;\n}\n\nexport interface QueryOptions {\n datasourceUrl: string;\n headers?: RequestHeaders;\n}\n\n/**\n * Calls the `/api/v1/query` endpoint to get metrics data.\n */\nexport function instantQuery(params: InstantQueryRequestParameters, queryOptions: QueryOptions) {\n return fetchWithPost<InstantQueryRequestParameters, InstantQueryResponse>('/api/v1/query', params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/query_range` endpoint to get metrics data.\n */\nexport function rangeQuery(params: RangeQueryRequestParameters, queryOptions: QueryOptions) {\n return fetchWithPost<RangeQueryRequestParameters, RangeQueryResponse>('/api/v1/query_range', params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/labels` endpoint to get a list of label names.\n */\nexport function labelNames(params: LabelNamesRequestParameters, queryOptions: QueryOptions) {\n return fetchWithPost<LabelNamesRequestParameters, LabelNamesResponse>('/api/v1/labels', params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of values for a label.\n */\nexport function labelValues(params: LabelValuesRequestParameters, queryOptions: QueryOptions) {\n const { labelName, ...searchParams } = params;\n const apiURI = `/api/v1/label/${encodeURIComponent(labelName)}/values`;\n return fetchWithGet<typeof searchParams, LabelValuesResponse>(apiURI, searchParams, queryOptions);\n}\n\nfunction fetchWithGet<T extends RequestParams<T>, TResponse>(apiURI: string, params: T, queryOptions: QueryOptions) {\n const { datasourceUrl } = queryOptions;\n\n let url = `${datasourceUrl}${apiURI}`;\n const urlParams = createSearchParams(params).toString();\n if (urlParams !== '') {\n url += `?${urlParams}`;\n }\n return fetchJson<TResponse>(url, { method: 'GET' });\n}\n\nfunction fetchWithPost<T extends RequestParams<T>, TResponse>(apiURI: string, params: T, queryOptions: QueryOptions) {\n const { datasourceUrl, headers } = queryOptions;\n\n const url = `${datasourceUrl}${apiURI}`;\n const init = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...headers,\n },\n body: createSearchParams(params),\n };\n return fetchJson<TResponse>(url, init);\n}\n\n// Request parameter values we know how to serialize\ntype ParamValue = string | string[] | number | undefined;\n\n// Used to constrain the types that can be passed to createSearchParams to\n// just the ones we know how to serialize\ntype RequestParams<T> = {\n [K in keyof T]: ParamValue;\n};\n\n/**\n * Creates URLSearchParams from a request params object.\n */\nfunction createSearchParams<T extends RequestParams<T>>(params: T) {\n const searchParams = new URLSearchParams();\n for (const key in params) {\n const value: ParamValue = params[key];\n if (value === undefined) continue;\n\n if (typeof value === 'string') {\n searchParams.append(key, value);\n continue;\n }\n\n if (typeof value === 'number') {\n searchParams.append(key, value.toString());\n continue;\n }\n\n for (const val of value) {\n searchParams.append(key, val);\n }\n }\n return searchParams;\n}\n"],"names":["fetchJson","instantQuery","params","queryOptions","fetchWithPost","rangeQuery","labelNames","labelValues","labelName","searchParams","apiURI","encodeURIComponent","fetchWithGet","datasourceUrl","url","urlParams","createSearchParams","toString","method","headers","init","body","URLSearchParams","key","value","undefined","append","val"],"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,SAAS,QAAwB,kBAAkB,CAAC;AA8B7D;;CA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../src/model/prometheus-client.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 { fetch, fetchJson, RequestHeaders } from '@perses-dev/core';\nimport { DatasourceClient } from '@perses-dev/plugin-system';\nimport {\n InstantQueryRequestParameters,\n InstantQueryResponse,\n LabelNamesRequestParameters,\n LabelNamesResponse,\n LabelValuesRequestParameters,\n LabelValuesResponse,\n RangeQueryRequestParameters,\n RangeQueryResponse,\n} from './api-types';\n\ninterface PrometheusClientOptions {\n datasourceUrl: string;\n headers?: RequestHeaders;\n}\n\nexport interface PrometheusClient extends DatasourceClient {\n options: PrometheusClientOptions;\n instantQuery(params: InstantQueryRequestParameters, headers?: RequestHeaders): Promise<InstantQueryResponse>;\n rangeQuery(params: RangeQueryRequestParameters, headers?: RequestHeaders): Promise<RangeQueryResponse>;\n labelNames(params: LabelNamesRequestParameters, headers?: RequestHeaders): Promise<LabelNamesResponse>;\n labelValues(params: LabelValuesRequestParameters, headers?: RequestHeaders): Promise<LabelValuesResponse>;\n}\n\nexport interface QueryOptions {\n datasourceUrl: string;\n headers?: RequestHeaders;\n}\n\n/**\n * Calls the `/api/v1/query` endpoint to get metrics data.\n */\nexport function instantQuery(params: InstantQueryRequestParameters, queryOptions: QueryOptions) {\n return fetchWithPost<InstantQueryRequestParameters, InstantQueryResponse>('/api/v1/query', params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/query_range` endpoint to get metrics data.\n */\nexport function rangeQuery(params: RangeQueryRequestParameters, queryOptions: QueryOptions) {\n return fetchWithPost<RangeQueryRequestParameters, RangeQueryResponse>('/api/v1/query_range', params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/labels` endpoint to get a list of label names.\n */\nexport function labelNames(params: LabelNamesRequestParameters, queryOptions: QueryOptions) {\n return fetchWithPost<LabelNamesRequestParameters, LabelNamesResponse>('/api/v1/labels', params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of values for a label.\n */\nexport function labelValues(params: LabelValuesRequestParameters, queryOptions: QueryOptions) {\n const { labelName, ...searchParams } = params;\n const apiURI = `/api/v1/label/${encodeURIComponent(labelName)}/values`;\n return fetchWithGet<typeof searchParams, LabelValuesResponse>(apiURI, searchParams, queryOptions);\n}\n\nfunction fetchWithGet<T extends RequestParams<T>, TResponse>(apiURI: string, params: T, queryOptions: QueryOptions) {\n const { datasourceUrl } = queryOptions;\n\n let url = `${datasourceUrl}${apiURI}`;\n const urlParams = createSearchParams(params).toString();\n if (urlParams !== '') {\n url += `?${urlParams}`;\n }\n return fetchJson<TResponse>(url, { method: 'GET' });\n}\n\nfunction fetchWithPost<T extends RequestParams<T>, TResponse>(apiURI: string, params: T, queryOptions: QueryOptions) {\n const { datasourceUrl, headers } = queryOptions;\n\n const url = `${datasourceUrl}${apiURI}`;\n const init = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...headers,\n },\n body: createSearchParams(params),\n };\n return fetchResults<TResponse>(url, init);\n}\n\n// Request parameter values we know how to serialize\ntype ParamValue = string | string[] | number | undefined;\n\n// Used to constrain the types that can be passed to createSearchParams to\n// just the ones we know how to serialize\ntype RequestParams<T> = {\n [K in keyof T]: ParamValue;\n};\n\n/**\n * Creates URLSearchParams from a request params object.\n */\nfunction createSearchParams<T extends RequestParams<T>>(params: T) {\n const searchParams = new URLSearchParams();\n for (const key in params) {\n const value: ParamValue = params[key];\n if (value === undefined) continue;\n\n if (typeof value === 'string') {\n searchParams.append(key, value);\n continue;\n }\n\n if (typeof value === 'number') {\n searchParams.append(key, value.toString());\n continue;\n }\n\n for (const val of value) {\n searchParams.append(key, val);\n }\n }\n return searchParams;\n}\n\n/**\n * Fetch JSON and parse warnings for query inspector\n */\nexport async function fetchResults<T>(...args: Parameters<typeof global.fetch>) {\n const response = await fetch(...args);\n const json: T = await response.json();\n return { ...json, rawResponse: response };\n}\n"],"names":["fetch","fetchJson","instantQuery","params","queryOptions","fetchWithPost","rangeQuery","labelNames","labelValues","labelName","searchParams","apiURI","encodeURIComponent","fetchWithGet","datasourceUrl","url","urlParams","createSearchParams","toString","method","headers","init","body","fetchResults","URLSearchParams","key","value","undefined","append","val","args","response","json","rawResponse"],"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,KAAK,EAAEC,SAAS,QAAwB,kBAAkB,CAAC;AA+BpE;;CAEC,GACD,OAAO,SAASC,YAAY,CAACC,MAAqC,EAAEC,YAA0B,EAAE;IAC9F,OAAOC,aAAa,CAAsD,eAAe,EAAEF,MAAM,EAAEC,YAAY,CAAC,CAAC;AACnH,CAAC;AAED;;CAEC,GACD,OAAO,SAASE,UAAU,CAACH,MAAmC,EAAEC,YAA0B,EAAE;IAC1F,OAAOC,aAAa,CAAkD,qBAAqB,EAAEF,MAAM,EAAEC,YAAY,CAAC,CAAC;AACrH,CAAC;AAED;;CAEC,GACD,OAAO,SAASG,UAAU,CAACJ,MAAmC,EAAEC,YAA0B,EAAE;IAC1F,OAAOC,aAAa,CAAkD,gBAAgB,EAAEF,MAAM,EAAEC,YAAY,CAAC,CAAC;AAChH,CAAC;AAED;;CAEC,GACD,OAAO,SAASI,WAAW,CAACL,MAAoC,EAAEC,YAA0B,EAAE;IAC5F,MAAM,EAAEK,SAAS,CAAA,EAAE,GAAGC,YAAY,EAAE,GAAGP,MAAM,AAAC;IAC9C,MAAMQ,MAAM,G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AMC,GAAG,IAAItB,MAAM,CAAE;QACxB,MAAMuB,KAAK,GAAevB,MAAM,CAACsB,GAAG,CAAC,AAAC;QACtC,IAAIC,KAAK,KAAKC,SAAS,EAAE,SAAS;QAElC,IAAI,OAAOD,KAAK,KAAK,QAAQ,EAAE;YAC7BhB,YAAY,CAACkB,MAAM,CAACH,GAAG,EAAEC,KAAK,CAAC,CAAC;YAChC,SAAS;QACX,CAAC;QAED,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;YAC7BhB,YAAY,CAACkB,MAAM,CAACH,GAAG,EAAEC,KAAK,CAACR,QAAQ,EAAE,CAAC,CAAC;YAC3C,SAAS;QACX,CAAC;QAED,KAAK,MAAMW,GAAG,IAAIH,KAAK,CAAE;YACvBhB,YAAY,CAACkB,MAAM,CAACH,GAAG,EAAEI,GAAG,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IACD,OAAOnB,YAAY,CAAC;AACtB,CAAC;AAED;;CAEC,GACD,OAAO,eAAea,YAAY,CAAI,GAAGO,IAAI,AAAiC,EAAE;IAC9E,MAAMC,QAAQ,GAAG,MAAM/B,KAAK,IAAI8B,IAAI,CAAC,AAAC;IACtC,MAAME,IAAI,GAAM,MAAMD,QAAQ,CAACC,IAAI,EAAE,AAAC;IACtC,OAAO;QAAE,GAAGA,IAAI;QAAEC,WAAW,EAAEF,QAAQ;KAAE,CAAC;AAC5C,CAAC"}
@@ -14,7 +14,7 @@ import { instantQuery, rangeQuery, labelNames, labelValues } from '../model';
14
14
  /**
15
15
  * Creates a PrometheusClient for a specific datasource spec.
16
16
  */ const createClient = (spec, options)=>{
17
- const { direct_url , headers } = spec;
17
+ const { direct_url , headers: specHeaders } = spec;
18
18
  const { proxyUrl } = options;
19
19
  // Use the direct URL if specified, but fallback to the proxyUrl by default if not specified
20
20
  const datasourceUrl = direct_url !== null && direct_url !== void 0 ? direct_url : proxyUrl;
@@ -26,21 +26,21 @@ import { instantQuery, rangeQuery, labelNames, labelValues } from '../model';
26
26
  options: {
27
27
  datasourceUrl
28
28
  },
29
- instantQuery: (params)=>instantQuery(params, {
29
+ instantQuery: (params, headers)=>instantQuery(params, {
30
30
  datasourceUrl,
31
- headers
31
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
32
32
  }),
33
- rangeQuery: (params)=>rangeQuery(params, {
33
+ rangeQuery: (params, headers)=>rangeQuery(params, {
34
34
  datasourceUrl,
35
- headers
35
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
36
36
  }),
37
- labelNames: (params)=>labelNames(params, {
37
+ labelNames: (params, headers)=>labelNames(params, {
38
38
  datasourceUrl,
39
- headers
39
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
40
40
  }),
41
- labelValues: (params)=>labelValues(params, {
41
+ labelValues: (params, headers)=>labelValues(params, {
42
42
  datasourceUrl,
43
- headers
43
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
44
44
  })
45
45
  };
46
46
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/prometheus-datasource.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 { RequestHeaders } from '@perses-dev/core';\nimport { DatasourcePlugin } from '@perses-dev/plugin-system';\nimport { instantQuery, rangeQuery, labelNames, labelValues, PrometheusClient } from '../model';\n\nexport interface PrometheusDatasourceSpec {\n direct_url?: string;\n headers?: RequestHeaders;\n}\n\n/**\n * Creates a PrometheusClient for a specific datasource spec.\n */\nconst createClient: DatasourcePlugin<PrometheusDatasourceSpec, PrometheusClient>['createClient'] = (spec, options) => {\n const { direct_url, headers } = spec;\n const { proxyUrl } = options;\n\n // Use the direct URL if specified, but fallback to the proxyUrl by default if not specified\n const datasourceUrl = direct_url ?? proxyUrl;\n if (datasourceUrl === undefined) {\n throw new Error('No URL specified for Prometheus client. You can use direct_url in the spec to configure it.');\n }\n\n // Could think about this becoming a class, although it definitely doesn't have to be\n return {\n options: {\n datasourceUrl,\n },\n instantQuery: (params) => instantQuery(params, { datasourceUrl, headers }),\n rangeQuery: (params) => rangeQuery(params, { datasourceUrl, headers }),\n labelNames: (params) => labelNames(params, { datasourceUrl, headers }),\n labelValues: (params) => labelValues(params, { datasourceUrl, headers }),\n };\n};\n\nexport const PrometheusDatasource: DatasourcePlugin<PrometheusDatasourceSpec, PrometheusClient> = {\n createClient,\n OptionsEditorComponent: () => null,\n createInitialOptions: () => ({ direct_url: '' }),\n};\n"],"names":["instantQuery","rangeQuery","labelNames","labelValues","createClient","spec","options","direct_url","headers","proxyUrl","datasourceUrl","undefined","Error","params","PrometheusDatasource","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;AAIjC,SAASA,YAAY,EAAEC,UAAU,EAAEC,UAAU,EAAEC,WAAW,QAA0B,UAAU,CAAC;AAO/F;;CAEC,GACD,MAAMC,YAAY,GAAiF,CAACC,IAAI,EAAEC,OAAO,GAAK;IACpH,MAAM,EAAEC,UAAU,CAAA,EAAEC,OAAO,CAAA,EAAE,GAAGH,IAAI,AAAC;IACrC,MAAM,EAAEI,QAAQ,CAAA,EAAE,GAAGH,OAAO,AAAC;IAE7B,4FAA4F;IAC5F,MAAMI,aAAa,GAAGH,UAAU,aAAVA,UAAU,cAAVA,UAAU,GAAIE,QAAQ,AAAC;IAC7C,IAAIC,aAAa,KAAKC,SAAS,EAAE;QAC/B,MAAM,IAAIC,KAAK,CAAC,6FAA6F,CAAC,CAAC;IACjH,CAAC;IAED,qFAAqF;IACrF,OAAO;QACLN,OAAO,EAAE;YACPI,aAAa;SACd;QACDV,YAAY,EAAE,CAACa,MAAM,GAAKb,YAAY,CAACa,MAAM,EAAE;gBAAEH,aAAa;gBAAEF,OAAO;aAAE,CAAC;QAC1EP,UAAU,EAAE,CAACY,MAAM,GAAKZ,UAAU,CAACY,MAAM,EAAE;gBAAEH,aAAa;gBAAEF,OAAO;aAAE,CAAC;QACtEN,UAAU,EAAE,CAACW,MAAM,GAAKX,UAAU,CAACW,MAAM,EAAE;gBAAEH,aAAa;gBAAEF,OAAO;aAAE,CAAC;QACtEL,WAAW,EAAE,CAACU,MAAM,GAAKV,WAAW,CAACU,MAAM,EAAE;gBAAEH,aAAa;gBAAEF,OAAO;aAAE,CAAC;KACzE,CAAC;AACJ,CAAC,AAAC;AAEF,OAAO,MAAMM,oBAAoB,GAAiE;IAChGV,YAAY;IACZW,sBAAsB,EAAE,IAAM,IAAI;IAClCC,oBAAoB,EAAE,IAAO,CAAA;YAAET,UAAU,EAAE,EAAE;SAAE,CAAA,AAAC;CACjD,CAAC"}
1
+ {"version":3,"sources":["../../src/plugins/prometheus-datasource.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 { RequestHeaders } from '@perses-dev/core';\nimport { DatasourcePlugin } from '@perses-dev/plugin-system';\nimport { instantQuery, rangeQuery, labelNames, labelValues, PrometheusClient } from '../model';\n\nexport interface PrometheusDatasourceSpec {\n direct_url?: string;\n headers?: RequestHeaders;\n}\n\n/**\n * Creates a PrometheusClient for a specific datasource spec.\n */\nconst createClient: DatasourcePlugin<PrometheusDatasourceSpec, PrometheusClient>['createClient'] = (spec, options) => {\n const { direct_url, headers: specHeaders } = spec;\n const { proxyUrl } = options;\n\n // Use the direct URL if specified, but fallback to the proxyUrl by default if not specified\n const datasourceUrl = direct_url ?? proxyUrl;\n if (datasourceUrl === undefined) {\n throw new Error('No URL specified for Prometheus client. You can use direct_url in the spec to configure it.');\n }\n\n // Could think about this becoming a class, although it definitely doesn't have to be\n return {\n options: {\n datasourceUrl,\n },\n instantQuery: (params, headers) => instantQuery(params, { datasourceUrl, headers: headers ?? specHeaders }),\n rangeQuery: (params, headers) => rangeQuery(params, { datasourceUrl, headers: headers ?? specHeaders }),\n labelNames: (params, headers) => labelNames(params, { datasourceUrl, headers: headers ?? specHeaders }),\n labelValues: (params, headers) => labelValues(params, { datasourceUrl, headers: headers ?? specHeaders }),\n };\n};\n\nexport const PrometheusDatasource: DatasourcePlugin<PrometheusDatasourceSpec, PrometheusClient> = {\n createClient,\n OptionsEditorComponent: () => null,\n createInitialOptions: () => ({ direct_url: '' }),\n};\n"],"names":["instantQuery","rangeQuery","labelNames","labelValues","createClient","spec","options","direct_url","headers","specHeaders","proxyUrl","datasourceUrl","undefined","Error","params","PrometheusDatasource","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;AAIjC,SAASA,YAAY,EAAEC,UAAU,EAAEC,UAAU,EAAEC,WAAW,QAA0B,UAAU,CAAC;AAO/F;;CAEC,GACD,MAAMC,YAAY,GAAiF,CAACC,IAAI,EAAEC,OAAO,GAAK;IACpH,MAAM,EAAEC,UAAU,CAAA,EAAEC,OAAO,EAAEC,WAAW,CAAA,EAAE,GAAGJ,IAAI,A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,"file":"get-time-series-data.d.ts","sourceRoot":"","sources":["../../../src/plugins/prometheus-time-series-query/get-time-series-data.ts"],"names":[],"mappings":"AAaA,OAAO,EAAkB,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAWlF,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAE1E,eAAO,MAAM,iBAAiB,EAAE,qBAAqB,CAAC,6BAA6B,CAAC,CAAC,mBAAmB,CAoEvG,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":"AAcA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAWlE,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAE1E,eAAO,MAAM,iBAAiB,EAAE,qBAAqB,CAAC,6BAA6B,CAAC,CAAC,mBAAmB,CA8EvG,CAAC"}
@@ -12,7 +12,7 @@
12
12
  // limitations under the License.
13
13
  import { fromUnixTime } from 'date-fns';
14
14
  import { parseValueTuple, getDurationStringSeconds, getPrometheusTimeRange, getRangeStep, DEFAULT_PROM } from '../../model';
15
- import { getUniqueKeyForPrometheusResult, replaceTemplateVariables, formatSeriesName } from '../../utils';
15
+ import { getFormattedPrometheusSeriesName, replaceTemplateVariables } from '../../utils';
16
16
  export const getTimeSeriesData = async (spec, context)=>{
17
17
  var ref;
18
18
  if (spec.query === undefined || spec.query === null || spec.query === '') {
@@ -47,6 +47,20 @@ export const getTimeSeriesData = async (spec, context)=>{
47
47
  var ref1;
48
48
  // TODO: What about error responses from Prom that have a response body?
49
49
  const result = (ref1 = (ref = response.data) === null || ref === void 0 ? void 0 : ref.result) !== null && ref1 !== void 0 ? ref1 : [];
50
+ // Custom display for response header warnings, configurable error responses display coming next
51
+ const notices = [];
52
+ if (response.status === 'success') {
53
+ var _warnings;
54
+ const warnings = (_warnings = response.warnings) !== null && _warnings !== void 0 ? _warnings : [];
55
+ var ref2;
56
+ const warningMessage = (ref2 = warnings[0]) !== null && ref2 !== void 0 ? ref2 : '';
57
+ if (warningMessage !== '') {
58
+ notices.push({
59
+ type: 'warning',
60
+ message: warningMessage
61
+ });
62
+ }
63
+ }
50
64
  // Transform response
51
65
  const chartData = {
52
66
  // Return the time range and step we actually used for the query
@@ -57,20 +71,18 @@ export const getTimeSeriesData = async (spec, context)=>{
57
71
  stepMs: step * 1000,
58
72
  series: result.map((value)=>{
59
73
  const { metric , values } = value;
60
- // Name the series after the metric labels or if no metric, use the query
61
- let name = getUniqueKeyForPrometheusResult(metric);
62
- if (name === '') {
63
- name = query;
64
- }
65
- // query editor allows you to define an optional series_name_format
66
- // property to customize legend and tooltip display
67
- const formattedName = spec.series_name_format ? formatSeriesName(spec.series_name_format, metric) : name;
74
+ // Account for series_name_format from query editor when determining name to show in legend, tooltip, etc.
75
+ const { name , formattedName } = getFormattedPrometheusSeriesName(query, metric, spec.series_name_format);
68
76
  return {
69
77
  name,
70
78
  values: values.map(parseValueTuple),
71
- formattedName
79
+ formattedName,
80
+ labels: metric
72
81
  };
73
- })
82
+ }),
83
+ metadata: {
84
+ notices
85
+ }
74
86
  };
75
87
  return chartData;
76
88
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/plugins/prometheus-time-series-query/get-time-series-data.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 { TimeSeriesData, TimeSeriesQueryPlugin } from '@perses-dev/plugin-system';\nimport { fromUnixTime } from 'date-fns';\nimport {\n parseValueTuple,\n PrometheusClient,\n getDurationStringSeconds,\n getPrometheusTimeRange,\n getRangeStep,\n DEFAULT_PROM,\n} from '../../model';\nimport { getUniqueKeyForPrometheusResult, replaceTemplateVariables, formatSeriesName } from '../../utils';\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 minStep = getDurationStringSeconds(spec.min_step);\n const timeRange = getPrometheusTimeRange(context.timeRange);\n const step = getRangeStep(timeRange, minStep, undefined, context.suggestedStepMs);\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 template variable placeholders in PromQL query\n let query = spec.query.replace('$__rate_interval', `15s`);\n query = replaceTemplateVariables(query, context.variableState);\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 const response = await client.rangeQuery({\n query,\n start,\n end,\n step,\n });\n\n // TODO: What about error responses from Prom that have a response body?\n const result = response.data?.result ?? [];\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: result.map((value) => {\n const { metric, values } = value;\n\n // Name the series after the metric labels or if no metric, use the query\n let name = getUniqueKeyForPrometheusResult(metric);\n if (name === '') {\n name = query;\n }\n\n // query editor allows you to define an optional series_name_format\n // property to customize legend and tooltip display\n const formattedName = spec.series_name_format ? formatSeriesName(spec.series_name_format, metric) : name;\n\n return {\n name,\n values: values.map(parseValueTuple),\n formattedName,\n };\n }),\n };\n\n return chartData;\n};\n"],"names":["fromUnixTime","parseValueTuple","getDurationStringSeconds","getPrometheusTimeRange","getRangeStep","DEFAULT_PROM","getUniqueKeyForPrometheusResult","replaceTemplateVariables","formatSeriesName","getTimeSeriesData","spec","context","response","query","undefined","series","minStep","min_step","timeRange","step","suggestedStepMs","start","end","utcOffsetSec","Date","getTimezoneOffset","alignedEnd","Math","floor","alignedStart","replace","variableState","client","datasourceStore","getDatasourceClient","datasource","rangeQuery","result","data","chartData","stepMs","map","value","metric","values","name","formattedName","series_name_format"],"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,QAAQ,UAAU,CAAC;AACxC,SACEC,eAAe,EAEfC,wBAAwB,EACxBC,sBAAsB,EACtBC,YAAY,EACZC,YAAY,QACP,aAAa,CAAC;AACrB,SAASC,+BAA+B,EAAEC,wBAAwB,EAAEC,gBAAgB,QAAQ,aAAa,CAAC;AAG1G,OAAO,MAAMC,iBAAiB,GAA8E,OAC1GC,IAAI,EACJC,OAAO,GACJ;QAmCYC,GAAa;IAlC5B,IAAIF,IAAI,CAACG,KAAK,KAAKC,SAAS,IAAIJ,IAAI,CAACG,KAAK,KAAK,IAAI,IAAIH,IAAI,CAACG,KAAK,KAAK,EAAE,EAAE;QACxE,+EAA+E;QAC/E,OAAO;YAAEE,MAAM,EAAE,EAAE;SAAE,CAAC;IACxB,CAAC;IAED,MAAMC,OAAO,GAAGd,wBAAwB,CAACQ,IAAI,CAACO,QAAQ,CAAC,AAAC;IACxD,MAAMC,SAAS,GAAGf,sBAAsB,CAACQ,OAAO,CAACO,SAAS,CAAC,AAAC;IAC5D,MAAMC,IAAI,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,IAAqB,GAArBA,CAAAA,GAAa,GAAbA,QAAQ,CAAC0B,IAAI,cAAb1B,GAAa,WAAQ,GAArBA,KAAAA,CAAqB,GAArBA,GAAa,CAAEyB,MAAM,cAArBzB,IAAqB,cAArBA,IAAqB,GAAI,EAAE,AAAC;IAE3C,qBAAqB;IACrB,MAAM2B,SAAS,GAAmB;QAChC,gEAAgE;QAChErB,SAAS,EAAE;YAAEG,KAAK,EAAErB,YAAY,CAACqB,KAAK,CAAC;YAAEC,GAAG,EAAEtB,YAAY,CAACsB,GAAG,CAAC;SAAE;QACjEkB,MAAM,EAAErB,IAAI,GAAG,IAAI;QAEnBJ,MAAM,EAAEsB,MAAM,CAACI,GAAG,CAAC,CAACC,KAAK,GAAK;YAC5B,MAAM,EAAEC,MAAM,CAAA,EAAEC,MAAM,CAAA,EAAE,GAAGF,KAAK,AAAC;YAEjC,yEAAyE;YACzE,IAAIG,IAAI,GAAGvC,+BAA+B,CAACqC,MAAM,CAAC,AAAC;YACnD,IAAIE,IAAI,KAAK,EAAE,EAAE;gBACfA,IAAI,GAAGhC,KAAK,CAAC;YACf,CAAC;YAED,mEAAmE;YACnE,mDAAmD;YACnD,MAAMiC,aAAa,GAAGpC,IAAI,CAACqC,kBAAkB,GAAGvC,gBAAgB,CAACE,IAAI,CAACqC,kBAAkB,EAAEJ,MAAM,CAAC,GAAGE,IAAI,AAAC;YAEzG,OAAO;gBACLA,IAAI;gBACJD,MAAM,EAAEA,MAAM,CAACH,GAAG,CAACxC,eAAe,CAAC;gBACnC6C,aAAa;aACd,CAAC;QACJ,CAAC,CAAC;KACH,AAAC;IAEF,OAAOP,SAAS,CAAC;AACnB,CAAC,CAAC"}
1
+ {"version":3,"sources":["../../../src/plugins/prometheus-time-series-query/get-time-series-data.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 { Notice, TimeSeriesData } from '@perses-dev/core';\nimport { TimeSeriesQueryPlugin } from '@perses-dev/plugin-system';\nimport { fromUnixTime } from 'date-fns';\nimport {\n parseValueTuple,\n PrometheusClient,\n getDurationStringSeconds,\n getPrometheusTimeRange,\n getRangeStep,\n DEFAULT_PROM,\n} from '../../model';\nimport { getFormattedPrometheusSeriesName, replaceTemplateVariables } from '../../utils';\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 minStep = getDurationStringSeconds(spec.min_step);\n const timeRange = getPrometheusTimeRange(context.timeRange);\n const step = getRangeStep(timeRange, minStep, undefined, context.suggestedStepMs);\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 template variable placeholders in PromQL query\n let query = spec.query.replace('$__rate_interval', `15s`);\n query = replaceTemplateVariables(query, context.variableState);\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 const response = await client.rangeQuery({\n query,\n start,\n end,\n step,\n });\n\n // TODO: What about error responses from Prom that have a response body?\n const result = response.data?.result ?? [];\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: result.map((value) => {\n const { metric, values } = value;\n\n // Account for series_name_format from query editor when determining name to show in legend, tooltip, etc.\n const { name, formattedName } = getFormattedPrometheusSeriesName(query, metric, spec.series_name_format);\n\n return {\n name,\n values: values.map(parseValueTuple),\n formattedName,\n labels: metric,\n };\n }),\n metadata: {\n notices,\n },\n };\n\n return chartData;\n};\n"],"names":["fromUnixTime","parseValueTuple","getDurationStringSeconds","getPrometheusTimeRange","getRangeStep","DEFAULT_PROM","getFormattedPrometheusSeriesName","replaceTemplateVariables","getTimeSeriesData","spec","context","response","query","undefined","series","minStep","min_step","timeRange","step","suggestedStepMs","start","end","utcOffsetSec","Date","getTimezoneOffset","alignedEnd","Math","floor","alignedStart","replace","variableState","client","datasourceStore","getDatasourceClient","datasource","rangeQuery","result","data","notices","status","warnings","warningMessage","push","type","message","chartData","stepMs","map","value","metric","values","name","formattedName","series_name_format","labels","metadata"],"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;AAIjC,SAASA,YAAY,QAAQ,UAAU,CAAC;AACxC,SACEC,eAAe,EAEfC,wBAAwB,EACxBC,sBAAsB,EACtBC,YAAY,EACZC,YAAY,QACP,aAAa,CAAC;AACrB,SAASC,gCAAgC,EAAEC,wBAAwB,QAAQ,aAAa,CAAC;AAGzF,OAAO,MAAMC,iBAAiB,GAA8E,OAC1GC,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CAACoB,KAAK,CAAC;YAAEC,GAAG,EAAErB,YAAY,CAACqB,GAAG,CAAC;SAAE;QACjEyB,MAAM,EAAE5B,IAAI,GAAG,IAAI;QAEnBJ,MAAM,EAAEsB,MAAM,CAACW,GAAG,CAAC,CAACC,KAAK,GAAK;YAC5B,MAAM,EAAEC,MAAM,CAAA,EAAEC,MAAM,CAAA,EAAE,GAAGF,KAAK,AAAC;YAEjC,0GAA0G;YAC1G,MAAM,EAAEG,IAAI,CAAA,EAAEC,aAAa,CAAA,EAAE,GAAG9C,gCAAgC,CAACM,KAAK,EAAEqC,MAAM,EAAExC,IAAI,CAAC4C,kBAAkB,CAAC,AAAC;YAEzG,OAAO;gBACLF,IAAI;gBACJD,MAAM,EAAEA,MAAM,CAACH,GAAG,CAAC9C,eAAe,CAAC;gBACnCmD,aAAa;gBACbE,MAAM,EAAEL,MAAM;aACf,CAAC;QACJ,CAAC,CAAC;QACFM,QAAQ,EAAE;YACRjB,OAAO;SACR;KACF,AAAC;IAEF,OAAOO,SAAS,CAAC;AACnB,CAAC,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { VariableValue } from '@perses-dev/core';
2
2
  import { VariableStateMap } from '@perses-dev/plugin-system';
3
+ import { Metric } from '../model/api-types';
3
4
  export declare function replaceTemplateVariables(text: string, variableState: VariableStateMap): string;
4
5
  export declare function replaceTemplateVariable(text: string, varName: string, templateVariableValue: VariableValue): string;
5
6
  /**
@@ -16,4 +17,11 @@ export declare function getUniqueKeyForPrometheusResult(metricLabels: {
16
17
  }, { removeExprWrap }?: {
17
18
  removeExprWrap?: boolean;
18
19
  }): string;
20
+ export declare function getFormattedPrometheusSeriesName(query: string, metric: Metric, formatter?: string): {
21
+ name: string;
22
+ formattedName?: undefined;
23
+ } | {
24
+ name: string;
25
+ formattedName: string;
26
+ };
19
27
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[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BAAY,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAMlD,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,EAAE,YAAY,EAAE,YAAY,GAAG,MAAM,CAGxF;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,UAqBtD;AAKD,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM;;;;;;EAejG"}
@@ -10,6 +10,7 @@
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 { isEmptyObject } from '@perses-dev/core';
13
14
  export function replaceTemplateVariables(text, variableState) {
14
15
  const variables = parseTemplateVariables(text);
15
16
  let finalText = text;
@@ -92,5 +93,26 @@ const TEMPLATE_VARIABLE_REGEX = /\$(\w+)|\${(\w+)(?:\.([^:^\}]+))?(?::([^\}]+))?
92
93
  }
93
94
  return '';
94
95
  }
96
+ /*
97
+ * Determine human-readable series name to be used in legend and tooltip
98
+ */ export function getFormattedPrometheusSeriesName(query, metric, formatter) {
99
+ if (isEmptyObject(metric)) {
100
+ return {
101
+ name: query
102
+ };
103
+ }
104
+ // Name the series after the metric labels or if no metric, use the query
105
+ let name = getUniqueKeyForPrometheusResult(metric);
106
+ if (name === '') {
107
+ name = query;
108
+ }
109
+ // Query editor allows you to define an optional series_name_format
110
+ // property to customize legend and tooltip display
111
+ const formattedName = formatter ? formatSeriesName(formatter, metric) : name;
112
+ return {
113
+ name,
114
+ formattedName
115
+ };
116
+ }
95
117
 
96
118
  //# sourceMappingURL=utils.js.map
@@ -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 { VariableValue } from '@perses-dev/core';\nimport { VariableStateMap } from '@perses-dev/plugin-system';\n\nexport function replaceTemplateVariables(text: string, variableState: VariableStateMap): string {\n const variables = parseTemplateVariables(text);\n let finalText = text;\n variables.forEach((v) => {\n const variable = variableState[v];\n if (variable && variable?.value) {\n finalText = replaceTemplateVariable(finalText, v, variable?.value);\n }\n });\n\n return finalText;\n}\n\nexport function replaceTemplateVariable(text: string, varName: string, templateVariableValue: VariableValue) {\n const variableTemplate = '$' + varName;\n let replaceString = '';\n if (Array.isArray(templateVariableValue)) {\n replaceString = `(${templateVariableValue.join('|')})`; // regex style\n }\n if (typeof templateVariableValue === 'string') {\n replaceString = templateVariableValue;\n }\n\n return text.replaceAll(variableTemplate, replaceString);\n}\n\n// TODO: Fix this lint error\n// eslint-disable-next-line no-useless-escape\nconst TEMPLATE_VARIABLE_REGEX = /\\$(\\w+)|\\${(\\w+)(?:\\.([^:^\\}]+))?(?::([^\\}]+))?}/gm;\n\n/**\n * Returns a list of template variables\n */\nexport const parseTemplateVariables = (text: string) => {\n const regex = TEMPLATE_VARIABLE_REGEX;\n const matches = new Set<string>();\n let match;\n\n while ((match = regex.exec(text)) !== null) {\n if (match && match.length > 1 && match[1]) {\n matches.add(match[1]);\n }\n }\n // return unique matches\n return Array.from(matches.values());\n};\n\n/**\n * Types for metric labels, used in series_name_format 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 */\nexport function formatSeriesName(inputFormat: string, seriesLabels: SeriesLabels): string {\n const resolveLabelsRegex = /\\{\\{\\s*(.+?)\\s*\\}\\}/g;\n return inputFormat.replace(resolveLabelsRegex, (_, g) => (seriesLabels[g] ? seriesLabels[g] : g));\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 formattter 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 (metricLabels) {\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 === true) {\n return `${stringifiedLabels}`;\n } else {\n return `${metricLabels[metricNameKey]}${stringifiedLabels}`;\n }\n }\n return stringifyPrometheusMetricLabels(metricLabels, removeExprWrap);\n }\n return '';\n}\n"],"names":["replaceTemplateVariables","text","variableState","variables","parseTemplateVariables","finalText","forEach","v","variable","value","replaceTemplateVariable","varName","templateVariableValue","variableTemplate","replaceString","Array","isArray","join","replaceAll","TEMPLATE_VARIABLE_REGEX","regex","matches","Set","match","exec","length","add","from","values","formatSeriesName","inputFormat","seriesLabels","resolveLabelsRegex","replace","_","g","stringifyPrometheusMetricLabels","labels","removeExprWrap","labelStrings","Object","keys","sort","labelName","labelValue","undefined","push","getUniqueKeyForPrometheusResult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AC;AACZ,CAAC"}
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 { isEmptyObject, VariableValue } from '@perses-dev/core';\nimport { VariableStateMap } from '@perses-dev/plugin-system';\nimport { Metric } from '../model/api-types';\n\nexport function replaceTemplateVariables(text: string, variableState: VariableStateMap): string {\n const variables = parseTemplateVariables(text);\n let finalText = text;\n variables.forEach((v) => {\n const variable = variableState[v];\n if (variable && variable?.value) {\n finalText = replaceTemplateVariable(finalText, v, variable?.value);\n }\n });\n\n return finalText;\n}\n\nexport function replaceTemplateVariable(text: string, varName: string, templateVariableValue: VariableValue) {\n const variableTemplate = '$' + varName;\n let replaceString = '';\n if (Array.isArray(templateVariableValue)) {\n replaceString = `(${templateVariableValue.join('|')})`; // regex style\n }\n if (typeof templateVariableValue === 'string') {\n replaceString = templateVariableValue;\n }\n\n return text.replaceAll(variableTemplate, replaceString);\n}\n\n// TODO: Fix this lint error\n// eslint-disable-next-line no-useless-escape\nconst TEMPLATE_VARIABLE_REGEX = /\\$(\\w+)|\\${(\\w+)(?:\\.([^:^\\}]+))?(?::([^\\}]+))?}/gm;\n\n/**\n * Returns a list of template variables\n */\nexport const parseTemplateVariables = (text: string) => {\n const regex = TEMPLATE_VARIABLE_REGEX;\n const matches = new Set<string>();\n let match;\n\n while ((match = regex.exec(text)) !== null) {\n if (match && match.length > 1 && match[1]) {\n matches.add(match[1]);\n }\n }\n // return unique matches\n return Array.from(matches.values());\n};\n\n/**\n * Types for metric labels, used in series_name_format 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 */\nexport function formatSeriesName(inputFormat: string, seriesLabels: SeriesLabels): string {\n const resolveLabelsRegex = /\\{\\{\\s*(.+?)\\s*\\}\\}/g;\n return inputFormat.replace(resolveLabelsRegex, (_, g) => (seriesLabels[g] ? seriesLabels[g] : g));\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 formattter 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 (metricLabels) {\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 === true) {\n return `${stringifiedLabels}`;\n } else {\n return `${metricLabels[metricNameKey]}${stringifiedLabels}`;\n }\n }\n return stringifyPrometheusMetricLabels(metricLabels, removeExprWrap);\n }\n return '';\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 if (isEmptyObject(metric)) {\n return { name: query };\n }\n\n // Name the series after the metric labels or if no metric, use the query\n let name = getUniqueKeyForPrometheusResult(metric);\n if (name === '') {\n name = query;\n }\n\n // Query editor allows you to define an optional series_name_format\n // property to customize legend and tooltip display\n const formattedName = formatter ? formatSeriesName(formatter, metric) : name;\n return { name, formattedName };\n}\n"],"names":["isEmptyObject","replaceTemplateVariables","text","variableState","variables","parseTemplateVariables","finalText","forEach","v","variable","value","replaceTemplateVariable","varName","templateVariableValue","variableTemplate","replaceString","Array","isArray","join","replaceAll","TEMPLATE_VARIABLE_REGEX","regex","matches","Set","match","exec","length","add","from","values","formatSeriesName","inputFormat","seriesLabels","resolveLabelsRegex","replace","_","g","stringifyPrometheusMetricLabels","labels","removeExprWrap","labelStrings","Object","keys","sort","labelName","labelValue","undefined","push","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;AAEjC,SAASA,aAAa,QAAuB,kBAAkB,CAAC;AAIhE,OAAO,SAASC,wBAAwB,CAACC,IAAY,EAAEC,aAA+B,EAAU;IAC9F,MAAMC,SAAS,GAAGC,sBAAsB,CAACH,IAAI,CAAC,AAAC;IAC/C,IAAII,SAAS,GAAGJ,IAAI,AAAC;IACrBE,SAAS,CAACG,OAAO,CAAC,CAACC,CAAC,GAAK;QACvB,MAAMC,QAAQ,GAAGN,aAAa,CAACK,CAAC,CAAC,AAAC;QAClC,IAAIC,QAAQ,IAAIA,CAAAA,QAAQ,aAARA,QAAQ,WAAO,GAAfA,KAAAA,CAAe,GAAfA,QAAQ,CAAEC,KAAK,CAAA,EAAE;YAC/BJ,SAAS,GAAGK,uBAAuB,CAACL,SAAS,EAAEE,CAAC,EAAEC,QAAQ,aAARA,QAAQ,WAAO,GAAfA,KAAAA,CAAe,GAAfA,QAAQ,CAAEC,KAAK,CAAC,CAAC;Q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AAY,EAAEC,aAAa,CAAC,EAAE;YACrE,MAAMI,iBAAiB,GAAGjB,+BAA+B,CACvD;gBACE,GAAGY,YAAY;gBACf,CAACC,aAAa,CAAC,EAAEJ,SAAS;aAC3B,EACDP,cAAc,CACf,AAAC;YACF,IAAIA,cAAc,KAAK,IAAI,EAAE;gBAC3B,OAAO,CAAC,EAAEe,iBAAiB,CAAC,CAAC,CAAC;YAChC,OAAO;gBACL,OAAO,CAAC,EAAEL,YAAY,CAACC,aAAa,CAAC,CAAC,EAAEI,iBAAiB,CAAC,CAAC,CAAC;YAC9D,CAAC;QACH,CAAC;QACD,OAAOjB,+BAA+B,CAACY,YAAY,EAAEV,cAAc,CAAC,CAAC;IACvE,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;CAEC,GACD,OAAO,SAASgB,gCAAgC,CAACC,KAAa,EAAEC,MAAc,EAAEC,SAAkB,EAAE;IAClG,IAAI1D,aAAa,CAACyD,MAAM,CAAC,EAAE;QACzB,OAAO;YAAEE,IAAI,EAAEH,KAAK;SAAE,CAAC;IACzB,CAAC;IAED,yEAAyE;IACzE,IAAIG,IAAI,GAAGX,+BAA+B,CAACS,MAAM,CAAC,AAAC;IACnD,IAAIE,IAAI,KAAK,EAAE,EAAE;QACfA,IAAI,GAAGH,KAAK,CAAC;IACf,CAAC;IAED,mEAAmE;IACnE,mDAAmD;IACnD,MAAMI,aAAa,GAAGF,SAAS,GAAG5B,gBAAgB,CAAC4B,SAAS,EAAED,MAAM,CAAC,GAAGE,IAAI,AAAC;IAC7E,OAAO;QAAEA,IAAI;QAAEC,aAAa;KAAE,CAAC;AACjC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@perses-dev/prometheus-plugin",
3
- "version": "0.24.0",
3
+ "version": "0.26.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,11 +31,10 @@
31
31
  "dependencies": {
32
32
  "@lezer/highlight": "^1.0.0",
33
33
  "@lezer/lr": "^1.2.0",
34
- "@perses-dev/components": "0.24.0",
35
- "@perses-dev/core": "0.24.0",
36
- "@perses-dev/plugin-system": "0.24.0",
37
- "@prometheus-io/codemirror-promql": "^0.40.5",
38
- "@prometheus-io/lezer-promql": "^0.37.0",
34
+ "@perses-dev/components": "0.26.0",
35
+ "@perses-dev/core": "0.26.0",
36
+ "@perses-dev/plugin-system": "0.26.0",
37
+ "@prometheus-io/codemirror-promql": "^0.43.0",
39
38
  "@uiw/react-codemirror": "^4.19.1",
40
39
  "date-fns": "^2.28.0",
41
40
  "immer": "^9.0.15"