@perses-dev/prometheus-plugin 0.23.1 → 0.25.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) {
@@ -53,16 +54,17 @@ function fetchWithGet(apiURI, params, queryOptions) {
53
54
  });
54
55
  }
55
56
  function fetchWithPost(apiURI, params, queryOptions) {
56
- const { datasourceUrl } = queryOptions;
57
+ const { datasourceUrl , headers } = queryOptions;
57
58
  const url = `${datasourceUrl}${apiURI}`;
58
59
  const init = {
59
60
  method: 'POST',
60
61
  headers: {
61
- 'Content-Type': 'application/x-www-form-urlencoded'
62
+ 'Content-Type': 'application/x-www-form-urlencoded',
63
+ ...headers
62
64
  },
63
65
  body: createSearchParams(params)
64
66
  };
65
- return (0, _core.fetchJson)(url, init);
67
+ return fetchResults(url, init);
66
68
  }
67
69
  /**
68
70
  * Creates URLSearchParams from a request params object.
@@ -85,3 +87,11 @@ function fetchWithPost(apiURI, params, queryOptions) {
85
87
  }
86
88
  return searchParams;
87
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 } = 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,17 +34,21 @@ const _model = require("../model");
34
34
  options: {
35
35
  datasourceUrl
36
36
  },
37
- instantQuery: (params)=>(0, _model.instantQuery)(params, {
38
- datasourceUrl
37
+ instantQuery: (params, headers)=>(0, _model.instantQuery)(params, {
38
+ datasourceUrl,
39
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
39
40
  }),
40
- rangeQuery: (params)=>(0, _model.rangeQuery)(params, {
41
- datasourceUrl
41
+ rangeQuery: (params, headers)=>(0, _model.rangeQuery)(params, {
42
+ datasourceUrl,
43
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
42
44
  }),
43
- labelNames: (params)=>(0, _model.labelNames)(params, {
44
- datasourceUrl
45
+ labelNames: (params, headers)=>(0, _model.labelNames)(params, {
46
+ datasourceUrl,
47
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
45
48
  }),
46
- labelValues: (params)=>(0, _model.labelValues)(params, {
47
- datasourceUrl
49
+ labelValues: (params, headers)=>(0, _model.labelValues)(params, {
50
+ datasourceUrl,
51
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
48
52
  })
49
53
  };
50
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
@@ -63,8 +77,6 @@ const getTimeSeriesData = async (spec, context)=>{
63
77
  end: (0, _dateFns.fromUnixTime)(end)
64
78
  },
65
79
  stepMs: step * 1000,
66
- // TODO: Maybe do a proper Iterable implementation that defers some of this
67
- // processing until its needed
68
80
  series: result.map((value)=>{
69
81
  const { metric , values } = value;
70
82
  // Name the series after the metric labels or if no metric, use the query
@@ -72,15 +84,19 @@ const getTimeSeriesData = async (spec, context)=>{
72
84
  if (name === '') {
73
85
  name = query;
74
86
  }
75
- // query editor allows you to define an optional series_name_format
87
+ // Query editor allows you to define an optional series_name_format
76
88
  // property to customize legend and tooltip display
77
89
  const formattedName = spec.series_name_format ? (0, _utils.formatSeriesName)(spec.series_name_format, metric) : name;
78
90
  return {
79
91
  name,
80
92
  values: values.map(_model.parseValueTuple),
81
- formattedName
93
+ formattedName,
94
+ labels: metric
82
95
  };
83
- })
96
+ }),
97
+ metadata: {
98
+ notices
99
+ }
84
100
  };
85
101
  return chartData;
86
102
  };
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","sourceRoot":"","sources":["../../src/model/api-types.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGlD,YAAY,EAAE,cAAc,EAAE,CAAC;AAE/B,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,MAAM,EAAE,SAAS,CAAC;IAClB,IAAI,EAAE,CAAC,CAAC;IACR,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED,MAAM,WAAW,aAAa,CAAC,CAAC;IAC9B,MAAM,EAAE,OAAO,CAAC;IAChB,IAAI,CAAC,EAAE,CAAC,CAAC;IACT,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,oBAAY,WAAW,CAAC,CAAC,IAAI,eAAe,CAAC,CAAC,CAAC,GAA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["../../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,32 +1,48 @@
1
+ import { RequestHeaders } from '@perses-dev/core';
2
+ import { DatasourceClient } from '@perses-dev/plugin-system';
1
3
  import { InstantQueryRequestParameters, InstantQueryResponse, LabelNamesRequestParameters, LabelNamesResponse, LabelValuesRequestParameters, LabelValuesResponse, RangeQueryRequestParameters, RangeQueryResponse } from './api-types';
2
4
  interface PrometheusClientOptions {
3
5
  datasourceUrl: string;
6
+ headers?: RequestHeaders;
4
7
  }
5
- export interface PrometheusClient {
8
+ export interface PrometheusClient extends DatasourceClient {
6
9
  options: PrometheusClientOptions;
7
- instantQuery(params: InstantQueryRequestParameters): Promise<InstantQueryResponse>;
8
- rangeQuery(params: RangeQueryRequestParameters): Promise<RangeQueryResponse>;
9
- labelNames(params: LabelNamesRequestParameters): Promise<LabelNamesResponse>;
10
- 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>;
11
14
  }
12
15
  export interface QueryOptions {
13
16
  datasourceUrl: string;
17
+ headers?: RequestHeaders;
14
18
  }
15
19
  /**
16
20
  * Calls the `/api/v1/query` endpoint to get metrics data.
17
21
  */
18
- 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
+ }>;
19
25
  /**
20
26
  * Calls the `/api/v1/query_range` endpoint to get metrics data.
21
27
  */
22
- 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
+ }>;
23
31
  /**
24
32
  * Calls the `/api/v1/labels` endpoint to get a list of label names.
25
33
  */
26
- 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
+ }>;
27
37
  /**
28
38
  * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of values for a label.
29
39
  */
30
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
+ }>;
31
47
  export {};
32
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":"AAcA,OAAO,EACL,6BAA6B,EAC7B,oBAAoB,EACpB,2BAA2B,EAC3B,kBAAkB,EAClB,4BAA4B,EAC5B,mBAAmB,EACnB,2BAA2B,EAC3B,kBAAkB,EACnB,MAAM,aAAa,CAAC;AAErB,UAAU,uBAAuB;IAC/B,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,uBAAuB,CAAC;IACjC,YAAY,CAAC,MAAM,EAAE,6BAA6B,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IACnF,UAAU,CAAC,MAAM,EAAE,2BAA2B,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IAC7E,UAAU,CAAC,MAAM,EAAE,2BAA2B,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IAC7E,WAAW,CAAC,MAAM,EA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AE,2BAA2B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACvG,WAAW,CAAC,MAAM,EAAE,4BAA4B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;CAC3G;AAED,MAAM,WAAW,YAAY;IAC3B,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,cAAc,CAAC;CAC1B;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,6BAA6B,EAAE,YAAY,EAAE,YAAY;;GAE7F;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,2BAA2B,EAAE,YAAY,EAAE,YAAY;;GAEzF;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,2BAA2B,EAAE,YAAY,EAAE,YAAY;;GAEzF;AAED;;GAEG;AACH,wBAAgB,WAAW,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) {
@@ -45,16 +45,17 @@ function fetchWithGet(apiURI, params, queryOptions) {
45
45
  });
46
46
  }
47
47
  function fetchWithPost(apiURI, params, queryOptions) {
48
- const { datasourceUrl } = queryOptions;
48
+ const { datasourceUrl , headers } = queryOptions;
49
49
  const url = `${datasourceUrl}${apiURI}`;
50
50
  const init = {
51
51
  method: 'POST',
52
52
  headers: {
53
- 'Content-Type': 'application/x-www-form-urlencoded'
53
+ 'Content-Type': 'application/x-www-form-urlencoded',
54
+ ...headers
54
55
  },
55
56
  body: createSearchParams(params)
56
57
  };
57
- return fetchJson(url, init);
58
+ return fetchResults(url, init);
58
59
  }
59
60
  /**
60
61
  * Creates URLSearchParams from a request params object.
@@ -77,5 +78,15 @@ function fetchWithPost(apiURI, params, queryOptions) {
77
78
  }
78
79
  return searchParams;
79
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
+ }
80
91
 
81
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 } 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}\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}\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 } = queryOptions;\n\n const url = `${datasourceUrl}${apiURI}`;\n const init = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\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","init","headers","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,QAAQ,kBAAkB,CAAC;AA4B7C;;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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,CAAC,CAAC;AACzC,CAAC;AAWD;;CAEC,GACD,SAASH,kBAAkB,CAA6Bd,MAAS,EAAE;IACjE,MAAMO,YAAY,GAAG,IAAIa,eAAe,EAAE,AAAC;IAC3C,IAAK,MAAMC,GAAG,IAAIrB,MAAM,CAAE;QACxB,MAAMsB,KAAK,GAAetB,MAAM,CAACqB,GAAG,CAAC,AAAC;QACtC,IAAIC,KAAK,KAAKC,SAAS,EAAE,SAAS;QAElC,IAAI,OAAOD,KAAK,KAAK,QAAQ,EAAE;YAC7Bf,YAAY,CAACiB,MAAM,CAACH,GAAG,EAAEC,KAAK,CAAC,CAAC;YAChC,SAAS;QACX,CAAC;QAED,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;YAC7Bf,YAAY,CAACiB,MAAM,CAACH,GAAG,EAAEC,KAAK,CAACP,QAAQ,EAAE,CAAC,CAAC;YAC3C,SAAS;QACX,CAAC;QAED,KAAK,MAAMU,GAAG,IAAIH,KAAK,CAAE;YACvBf,YAAY,CAACiB,MAAM,CAACH,GAAG,EAAEI,GAAG,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IACD,OAAOlB,YAAY,CAAC;AACtB,CAAC"}
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 { 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,sE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,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"}
@@ -1,7 +1,9 @@
1
+ import { RequestHeaders } from '@perses-dev/core';
1
2
  import { DatasourcePlugin } from '@perses-dev/plugin-system';
2
3
  import { PrometheusClient } from '../model';
3
4
  export interface PrometheusDatasourceSpec {
4
5
  direct_url?: string;
6
+ headers?: RequestHeaders;
5
7
  }
6
8
  export declare const PrometheusDatasource: DatasourcePlugin<PrometheusDatasourceSpec, PrometheusClient>;
7
9
  //# sourceMappingURL=prometheus-datasource.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prometheus-datasource.d.ts","sourceRoot":"","sources":["../../src/plugins/prometheus-datasource.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAqD,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE/F,MAAM,WAAW,wBAAwB;IACvC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AA2BD,eAAO,MAAM,oBAAoB,EAAE,gBAAgB,CAAC,wBAAwB,EAAE,gBAAgB,CAI7F,CAAC"}
1
+ {"version":3,"file":"prometheus-datasource.d.ts","sourceRoot":"","sources":["../../src/plugins/prometheus-datasource.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAqD,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE/F,MAAM,WAAW,wBAAwB;IACvC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,cAAc,CAAC;CAC1B;AA2BD,eAAO,MAAM,oBAAoB,EAAE,gBAAgB,CAAC,wBAAwB,EAAE,gBAAgB,CAI7F,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 } = 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,17 +26,21 @@ import { instantQuery, rangeQuery, labelNames, labelValues } from '../model';
26
26
  options: {
27
27
  datasourceUrl
28
28
  },
29
- instantQuery: (params)=>instantQuery(params, {
30
- datasourceUrl
29
+ instantQuery: (params, headers)=>instantQuery(params, {
30
+ datasourceUrl,
31
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
31
32
  }),
32
- rangeQuery: (params)=>rangeQuery(params, {
33
- datasourceUrl
33
+ rangeQuery: (params, headers)=>rangeQuery(params, {
34
+ datasourceUrl,
35
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
34
36
  }),
35
- labelNames: (params)=>labelNames(params, {
36
- datasourceUrl
37
+ labelNames: (params, headers)=>labelNames(params, {
38
+ datasourceUrl,
39
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
37
40
  }),
38
- labelValues: (params)=>labelValues(params, {
39
- datasourceUrl
41
+ labelValues: (params, headers)=>labelValues(params, {
42
+ datasourceUrl,
43
+ headers: headers !== null && headers !== void 0 ? headers : specHeaders
40
44
  })
41
45
  };
42
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 { DatasourcePlugin } from '@perses-dev/plugin-system';\nimport { instantQuery, rangeQuery, labelNames, labelValues, PrometheusClient } from '../model';\n\nexport interface PrometheusDatasourceSpec {\n direct_url?: string;\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 } = 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 }),\n rangeQuery: (params) => rangeQuery(params, { datasourceUrl }),\n labelNames: (params) => labelNames(params, { datasourceUrl }),\n labelValues: (params) => labelValues(params, { datasourceUrl }),\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","proxyUrl","datasourceUrl","undefined","Error","params","PrometheusDatasource","OptionsEditorComponent","createInitialOptions"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AAC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ugins/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,AAAC;IAClD,MAAM,EAAEK,QAAQ,CAAA,EAAE,GAAGJ,OAAO,AAAC;IAE7B,4FAA4F;IAC5F,MAAMK,aAAa,GAAGJ,UAAU,aAAVA,UAAU,cAAVA,UAAU,GAAIG,QAAQ,AAAC;IAC7C,IAAIC,aAAa,KAAKC,SAAS,EAAE;QAC/B,MAAM,IAAIC,KAAK,CAAC,6FAA6F,CAAC,CAAC;IACjH,CAAC;IAED,qFAAqF;IACrF,OAAO;QACLP,OAAO,EAAE;YACPK,aAAa;SACd;QACDX,YAAY,EAAE,CAACc,MAAM,EAAEN,OAAO,GAAKR,YAAY,CAACc,MAAM,EAAE;gBAAEH,aAAa;gBAAEH,OAAO,EAAEA,OAAO,aAAPA,OAAO,cAAPA,OAAO,GAAIC,WAAW;aAAE,CAAC;QAC3GR,UAAU,EAAE,CAACa,MAAM,EAAEN,OAAO,GAAKP,UAAU,CAACa,MAAM,EAAE;gBAAEH,aAAa;gBAAEH,OAAO,EAAEA,OAAO,aAAPA,OAAO,cAAPA,OAAO,GAAIC,WAAW;aAAE,CAAC;QACvGP,UAAU,EAAE,CAACY,MAAM,EAAEN,OAAO,GAAKN,UAAU,CAACY,MAAM,EAAE;gBAAEH,aAAa;gBAAEH,OAAO,EAAEA,OAAO,aAAPA,OAAO,cAAPA,OAAO,GAAIC,WAAW;aAAE,CAAC;QACvGN,WAAW,EAAE,CAACW,MAAM,EAAEN,OAAO,GAAKL,WAAW,CAACW,MAAM,EAAE;gBAAEH,aAAa;gBAAEH,OAAO,EAAEA,OAAO,aAAPA,OAAO,cAAPA,OAAO,GAAIC,WAAW;aAAE,CAAC;KAC1G,CAAC;AACJ,CAAC,AAAC;AAEF,OAAO,MAAMM,oBAAoB,GAAiE;IAChGX,YAAY;IACZY,sBAAsB,EAAE,IAAM,IAAI;IAClCC,oBAAoB,EAAE,IAAO,CAAA;YAAEV,UAAU,EAAE,EAAE;SAAE,CAAA,AAAC;CACjD,CAAC"}
@@ -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":"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,CAsEvG,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,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,CAqFvG,CAAC"}
@@ -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
@@ -55,8 +69,6 @@ export const getTimeSeriesData = async (spec, context)=>{
55
69
  end: fromUnixTime(end)
56
70
  },
57
71
  stepMs: step * 1000,
58
- // TODO: Maybe do a proper Iterable implementation that defers some of this
59
- // processing until its needed
60
72
  series: result.map((value)=>{
61
73
  const { metric , values } = value;
62
74
  // Name the series after the metric labels or if no metric, use the query
@@ -64,15 +76,19 @@ export const getTimeSeriesData = async (spec, context)=>{
64
76
  if (name === '') {
65
77
  name = query;
66
78
  }
67
- // query editor allows you to define an optional series_name_format
79
+ // Query editor allows you to define an optional series_name_format
68
80
  // property to customize legend and tooltip display
69
81
  const formattedName = spec.series_name_format ? formatSeriesName(spec.series_name_format, metric) : name;
70
82
  return {
71
83
  name,
72
84
  values: values.map(parseValueTuple),
73
- formattedName
85
+ formattedName,
86
+ labels: metric
74
87
  };
75
- })
88
+ }),
89
+ metadata: {
90
+ notices
91
+ }
76
92
  };
77
93
  return chartData;
78
94
  };
@@ -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 // TODO: Maybe do a proper Iterable implementation that defers some of this\n // processing until its needed\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;QAC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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 } from '@perses-dev/core';\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 // 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 // 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 labels: metric,\n };\n }),\n metadata: {\n notices,\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","notices","status","warnings","warningMessage","push","type","message","chartData","stepMs","map","value","metric","values","name","formattedName","series_name_format","labels","metadata"],"mappings":"AAAA,oCAAoC;AACpC,kEAA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ED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@perses-dev/prometheus-plugin",
3
- "version": "0.23.1",
3
+ "version": "0.25.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",
@@ -20,7 +20,8 @@
20
20
  "build": "concurrently \"npm:build:*\"",
21
21
  "build:cjs": "swc ./src -d dist/cjs --config-file ../.cjs.swcrc",
22
22
  "build:esm": "swc ./src -d dist --config-file ../.swcrc",
23
- "build:types": "tsc --emitDeclarationOnly --declaration --preserveWatchOutput",
23
+ "build:types": "tsc --project tsconfig.build.json",
24
+ "type-check": "tsc --noEmit",
24
25
  "start": "concurrently -P \"npm:build:* -- {*}\" -- --watch",
25
26
  "test": "TZ=UTC jest",
26
27
  "test:watch": "TZ=UTC jest --watch",
@@ -30,9 +31,9 @@
30
31
  "dependencies": {
31
32
  "@lezer/highlight": "^1.0.0",
32
33
  "@lezer/lr": "^1.2.0",
33
- "@perses-dev/components": "0.23.1",
34
- "@perses-dev/core": "0.23.1",
35
- "@perses-dev/plugin-system": "0.23.1",
34
+ "@perses-dev/components": "0.25.0",
35
+ "@perses-dev/core": "0.25.0",
36
+ "@perses-dev/plugin-system": "0.25.0",
36
37
  "@prometheus-io/codemirror-promql": "^0.40.5",
37
38
  "@prometheus-io/lezer-promql": "^0.37.0",
38
39
  "@uiw/react-codemirror": "^4.19.1",
@@ -1,172 +0,0 @@
1
- // Copyright 2023 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
- "use strict";
14
- Object.defineProperty(exports, "__esModule", {
15
- value: true
16
- });
17
- const _utils = require("./utils");
18
- describe('parseTemplateVariables()', ()=>{
19
- const tests = [
20
- {
21
- text: 'hello $var1 world $var2',
22
- variables: [
23
- 'var1',
24
- 'var2'
25
- ]
26
- }
27
- ];
28
- tests.forEach(({ text , variables })=>{
29
- it(`parses ${text}`, ()=>{
30
- expect((0, _utils.parseTemplateVariables)(text)).toEqual(variables);
31
- });
32
- });
33
- });
34
- describe('replaceTemplateVariable()', ()=>{
35
- const tests = [
36
- {
37
- text: 'hello $var1',
38
- varName: 'var1',
39
- value: 'world',
40
- expected: 'hello world'
41
- },
42
- {
43
- text: 'hello $var1 $var1',
44
- varName: 'var1',
45
- value: 'world',
46
- expected: 'hello world world'
47
- },
48
- {
49
- text: 'hello $var1',
50
- varName: 'var1',
51
- value: [
52
- 'world',
53
- 'w'
54
- ],
55
- expected: 'hello (world|w)'
56
- },
57
- {
58
- text: 'hello $var1 $var1',
59
- varName: 'var1',
60
- value: [
61
- 'world',
62
- 'w'
63
- ],
64
- expected: 'hello (world|w) (world|w)'
65
- }
66
- ];
67
- tests.forEach(({ text , value , varName , expected })=>{
68
- it(`replaces ${text} ${value}`, ()=>{
69
- expect((0, _utils.replaceTemplateVariable)(text, varName, value)).toEqual(expected);
70
- });
71
- });
72
- });
73
- describe('replaceTemplateVariables()', ()=>{
74
- const tests = [
75
- {
76
- text: 'hello $var1 $var2',
77
- state: {
78
- var1: {
79
- value: 'world',
80
- loading: false
81
- },
82
- var2: {
83
- value: 'world',
84
- loading: false
85
- }
86
- },
87
- expected: 'hello world world'
88
- },
89
- {
90
- text: 'hello $var1 $var2',
91
- state: {
92
- var1: {
93
- value: 'world',
94
- loading: false
95
- },
96
- var2: {
97
- value: [
98
- 'a',
99
- 'b'
100
- ],
101
- loading: false
102
- }
103
- },
104
- expected: 'hello world (a|b)'
105
- }
106
- ];
107
- tests.forEach(({ text , state , expected })=>{
108
- it(`replaces ${text} ${JSON.stringify(state)}`, ()=>{
109
- expect((0, _utils.replaceTemplateVariables)(text, state)).toEqual(expected);
110
- });
111
- });
112
- });
113
- describe('formatSeriesName', ()=>{
114
- it('should resolve label name tokens to label values from query response', ()=>{
115
- // example from query: node_load15{instance=~\"(demo.do.prometheus.io:9100)\",job='$job'}
116
- const inputFormat = 'Test {{job}} {{instance}}';
117
- const metric = {
118
- __name__: 'node_load15',
119
- env: 'demo',
120
- instance: 'demo.do.prometheus.io:9100',
121
- job: 'node'
122
- };
123
- const output = 'Test node demo.do.prometheus.io:9100';
124
- expect((0, _utils.formatSeriesName)(inputFormat, metric)).toEqual(output);
125
- });
126
- });
127
- describe('getUniqueKeyForPrometheusResult', ()=>{
128
- let labels = {};
129
- beforeEach(()=>{
130
- labels = {};
131
- });
132
- it('should be a formatted prometheus string', ()=>{
133
- labels = {
134
- ['foo']: 'bar'
135
- };
136
- const result = (0, _utils.getUniqueKeyForPrometheusResult)(labels);
137
- expect(result).toEqual('{foo="bar"}');
138
- });
139
- it('should be formatted with "', ()=>{
140
- labels = {
141
- ['foo']: 'bar'
142
- };
143
- const result = (0, _utils.getUniqueKeyForPrometheusResult)(labels, {
144
- removeExprWrap: true
145
- });
146
- expect(result).toEqual('{"foo":"bar"}');
147
- });
148
- it('should be formatted with __name__ removed', ()=>{
149
- labels = {
150
- __name__: 'node_memory_Buffers_bytes',
151
- env: 'demo',
152
- instance: 'demo.do.prometheus.io:9100',
153
- job: 'node'
154
- };
155
- const result = (0, _utils.getUniqueKeyForPrometheusResult)(labels, {
156
- removeExprWrap: true
157
- });
158
- expect(result).toEqual('{"env":"demo","instance":"demo.do.prometheus.io:9100","job":"node"}');
159
- });
160
- it('should return a valid query to filter by label', ()=>{
161
- labels = {
162
- __name__: 'node_memory_Buffers_bytes',
163
- env: 'demo',
164
- instance: 'demo.do.prometheus.io:9100',
165
- job: 'node'
166
- };
167
- const result = (0, _utils.getUniqueKeyForPrometheusResult)(labels, {
168
- removeExprWrap: false
169
- });
170
- expect(result).toEqual('node_memory_Buffers_bytes{env="demo",instance="demo.do.prometheus.io:9100",job="node"}');
171
- });
172
- });
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=utils.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.test.d.ts","sourceRoot":"","sources":["../../src/utils/utils.test.ts"],"names":[],"mappings":""}
@@ -1,170 +0,0 @@
1
- // Copyright 2023 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 { parseTemplateVariables, replaceTemplateVariable, replaceTemplateVariables, formatSeriesName, getUniqueKeyForPrometheusResult } from './utils';
14
- describe('parseTemplateVariables()', ()=>{
15
- const tests = [
16
- {
17
- text: 'hello $var1 world $var2',
18
- variables: [
19
- 'var1',
20
- 'var2'
21
- ]
22
- }
23
- ];
24
- tests.forEach(({ text , variables })=>{
25
- it(`parses ${text}`, ()=>{
26
- expect(parseTemplateVariables(text)).toEqual(variables);
27
- });
28
- });
29
- });
30
- describe('replaceTemplateVariable()', ()=>{
31
- const tests = [
32
- {
33
- text: 'hello $var1',
34
- varName: 'var1',
35
- value: 'world',
36
- expected: 'hello world'
37
- },
38
- {
39
- text: 'hello $var1 $var1',
40
- varName: 'var1',
41
- value: 'world',
42
- expected: 'hello world world'
43
- },
44
- {
45
- text: 'hello $var1',
46
- varName: 'var1',
47
- value: [
48
- 'world',
49
- 'w'
50
- ],
51
- expected: 'hello (world|w)'
52
- },
53
- {
54
- text: 'hello $var1 $var1',
55
- varName: 'var1',
56
- value: [
57
- 'world',
58
- 'w'
59
- ],
60
- expected: 'hello (world|w) (world|w)'
61
- }
62
- ];
63
- tests.forEach(({ text , value , varName , expected })=>{
64
- it(`replaces ${text} ${value}`, ()=>{
65
- expect(replaceTemplateVariable(text, varName, value)).toEqual(expected);
66
- });
67
- });
68
- });
69
- describe('replaceTemplateVariables()', ()=>{
70
- const tests = [
71
- {
72
- text: 'hello $var1 $var2',
73
- state: {
74
- var1: {
75
- value: 'world',
76
- loading: false
77
- },
78
- var2: {
79
- value: 'world',
80
- loading: false
81
- }
82
- },
83
- expected: 'hello world world'
84
- },
85
- {
86
- text: 'hello $var1 $var2',
87
- state: {
88
- var1: {
89
- value: 'world',
90
- loading: false
91
- },
92
- var2: {
93
- value: [
94
- 'a',
95
- 'b'
96
- ],
97
- loading: false
98
- }
99
- },
100
- expected: 'hello world (a|b)'
101
- }
102
- ];
103
- tests.forEach(({ text , state , expected })=>{
104
- it(`replaces ${text} ${JSON.stringify(state)}`, ()=>{
105
- expect(replaceTemplateVariables(text, state)).toEqual(expected);
106
- });
107
- });
108
- });
109
- describe('formatSeriesName', ()=>{
110
- it('should resolve label name tokens to label values from query response', ()=>{
111
- // example from query: node_load15{instance=~\"(demo.do.prometheus.io:9100)\",job='$job'}
112
- const inputFormat = 'Test {{job}} {{instance}}';
113
- const metric = {
114
- __name__: 'node_load15',
115
- env: 'demo',
116
- instance: 'demo.do.prometheus.io:9100',
117
- job: 'node'
118
- };
119
- const output = 'Test node demo.do.prometheus.io:9100';
120
- expect(formatSeriesName(inputFormat, metric)).toEqual(output);
121
- });
122
- });
123
- describe('getUniqueKeyForPrometheusResult', ()=>{
124
- let labels = {};
125
- beforeEach(()=>{
126
- labels = {};
127
- });
128
- it('should be a formatted prometheus string', ()=>{
129
- labels = {
130
- ['foo']: 'bar'
131
- };
132
- const result = getUniqueKeyForPrometheusResult(labels);
133
- expect(result).toEqual('{foo="bar"}');
134
- });
135
- it('should be formatted with "', ()=>{
136
- labels = {
137
- ['foo']: 'bar'
138
- };
139
- const result = getUniqueKeyForPrometheusResult(labels, {
140
- removeExprWrap: true
141
- });
142
- expect(result).toEqual('{"foo":"bar"}');
143
- });
144
- it('should be formatted with __name__ removed', ()=>{
145
- labels = {
146
- __name__: 'node_memory_Buffers_bytes',
147
- env: 'demo',
148
- instance: 'demo.do.prometheus.io:9100',
149
- job: 'node'
150
- };
151
- const result = getUniqueKeyForPrometheusResult(labels, {
152
- removeExprWrap: true
153
- });
154
- expect(result).toEqual('{"env":"demo","instance":"demo.do.prometheus.io:9100","job":"node"}');
155
- });
156
- it('should return a valid query to filter by label', ()=>{
157
- labels = {
158
- __name__: 'node_memory_Buffers_bytes',
159
- env: 'demo',
160
- instance: 'demo.do.prometheus.io:9100',
161
- job: 'node'
162
- };
163
- const result = getUniqueKeyForPrometheusResult(labels, {
164
- removeExprWrap: false
165
- });
166
- expect(result).toEqual('node_memory_Buffers_bytes{env="demo",instance="demo.do.prometheus.io:9100",job="node"}');
167
- });
168
- });
169
-
170
- //# sourceMappingURL=utils.test.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/utils/utils.test.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 {\n parseTemplateVariables,\n replaceTemplateVariable,\n replaceTemplateVariables,\n formatSeriesName,\n getUniqueKeyForPrometheusResult,\n} from './utils';\n\ndescribe('parseTemplateVariables()', () => {\n const tests = [\n {\n text: 'hello $var1 world $var2',\n variables: ['var1', 'var2'],\n },\n ];\n\n tests.forEach(({ text, variables }) => {\n it(`parses ${text}`, () => {\n expect(parseTemplateVariables(text)).toEqual(variables);\n });\n });\n});\n\ndescribe('replaceTemplateVariable()', () => {\n const tests = [\n {\n text: 'hello $var1',\n varName: 'var1',\n value: 'world',\n expected: 'hello world',\n },\n {\n text: 'hello $var1 $var1',\n varName: 'var1',\n value: 'world',\n expected: 'hello world world',\n },\n {\n text: 'hello $var1',\n varName: 'var1',\n value: ['world', 'w'],\n expected: 'hello (world|w)',\n },\n {\n text: 'hello $var1 $var1',\n varName: 'var1',\n value: ['world', 'w'],\n expected: 'hello (world|w) (world|w)',\n },\n ];\n\n tests.forEach(({ text, value, varName, expected }) => {\n it(`replaces ${text} ${value}`, () => {\n expect(replaceTemplateVariable(text, varName, value)).toEqual(expected);\n });\n });\n});\n\ndescribe('replaceTemplateVariables()', () => {\n const tests = [\n {\n text: 'hello $var1 $var2',\n state: {\n var1: { value: 'world', loading: false },\n var2: { value: 'world', loading: false },\n },\n expected: 'hello world world',\n },\n {\n text: 'hello $var1 $var2',\n state: {\n var1: { value: 'world', loading: false },\n var2: { value: ['a', 'b'], loading: false },\n },\n expected: 'hello world (a|b)',\n },\n ];\n\n tests.forEach(({ text, state, expected }) => {\n it(`replaces ${text} ${JSON.stringify(state)}`, () => {\n expect(replaceTemplateVariables(text, state)).toEqual(expected);\n });\n });\n});\n\ndescribe('formatSeriesName', () => {\n it('should resolve label name tokens to label values from query response', () => {\n // example from query: node_load15{instance=~\\\"(demo.do.prometheus.io:9100)\\\",job='$job'}\n const inputFormat = 'Test {{job}} {{instance}}';\n\n const metric = {\n __name__: 'node_load15',\n env: 'demo',\n instance: 'demo.do.prometheus.io:9100',\n job: 'node',\n };\n\n const output = 'Test node demo.do.prometheus.io:9100';\n\n expect(formatSeriesName(inputFormat, metric)).toEqual(output);\n });\n});\n\ndescribe('getUniqueKeyForPrometheusResult', () => {\n let labels: { [key: string]: string } = {};\n beforeEach(() => {\n labels = {};\n });\n\n it('should be a formatted prometheus string', () => {\n labels = { ['foo']: 'bar' };\n const result = getUniqueKeyForPrometheusResult(labels);\n expect(result).toEqual('{foo=\"bar\"}');\n });\n\n it('should be formatted with \"', () => {\n labels = { ['foo']: 'bar' };\n const result = getUniqueKeyForPrometheusResult(labels, { removeExprWrap: true });\n expect(result).toEqual('{\"foo\":\"bar\"}');\n });\n\n it('should be formatted with __name__ removed', () => {\n labels = {\n __name__: 'node_memory_Buffers_bytes',\n env: 'demo',\n instance: 'demo.do.prometheus.io:9100',\n job: 'node',\n };\n const result = getUniqueKeyForPrometheusResult(labels, { removeExprWrap: true });\n expect(result).toEqual('{\"env\":\"demo\",\"instance\":\"demo.do.prometheus.io:9100\",\"job\":\"node\"}');\n });\n\n it('should return a valid query to filter by label', () => {\n labels = {\n __name__: 'node_memory_Buffers_bytes',\n env: 'demo',\n instance: 'demo.do.prometheus.io:9100',\n job: 'node',\n };\n const result = getUniqueKeyForPrometheusResult(labels, { removeExprWrap: false });\n expect(result).toEqual('node_memory_Buffers_bytes{env=\"demo\",instance=\"demo.do.prometheus.io:9100\",job=\"node\"}');\n });\n});\n"],"names":["parseTemplateVariables","replaceTemplateVariable","replaceTemplateVariables","formatSeriesName","getUniqueKeyForPrometheusResult","describe","tests","text","variables","forEach","it","expect","toEqual","varName","value","expected","state","var1","loading","var2","JSON","stringify","inputFormat","metric","__name__","env","instance","job","output","labels","beforeEach","result","removeExprWrap"],"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,SACEA,sBAAsB,EACtBC,uBAAuB,EACvBC,wBAAwB,EACxBC,gBAAgB,EAChBC,+BAA+B,QAC1B,SAAS,CAAC;AAEjBC,QAAQ,CAAC,0BAA0B,EAAE,IAAM;IACzC,MAAMC,KAAK,GAAG;QACZ;YACEC,IAAI,EAAE,yBAAyB;YAC/BC,SAAS,EAAE;gBAAC,MAAM;gBAAE,MAAM;aAAC;SAC5B;KACF,AAAC;IAEFF,KAAK,CAACG,OAAO,CAAC,CAAC,E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