@perses-dev/prometheus-plugin 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/index.d.ts +3 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +50 -0
  4. package/dist/model/api-types.d.ts +80 -0
  5. package/dist/model/api-types.d.ts.map +1 -0
  6. package/dist/model/api-types.js +13 -0
  7. package/dist/model/datasource.d.ts +7 -0
  8. package/dist/model/datasource.d.ts.map +1 -0
  9. package/dist/model/datasource.js +19 -0
  10. package/dist/model/parse-sample-values.d.ts +16 -0
  11. package/dist/model/parse-sample-values.d.ts.map +1 -0
  12. package/dist/model/parse-sample-values.js +39 -0
  13. package/dist/model/prometheus-client.d.ts +22 -0
  14. package/dist/model/prometheus-client.d.ts.map +1 -0
  15. package/dist/model/prometheus-client.js +97 -0
  16. package/dist/model/templating.d.ts +25 -0
  17. package/dist/model/templating.d.ts.map +1 -0
  18. package/dist/model/templating.js +116 -0
  19. package/dist/model/time.d.ts +25 -0
  20. package/dist/model/time.d.ts.map +1 -0
  21. package/dist/model/time.js +68 -0
  22. package/dist/plugins/graph-query.d.ts +12 -0
  23. package/dist/plugins/graph-query.d.ts.map +1 -0
  24. package/dist/plugins/graph-query.js +77 -0
  25. package/dist/plugins/interval-variable.d.ts +17 -0
  26. package/dist/plugins/interval-variable.d.ts.map +1 -0
  27. package/dist/plugins/interval-variable.js +22 -0
  28. package/dist/plugins/label-names-variable.d.ts +13 -0
  29. package/dist/plugins/label-names-variable.d.ts.map +1 -0
  30. package/dist/plugins/label-names-variable.js +42 -0
  31. package/dist/plugins/label-values-variable.d.ts +14 -0
  32. package/dist/plugins/label-values-variable.d.ts.map +1 -0
  33. package/dist/plugins/label-values-variable.js +42 -0
  34. package/package.json +41 -0
@@ -0,0 +1,3 @@
1
+ import { PluginSetupFunction } from '@perses-dev/core';
2
+ export declare const setup: PluginSetupFunction;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAMvD,eAAO,MAAM,KAAK,EAAE,mBAiCnB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,50 @@
1
+ // Copyright 2021 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 { PrometheusGraphQueryKind, usePrometheusGraphQuery } from './plugins/graph-query';
14
+ import { IntervalKind, useIntervalValues } from './plugins/interval-variable';
15
+ import { PrometheusLabelNamesKind, usePrometheusLabelNames } from './plugins/label-names-variable';
16
+ import { PrometheusLabelValuesKind, usePrometheusLabelValues } from './plugins/label-values-variable';
17
+ export const setup = (registerPlugin) => {
18
+ registerPlugin({
19
+ pluginType: 'Variable',
20
+ kind: PrometheusLabelNamesKind,
21
+ validate: undefined,
22
+ plugin: {
23
+ useVariableOptions: usePrometheusLabelNames,
24
+ },
25
+ });
26
+ registerPlugin({
27
+ pluginType: 'Variable',
28
+ kind: PrometheusLabelValuesKind,
29
+ validate: undefined,
30
+ plugin: {
31
+ useVariableOptions: usePrometheusLabelValues,
32
+ },
33
+ });
34
+ registerPlugin({
35
+ pluginType: 'Variable',
36
+ kind: IntervalKind,
37
+ validate: undefined,
38
+ plugin: {
39
+ useVariableOptions: useIntervalValues,
40
+ },
41
+ });
42
+ registerPlugin({
43
+ pluginType: 'GraphQuery',
44
+ kind: PrometheusGraphQueryKind,
45
+ validate: undefined,
46
+ plugin: {
47
+ useGraphQuery: usePrometheusGraphQuery,
48
+ },
49
+ });
50
+ };
@@ -0,0 +1,80 @@
1
+ import { DurationString } from '@perses-dev/core';
2
+ export type { DurationString };
3
+ export interface SuccessResponse<T> {
4
+ status: 'success';
5
+ data: T;
6
+ warnings?: string[];
7
+ }
8
+ export interface ErrorResponse<T> {
9
+ status: 'error';
10
+ data?: T;
11
+ errorType: string;
12
+ error: string;
13
+ }
14
+ export declare type ApiResponse<T> = SuccessResponse<T> | ErrorResponse<T>;
15
+ export declare type DurationSeconds = number;
16
+ export declare type UnixTimestampSeconds = number;
17
+ export declare type ValueTuple = [unixTimeSeconds: UnixTimestampSeconds, sampleValue: string];
18
+ export declare type Metric = Record<string, string>;
19
+ export interface VectorData {
20
+ resultType: 'vector';
21
+ result: Array<{
22
+ metric: Metric;
23
+ value: ValueTuple;
24
+ }>;
25
+ }
26
+ export interface MatrixData {
27
+ resultType: 'matrix';
28
+ result: Array<{
29
+ metric: Metric;
30
+ values: ValueTuple[];
31
+ }>;
32
+ }
33
+ export interface ScalarData {
34
+ resultType: 'scalar';
35
+ result: ValueTuple;
36
+ }
37
+ export interface InstantQueryRequestParameters {
38
+ query: string;
39
+ time?: UnixTimestampSeconds;
40
+ timeout?: DurationString;
41
+ }
42
+ export declare type InstantQueryResponse = ApiResponse<MatrixData | VectorData | ScalarData>;
43
+ export interface RangeQueryRequestParameters {
44
+ query: string;
45
+ start: UnixTimestampSeconds;
46
+ end: UnixTimestampSeconds;
47
+ step: DurationSeconds;
48
+ timeout?: DurationString;
49
+ }
50
+ export declare type RangeQueryResponse = ApiResponse<MatrixData>;
51
+ export interface SeriesRequestParameters {
52
+ match: string[];
53
+ start: UnixTimestampSeconds;
54
+ end: UnixTimestampSeconds;
55
+ }
56
+ export declare type SeriesResponse = ApiResponse<Metric[]>;
57
+ export interface LabelNamesRequestParameters {
58
+ start?: UnixTimestampSeconds;
59
+ end?: UnixTimestampSeconds;
60
+ match?: string[];
61
+ }
62
+ export declare type LabelNamesResponse = ApiResponse<string[]>;
63
+ export interface LabelValuesRequestParameters {
64
+ labelName: string;
65
+ start?: UnixTimestampSeconds;
66
+ end?: UnixTimestampSeconds;
67
+ match?: string[];
68
+ }
69
+ export declare type LabelValuesResponse = ApiResponse<string[]>;
70
+ export interface MetricMetadata {
71
+ type: string;
72
+ help: string;
73
+ unit?: string;
74
+ }
75
+ export interface MetricMetadataRequestParameters {
76
+ limit?: number;
77
+ metric?: string;
78
+ }
79
+ export declare type MetricMetadataResponse = ApiResponse<Record<string, MetricMetadata[]>>;
80
+ //# sourceMappingURL=api-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-types.d.ts","sourceRoot":"","sources":["../../src/model/api-types.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,13 @@
1
+ // Copyright 2021 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
+ export {};
@@ -0,0 +1,7 @@
1
+ import { DatasourceSelector, DatasourceSpecDefinition, HTTPConfig } from '@perses-dev/core';
2
+ export interface PrometheusSpecDatasource extends DatasourceSpecDefinition {
3
+ kind: 'Prometheus';
4
+ http: HTTPConfig;
5
+ }
6
+ export declare function usePrometheusConfig(selector: DatasourceSelector): PrometheusSpecDatasource;
7
+ //# sourceMappingURL=datasource.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"datasource.d.ts","sourceRoot":"","sources":["../../src/model/datasource.ts"],"names":[],"mappings":"AAaA,OAAO,EAEL,kBAAkB,EAClB,wBAAwB,EACxB,UAAU,EAEX,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,wBAAyB,SAAQ,wBAAwB;IACxE,IAAI,EAAE,YAAY,CAAC;IACnB,IAAI,EAAE,UAAU,CAAC;CAClB;AAMD,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,kBAAkB,4BAE/D"}
@@ -0,0 +1,19 @@
1
+ // Copyright 2021 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 { useDataSourceConfig, } from '@perses-dev/core';
14
+ function isPrometheusDatasource(def) {
15
+ return def.kind === 'Prometheus';
16
+ }
17
+ export function usePrometheusConfig(selector) {
18
+ return useDataSourceConfig(selector, isPrometheusDatasource);
19
+ }
@@ -0,0 +1,16 @@
1
+ import { ValueTuple } from './api-types';
2
+ /**
3
+ * ValueTuple from the Prom server, parsed into ms and floating point number
4
+ */
5
+ export declare type ParsedValueTuple = [unixTimeMs: number, value: number];
6
+ /**
7
+ * Parse a ValueTuple from a PromServer response into the a millisecond-based
8
+ * unix time and a numeric sample value.
9
+ */
10
+ export declare function parseValueTuple(data: ValueTuple): ParsedValueTuple;
11
+ /**
12
+ * Parses a string sample value from Prometheus, usually included as the
13
+ * second member of a ValueTuple.
14
+ */
15
+ export declare function parseSampleValue(sampleValue: ValueTuple[1]): number;
16
+ //# sourceMappingURL=parse-sample-values.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse-sample-values.d.ts","sourceRoot":"","sources":["../../src/model/parse-sample-values.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC;;GAEG;AACH,oBAAY,gBAAgB,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAEnE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,UAAU,GAAG,gBAAgB,CAKlE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,MAAM,CAanE"}
@@ -0,0 +1,39 @@
1
+ // Copyright 2021 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
+ /**
14
+ * Parse a ValueTuple from a PromServer response into the a millisecond-based
15
+ * unix time and a numeric sample value.
16
+ */
17
+ export function parseValueTuple(data) {
18
+ const [unixTimeSeconds, sampleValue] = data;
19
+ // Prom returns unix time in seconds, so convert to ms
20
+ return [unixTimeSeconds * 1000, parseSampleValue(sampleValue)];
21
+ }
22
+ /**
23
+ * Parses a string sample value from Prometheus, usually included as the
24
+ * second member of a ValueTuple.
25
+ */
26
+ export function parseSampleValue(sampleValue) {
27
+ // Account for Prometheus' representation of +/- infinity, otherwise just
28
+ // parse the sample value as a float
29
+ let value;
30
+ switch (sampleValue) {
31
+ case '+Inf':
32
+ value = Number.POSITIVE_INFINITY;
33
+ case '-Inf':
34
+ value = Number.NEGATIVE_INFINITY;
35
+ default:
36
+ value = parseFloat(sampleValue);
37
+ }
38
+ return value;
39
+ }
@@ -0,0 +1,22 @@
1
+ import { UseQueryOptions } from 'react-query';
2
+ import { DatasourceSelector } from '@perses-dev/core';
3
+ import { InstantQueryRequestParameters, InstantQueryResponse, LabelNamesRequestParameters, LabelNamesResponse, LabelValuesRequestParameters, LabelValuesResponse, RangeQueryRequestParameters, RangeQueryResponse } from './api-types';
4
+ export declare type QueryOptions = Pick<UseQueryOptions, 'enabled'>;
5
+ /**
6
+ * Calls the `/api/v1/query` endpoint to get metrics data.
7
+ */
8
+ export declare function useInstantQuery(datasource: DatasourceSelector, params: InstantQueryRequestParameters, queryOptions?: QueryOptions): import("react-query").UseQueryResult<InstantQueryResponse, Error>;
9
+ /**
10
+ * Calls the `/api/v1/query_range` endpoint to get metrics data.
11
+ */
12
+ export declare function useRangeQuery(datasource: DatasourceSelector, params: RangeQueryRequestParameters, queryOptions?: QueryOptions): import("react-query").UseQueryResult<RangeQueryResponse, Error>;
13
+ /**
14
+ * Calls the `/api/v1/labels` endpoint to get a list of label names.
15
+ */
16
+ export declare function useLabelNames(datasource: DatasourceSelector, params: LabelNamesRequestParameters, queryOptions?: QueryOptions): import("react-query").UseQueryResult<LabelNamesResponse, Error>;
17
+ /**
18
+ * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of
19
+ * values for a label.
20
+ */
21
+ export declare function useLabelValues(datasource: DatasourceSelector, params: LabelValuesRequestParameters, queryOptions?: QueryOptions): import("react-query").UseQueryResult<LabelValuesResponse, Error>;
22
+ //# sourceMappingURL=prometheus-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prometheus-client.d.ts","sourceRoot":"","sources":["../../src/model/prometheus-client.ts"],"names":[],"mappings":"AAaA,OAAO,EAAY,eAAe,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAsB,kBAAkB,EAAa,MAAM,kBAAkB,CAAC;AACrF,OAAO,EACL,6BAA6B,EAC7B,oBAAoB,EACpB,2BAA2B,EAC3B,kBAAkB,EAClB,4BAA4B,EAC5B,mBAAmB,EACnB,2BAA2B,EAC3B,kBAAkB,EACnB,MAAM,aAAa,CAAC;AAGrB,oBAAY,YAAY,GAAG,IAAI,CAAC,eAAe,EAAE,SAAS,CAAC,CAAC;AAE5D;;GAEG;AACH,wBAAgB,eAAe,CAC7B,UAAU,EAAE,kBAAkB,EAC9B,MAAM,EAAE,6BAA6B,EACrC,YAAY,CAAC,EAAE,YAAY,qEAS5B;AAED;;GAEG;AACH,wBAAgB,aAAa,CAC3B,UAAU,EAAE,kBAAkB,EAC9B,MAAM,EAAE,2BAA2B,EACnC,YAAY,CAAC,EAAE,YAAY,mEAS5B;AAED;;GAEG;AACH,wBAAgB,aAAa,CAC3B,UAAU,EAAE,kBAAkB,EAC9B,MAAM,EAAE,2BAA2B,EACnC,YAAY,CAAC,EAAE,YAAY,mEAS5B;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,UAAU,EAAE,kBAAkB,EAC9B,MAAM,EAAE,4BAA4B,EACpC,YAAY,CAAC,EAAE,YAAY,oEAW5B"}
@@ -0,0 +1,97 @@
1
+ // Copyright 2021 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 { useQuery } from 'react-query';
14
+ import { buildDatasourceURL, fetchJson } from '@perses-dev/core';
15
+ import { usePrometheusConfig } from './datasource';
16
+ /**
17
+ * Calls the `/api/v1/query` endpoint to get metrics data.
18
+ */
19
+ export function useInstantQuery(datasource, params, queryOptions) {
20
+ return useQueryWithPost(datasource, '/api/v1/query', params, undefined, queryOptions);
21
+ }
22
+ /**
23
+ * Calls the `/api/v1/query_range` endpoint to get metrics data.
24
+ */
25
+ export function useRangeQuery(datasource, params, queryOptions) {
26
+ return useQueryWithPost(datasource, '/api/v1/query_range', params, undefined, queryOptions);
27
+ }
28
+ /**
29
+ * Calls the `/api/v1/labels` endpoint to get a list of label names.
30
+ */
31
+ export function useLabelNames(datasource, params, queryOptions) {
32
+ return useQueryWithPost(datasource, '/api/v1/labels', params, { match: 'match[]' }, queryOptions);
33
+ }
34
+ /**
35
+ * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of
36
+ * values for a label.
37
+ */
38
+ export function useLabelValues(datasource, params, queryOptions) {
39
+ const { labelName, ...searchParams } = params;
40
+ const apiURI = `/api/v1/label/${encodeURIComponent(labelName)}/values`;
41
+ return useQueryWithGet(datasource, apiURI, searchParams, { match: 'match[]' }, queryOptions);
42
+ }
43
+ function useQueryWithGet(datasourceSelector, apiURI, params, rename, queryOptions) {
44
+ const httpConfig = usePrometheusConfig(datasourceSelector).http;
45
+ const datasourceURL = buildDatasourceURL(datasourceSelector.name, httpConfig);
46
+ const key = [datasourceURL, apiURI, params];
47
+ return useQuery(key, () => {
48
+ let url = `${datasourceURL}${apiURI}`;
49
+ const urlParams = createSearchParams(params, rename).toString();
50
+ if (urlParams !== '') {
51
+ url += `?${urlParams}`;
52
+ }
53
+ return fetchJson(url, { method: 'GET' });
54
+ }, queryOptions);
55
+ }
56
+ function useQueryWithPost(datasourceSelector, apiURI, params, rename, queryOptions) {
57
+ const httpConfig = usePrometheusConfig(datasourceSelector).http;
58
+ const datasourceURL = buildDatasourceURL(datasourceSelector.name, httpConfig);
59
+ const key = [datasourceURL, apiURI, params];
60
+ return useQuery(key, () => {
61
+ const url = `${datasourceURL}${apiURI}`;
62
+ const init = {
63
+ method: 'POST',
64
+ headers: {
65
+ 'Content-Type': 'application/x-www-form-urlencoded',
66
+ },
67
+ body: createSearchParams(params, rename),
68
+ };
69
+ return fetchJson(url, init);
70
+ }, queryOptions);
71
+ }
72
+ /**
73
+ * Creates URLSearchParams from a request params object.
74
+ */
75
+ function createSearchParams(params, rename) {
76
+ const searchParams = new URLSearchParams();
77
+ for (const key in params) {
78
+ const value = params[key];
79
+ if (value === undefined)
80
+ continue;
81
+ // Allow keys to be renamed when mapping to parameters
82
+ const renamed = rename === null || rename === void 0 ? void 0 : rename[key];
83
+ const name = renamed !== undefined ? renamed : key;
84
+ if (typeof value === 'string') {
85
+ searchParams.append(name, value);
86
+ continue;
87
+ }
88
+ if (typeof value === 'number') {
89
+ searchParams.append(name, value.toString());
90
+ continue;
91
+ }
92
+ for (const val of value) {
93
+ searchParams.append(name, val);
94
+ }
95
+ }
96
+ return searchParams;
97
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Type alias to indicate what parts of the API support template variables.
3
+ */
4
+ export declare type TemplateString = string;
5
+ /**
6
+ * Replaces template variable placeholders with variable values from the current
7
+ * dashbboard in multiple template strings. Since template strings are often
8
+ * used as request parameters, the results are memoized and only recalculated
9
+ * if the templateStrings or variable values change.
10
+ */
11
+ export declare function useReplaceTemplateStrings(templateStrings?: TemplateString[]): {
12
+ result: string[];
13
+ needsVariableValuesFor: Set<string>;
14
+ };
15
+ /**
16
+ * Replaces template variable placeholders with variable values from the current
17
+ * dashboard in a single template string. Since template strings are often
18
+ * used as request parameters, the results are memoized and only recalculated
19
+ * if the templateString or variable values change.
20
+ */
21
+ export declare function useReplaceTemplateString(templateString?: TemplateString): {
22
+ result: string;
23
+ needsVariableValuesFor: Set<string>;
24
+ };
25
+ //# sourceMappingURL=templating.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templating.d.ts","sourceRoot":"","sources":["../../src/model/templating.ts"],"names":[],"mappings":"AAkBA;;GAEG;AACH,oBAAY,cAAc,GAAG,MAAM,CAAC;AAEpC;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,eAAe,CAAC,EAAE,cAAc,EAAE;;;EAkB3E;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,cAAc,CAAC,EAAE,cAAc;;;EAWvE"}
@@ -0,0 +1,116 @@
1
+ // Copyright 2021 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 { Duration, parser, StringLiteral } from 'lezer-promql';
14
+ import { DEFAULT_ALL_VALUE, useMemoized, useDashboardVariables } from '@perses-dev/core';
15
+ const REPLACE_IN_NODE_TYPES = new Set([StringLiteral, Duration]);
16
+ /**
17
+ * Replaces template variable placeholders with variable values from the current
18
+ * dashbboard in multiple template strings. Since template strings are often
19
+ * used as request parameters, the results are memoized and only recalculated
20
+ * if the templateStrings or variable values change.
21
+ */
22
+ export function useReplaceTemplateStrings(templateStrings) {
23
+ const variablesState = useDashboardVariables();
24
+ // Replace template string placeholders with variable values
25
+ return useMemoized(() => {
26
+ const result = [];
27
+ const needsVariableValuesFor = new Set();
28
+ for (const templateString of templateStrings !== null && templateStrings !== void 0 ? templateStrings : []) {
29
+ const replaced = replaceTemplateVariables(templateString, variablesState);
30
+ result.push(replaced.result);
31
+ for (const varName of replaced.needsVariableValuesFor) {
32
+ needsVariableValuesFor.add(varName);
33
+ }
34
+ }
35
+ return { result, needsVariableValuesFor };
36
+ }, [templateStrings, variablesState]);
37
+ }
38
+ /**
39
+ * Replaces template variable placeholders with variable values from the current
40
+ * dashboard in a single template string. Since template strings are often
41
+ * used as request parameters, the results are memoized and only recalculated
42
+ * if the templateString or variable values change.
43
+ */
44
+ export function useReplaceTemplateString(templateString) {
45
+ const variablesState = useDashboardVariables();
46
+ // Replace template string placeholders with variable values
47
+ return useMemoized(() => {
48
+ if (templateString === undefined) {
49
+ return { result: '', needsVariableValuesFor: new Set() };
50
+ }
51
+ return replaceTemplateVariables(templateString, variablesState);
52
+ }, [templateString, variablesState]);
53
+ }
54
+ /**
55
+ * Replace template variable placeholders with variable values.
56
+ */
57
+ function replaceTemplateVariables(templateString, variablesState) {
58
+ const needsVariableValuesFor = new Set();
59
+ let indexAdjustment = 0;
60
+ const tree = parser.parse(templateString);
61
+ const cursor = tree.cursor();
62
+ do {
63
+ // Only replace variables in string literals for now
64
+ if (REPLACE_IN_NODE_TYPES.has(cursor.node.type.id))
65
+ continue;
66
+ let { from, to } = cursor.node;
67
+ from += indexAdjustment;
68
+ to += indexAdjustment;
69
+ let nodeText = templateString.substring(from, to);
70
+ nodeText = nodeText.replaceAll(/\$([a-zA-Z0-9_-]+)/g, (match, variableName) => {
71
+ const state = variablesState[variableName];
72
+ if (state === undefined) {
73
+ throw new Error(`Unknown variable '${variableName}'`);
74
+ }
75
+ const { value, options } = state;
76
+ let replacement;
77
+ if (Array.isArray(value)) {
78
+ let selectedValues = value;
79
+ // Is the default ALL value?
80
+ if (value.length === 1 && value[0] === DEFAULT_ALL_VALUE) {
81
+ // For the default ALL value, we want to use all options as the
82
+ // selected values
83
+ if (options === undefined) {
84
+ // Wait until options are loaded before we do replacement
85
+ needsVariableValuesFor.add(variableName);
86
+ return match;
87
+ }
88
+ selectedValues = options;
89
+ }
90
+ // TODO: Escape v for regex
91
+ replacement = selectedValues.map((v) => v).join('|');
92
+ }
93
+ else {
94
+ replacement = escapeVariableValue(value);
95
+ }
96
+ return replacement;
97
+ });
98
+ // Replace the string literal with the new one and since that may change the
99
+ // overall length of the string, keep track of an "index adjustment" so we
100
+ // can shift positions in the tree accordingly
101
+ const oldLength = to - from;
102
+ indexAdjustment += nodeText.length - oldLength;
103
+ templateString = templateString.substring(0, from) + nodeText + templateString.substring(from + oldLength);
104
+ } while (cursor.next());
105
+ return {
106
+ result: templateString,
107
+ needsVariableValuesFor,
108
+ };
109
+ }
110
+ const SINGLE_BACKSLASH = '\\';
111
+ const DOUBLE_BACKSLASH = '\\\\';
112
+ function escapeVariableValue(value) {
113
+ // TODO: What about ["'`]? Do we need to know what kind of quotes the
114
+ // string literal is using?
115
+ return value.replaceAll(SINGLE_BACKSLASH, DOUBLE_BACKSLASH);
116
+ }
@@ -0,0 +1,25 @@
1
+ import { DurationString } from '@perses-dev/core';
2
+ import { UnixTimestampSeconds } from './api-types';
3
+ export interface PrometheusTimeRange {
4
+ start: UnixTimestampSeconds;
5
+ end: UnixTimestampSeconds;
6
+ }
7
+ /**
8
+ * Get the time range for the current dashboard, converted to Prometheus time.
9
+ */
10
+ export declare function useDashboardPrometheusTimeRange(): {
11
+ start: number;
12
+ end: number;
13
+ };
14
+ /**
15
+ * Gets the step to use for a Panel range query. Tries to take into account
16
+ * the width of the panel, any minimum step/resolution set by the user, and
17
+ * a "safe" step based on the max data points we want to allow returning from
18
+ * a Prom query.
19
+ */
20
+ export declare function usePanelRangeStep(timeRange: PrometheusTimeRange, minStepSeconds?: number, resolution?: number): number;
21
+ /**
22
+ * Converts a DurationString to seconds, rounding down.
23
+ */
24
+ export declare function getDurationStringSeconds(durationString?: DurationString): number | undefined;
25
+ //# sourceMappingURL=time.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../../src/model/time.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,cAAc,EAKf,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,oBAAoB,CAAC;IAC5B,GAAG,EAAE,oBAAoB,CAAC;CAC3B;AAED;;GAEG;AACH,wBAAgB,+BAA+B;;;EAU9C;AAMD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,mBAAmB,EAAE,cAAc,SAAK,EAAE,UAAU,SAAI,UAwBpG;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,cAAc,CAAC,EAAE,cAAc,sBAMvE"}
@@ -0,0 +1,68 @@
1
+ // Copyright 2021 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 { parseDurationString, useMemoized, usePanelState, useDashboardTimeRange, } from '@perses-dev/core';
14
+ import { milliseconds, getUnixTime } from 'date-fns';
15
+ import { useRef } from 'react';
16
+ /**
17
+ * Get the time range for the current dashboard, converted to Prometheus time.
18
+ */
19
+ export function useDashboardPrometheusTimeRange() {
20
+ const { start, end } = useDashboardTimeRange();
21
+ // Only recalculate the time range if the value on the dashboard changes
22
+ return useMemoized(() => {
23
+ return {
24
+ start: Math.ceil(getUnixTime(start)),
25
+ end: Math.ceil(getUnixTime(end)),
26
+ };
27
+ }, [start, end]);
28
+ }
29
+ // Max data points to allow returning from a Prom Query, used to calculate a
30
+ // "safe" step for a range query
31
+ const MAX_PROM_DATA_POINTS = 10000;
32
+ /**
33
+ * Gets the step to use for a Panel range query. Tries to take into account
34
+ * the width of the panel, any minimum step/resolution set by the user, and
35
+ * a "safe" step based on the max data points we want to allow returning from
36
+ * a Prom query.
37
+ */
38
+ export function usePanelRangeStep(timeRange, minStepSeconds = 15, resolution = 1) {
39
+ // Keep track of the latest panel width in a ref
40
+ const { contentDimensions } = usePanelState();
41
+ const panelWidth = useRef(contentDimensions === null || contentDimensions === void 0 ? void 0 : contentDimensions.width);
42
+ panelWidth.current = contentDimensions === null || contentDimensions === void 0 ? void 0 : contentDimensions.width;
43
+ // Whenever the time range changes, recalculate the appropriate step
44
+ return useMemoized(() => {
45
+ const queryRangeSeconds = timeRange.end - timeRange.start;
46
+ // TODO: Should we try to suggest more "rounded" step values based around
47
+ // time increments that make sense (e.g. 15s, 30s, 1m, 5m, etc.)
48
+ let suggestedStep = 0;
49
+ if (panelWidth.current !== undefined) {
50
+ suggestedStep = Math.floor(queryRangeSeconds / panelWidth.current);
51
+ }
52
+ let safeStep = queryRangeSeconds / MAX_PROM_DATA_POINTS;
53
+ if (safeStep > 1) {
54
+ safeStep = Math.ceil(safeStep);
55
+ }
56
+ return Math.max(suggestedStep * resolution, minStepSeconds, safeStep);
57
+ }, [timeRange, minStepSeconds, resolution]);
58
+ }
59
+ /**
60
+ * Converts a DurationString to seconds, rounding down.
61
+ */
62
+ export function getDurationStringSeconds(durationString) {
63
+ if (durationString === undefined)
64
+ return undefined;
65
+ const duration = parseDurationString(durationString);
66
+ const ms = milliseconds(duration);
67
+ return Math.floor(ms / 1000);
68
+ }
@@ -0,0 +1,12 @@
1
+ import { DurationString, GraphQueryDefinition, JsonObject, UseGraphQueryHook } from '@perses-dev/core';
2
+ import { TemplateString } from '../model/templating';
3
+ export declare const PrometheusGraphQueryKind: "PrometheusGraphQuery";
4
+ declare type PrometheusGraphQuery = GraphQueryDefinition<GraphQueryOptions>;
5
+ interface GraphQueryOptions extends JsonObject {
6
+ query: TemplateString;
7
+ min_step?: DurationString;
8
+ resolution?: number;
9
+ }
10
+ export declare function usePrometheusGraphQuery(definition: PrometheusGraphQuery): ReturnType<UseGraphQueryHook<GraphQueryOptions>>;
11
+ export {};
12
+ //# sourceMappingURL=graph-query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-query.d.ts","sourceRoot":"","sources":["../../src/plugins/graph-query.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,cAAc,EAEd,oBAAoB,EACpB,UAAU,EAEV,iBAAiB,EAElB,MAAM,kBAAkB,CAAC;AAM1B,OAAO,EAAE,cAAc,EAA4B,MAAM,qBAAqB,CAAC;AAG/E,eAAO,MAAM,wBAAwB,wBAAkC,CAAC;AAExE,aAAK,oBAAoB,GAAG,oBAAoB,CAAC,iBAAiB,CAAC,CAAC;AAEpE,UAAU,iBAAkB,SAAQ,UAAU;IAC5C,KAAK,EAAE,cAAc,CAAC;IACtB,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,wBAAgB,uBAAuB,CACrC,UAAU,EAAE,oBAAoB,GAC/B,UAAU,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,CAAC,CAsElD"}
@@ -0,0 +1,77 @@
1
+ // Copyright 2021 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 { useDashboardSpec, useMemoized, } from '@perses-dev/core';
14
+ import { fromUnixTime } from 'date-fns';
15
+ import { useMemo } from 'react';
16
+ import { parseValueTuple } from '../model/parse-sample-values';
17
+ import { useRangeQuery } from '../model/prometheus-client';
18
+ import { useReplaceTemplateString } from '../model/templating';
19
+ import { getDurationStringSeconds, useDashboardPrometheusTimeRange, usePanelRangeStep } from '../model/time';
20
+ export const PrometheusGraphQueryKind = 'PrometheusGraphQuery';
21
+ export function usePrometheusGraphQuery(definition) {
22
+ const spec = useDashboardSpec();
23
+ const minStep = getDurationStringSeconds(definition.options.min_step);
24
+ const timeRange = useDashboardPrometheusTimeRange();
25
+ const step = usePanelRangeStep(timeRange, minStep);
26
+ // Align the time range so that it's a multiple of the step (TODO: we may
27
+ // ultimately want to return this from the hook so that charts will know what
28
+ // time range was actually used?)
29
+ const { start, end } = useMemoized(() => {
30
+ const { start, end } = timeRange;
31
+ const utcOffsetSec = new Date().getTimezoneOffset() * 60;
32
+ const alignedEnd = Math.floor((end + utcOffsetSec) / step) * step - utcOffsetSec;
33
+ const alignedStart = Math.floor((start + utcOffsetSec) / step) * step - utcOffsetSec;
34
+ return {
35
+ start: alignedStart,
36
+ end: alignedEnd,
37
+ };
38
+ }, [timeRange, step]);
39
+ const { result: query, needsVariableValuesFor } = useReplaceTemplateString(definition.options.query);
40
+ const request = {
41
+ query,
42
+ start,
43
+ end,
44
+ step,
45
+ };
46
+ const { data: response, isLoading: loading, error, } = useRangeQuery(spec.datasource, request, {
47
+ enabled: needsVariableValuesFor.size === 0,
48
+ });
49
+ const data = useMemo(() => {
50
+ if (response === undefined)
51
+ return undefined;
52
+ if (response.status === 'error')
53
+ return undefined;
54
+ // TODO: Maybe do a proper Iterable implementation that defers some of this
55
+ // processing until its needed
56
+ const chartData = {
57
+ timeRange: { start: fromUnixTime(start), end: fromUnixTime(end) },
58
+ stepMs: step * 1000,
59
+ series: response.data.result.map((value) => {
60
+ const { metric, values } = value;
61
+ // Name the series after the metric labels or if no metric, just use the
62
+ // overall query
63
+ let name = Object.entries(metric)
64
+ .map(([labelName, labelValue]) => `${labelName}="${labelValue}"`)
65
+ .join(', ');
66
+ if (name === '')
67
+ name = query;
68
+ return {
69
+ name,
70
+ values: values.map(parseValueTuple),
71
+ };
72
+ }),
73
+ };
74
+ return chartData;
75
+ }, [response, start, end, step, query]);
76
+ return { data, loading, error: error !== null && error !== void 0 ? error : undefined };
77
+ }
@@ -0,0 +1,17 @@
1
+ import { JsonObject, DurationString, UseVariableOptionsHook, VariableDefinition } from '@perses-dev/core';
2
+ export declare const IntervalKind: "Inverval";
3
+ declare type IntervalVariable = VariableDefinition<IntervalOptions>;
4
+ interface IntervalOptions extends JsonObject {
5
+ values: DurationString[];
6
+ auto?: {
7
+ step_count: number;
8
+ min_interval: DurationString;
9
+ };
10
+ }
11
+ /**
12
+ * Variable plugin for getting a list of variable options from a predefined
13
+ * list of duration values.
14
+ */
15
+ export declare function useIntervalValues(definition: IntervalVariable): ReturnType<UseVariableOptionsHook<IntervalOptions>>;
16
+ export {};
17
+ //# sourceMappingURL=interval-variable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interval-variable.d.ts","sourceRoot":"","sources":["../../src/plugins/interval-variable.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE1G,eAAO,MAAM,YAAY,YAAsB,CAAC;AAEhD,aAAK,gBAAgB,GAAG,kBAAkB,CAAC,eAAe,CAAC,CAAC;AAE5D,UAAU,eAAgB,SAAQ,UAAU;IAC1C,MAAM,EAAE,cAAc,EAAE,CAAC;IACzB,IAAI,CAAC,EAAE;QACL,UAAU,EAAE,MAAM,CAAC;QACnB,YAAY,EAAE,cAAc,CAAC;KAC9B,CAAC;CACH;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,gBAAgB,GAAG,UAAU,CAAC,sBAAsB,CAAC,eAAe,CAAC,CAAC,CAMnH"}
@@ -0,0 +1,22 @@
1
+ // Copyright 2021 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
+ export const IntervalKind = 'Inverval';
14
+ /**
15
+ * Variable plugin for getting a list of variable options from a predefined
16
+ * list of duration values.
17
+ */
18
+ export function useIntervalValues(definition) {
19
+ // TODO: What about auto?
20
+ const { options: { values }, } = definition;
21
+ return { loading: false, error: undefined, data: values };
22
+ }
@@ -0,0 +1,13 @@
1
+ import { JsonObject, UseVariableOptionsHook, VariableDefinition } from '@perses-dev/core';
2
+ import { TemplateString } from '../model/templating';
3
+ export declare const PrometheusLabelNamesKind: "PrometheusLabelNames";
4
+ declare type PrometheusLabelNames = VariableDefinition<LabelNamesOptions>;
5
+ interface LabelNamesOptions extends JsonObject {
6
+ match: TemplateString[];
7
+ }
8
+ /**
9
+ * Get variable option values by running a Prometheus label names query.
10
+ */
11
+ export declare function usePrometheusLabelNames(definition: PrometheusLabelNames): ReturnType<UseVariableOptionsHook<LabelNamesOptions>>;
12
+ export {};
13
+ //# sourceMappingURL=label-names-variable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"label-names-variable.d.ts","sourceRoot":"","sources":["../../src/plugins/label-names-variable.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,UAAU,EAAoB,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC5G,OAAO,EAAE,cAAc,EAA6B,MAAM,qBAAqB,CAAC;AAKhF,eAAO,MAAM,wBAAwB,wBAAkC,CAAC;AAExE,aAAK,oBAAoB,GAAG,kBAAkB,CAAC,iBAAiB,CAAC,CAAC;AAElE,UAAU,iBAAkB,SAAQ,UAAU;IAC5C,KAAK,EAAE,cAAc,EAAE,CAAC;CACzB;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,UAAU,EAAE,oBAAoB,GAC/B,UAAU,CAAC,sBAAsB,CAAC,iBAAiB,CAAC,CAAC,CA2BvD"}
@@ -0,0 +1,42 @@
1
+ // Copyright 2021 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 { useDashboardSpec } from '@perses-dev/core';
14
+ import { useReplaceTemplateStrings } from '../model/templating';
15
+ import { useDashboardPrometheusTimeRange } from '../model/time';
16
+ import { useLabelNames } from '../model/prometheus-client';
17
+ export const PrometheusLabelNamesKind = 'PrometheusLabelNames';
18
+ /**
19
+ * Get variable option values by running a Prometheus label names query.
20
+ */
21
+ export function usePrometheusLabelNames(definition) {
22
+ var _a;
23
+ const spec = useDashboardSpec();
24
+ const { start, end } = useDashboardPrometheusTimeRange();
25
+ const { result: match, needsVariableValuesFor } = useReplaceTemplateStrings(definition.options.match);
26
+ // Make the request, pausing any requests that are still waiting on variable
27
+ // values to be filled in/selected
28
+ const request = {
29
+ match,
30
+ start,
31
+ end,
32
+ };
33
+ const { data: response, isLoading: loading, error, } = useLabelNames(spec.datasource, request, {
34
+ enabled: needsVariableValuesFor.size === 0,
35
+ });
36
+ const data = (_a = response === null || response === void 0 ? void 0 : response.data) !== null && _a !== void 0 ? _a : [];
37
+ return {
38
+ data: data,
39
+ loading: loading || needsVariableValuesFor.size > 0,
40
+ error: error !== null && error !== void 0 ? error : undefined,
41
+ };
42
+ }
@@ -0,0 +1,14 @@
1
+ import { JsonObject, UseVariableOptionsHook, VariableDefinition } from '@perses-dev/core';
2
+ import { TemplateString } from '../model/templating';
3
+ export declare const PrometheusLabelValuesKind: "PrometheusLabelValues";
4
+ declare type PrometheusLabelValues = VariableDefinition<LabelValuesOptions>;
5
+ interface LabelValuesOptions extends JsonObject {
6
+ label_name: string;
7
+ match?: TemplateString[];
8
+ }
9
+ /**
10
+ * Get variable option values by running a Prometheus label values query.
11
+ */
12
+ export declare function usePrometheusLabelValues(definition: PrometheusLabelValues): ReturnType<UseVariableOptionsHook<LabelValuesOptions>>;
13
+ export {};
14
+ //# sourceMappingURL=label-values-variable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"label-values-variable.d.ts","sourceRoot":"","sources":["../../src/plugins/label-values-variable.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,UAAU,EAGV,sBAAsB,EACtB,kBAAkB,EACnB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAE,cAAc,EAA6B,MAAM,qBAAqB,CAAC;AAGhF,eAAO,MAAM,yBAAyB,yBAAmC,CAAC;AAE1E,aAAK,qBAAqB,GAAG,kBAAkB,CAAC,kBAAkB,CAAC,CAAC;AAEpE,UAAU,kBAAmB,SAAQ,UAAU;IAC7C,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,cAAc,EAAE,CAAC;CAC1B;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,qBAAqB,GAChC,UAAU,CAAC,sBAAsB,CAAC,kBAAkB,CAAC,CAAC,CA4BxD"}
@@ -0,0 +1,42 @@
1
+ // Copyright 2021 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 { useDashboardSpec, useMemoized, } from '@perses-dev/core';
14
+ import { useDashboardPrometheusTimeRange } from '../model/time';
15
+ import { useReplaceTemplateStrings } from '../model/templating';
16
+ import { useLabelValues } from '../model/prometheus-client';
17
+ export const PrometheusLabelValuesKind = 'PrometheusLabelValues';
18
+ /**
19
+ * Get variable option values by running a Prometheus label values query.
20
+ */
21
+ export function usePrometheusLabelValues(definition) {
22
+ const spec = useDashboardSpec();
23
+ const { start, end } = useDashboardPrometheusTimeRange();
24
+ const { result: match, needsVariableValuesFor } = useReplaceTemplateStrings(definition.options.match);
25
+ // Make the request, pausing any requests that are still waiting on variable
26
+ // values to be filled in/selected
27
+ const request = {
28
+ labelName: definition.options.label_name,
29
+ match,
30
+ start,
31
+ end,
32
+ };
33
+ const { data: response, isLoading: loading, error, } = useLabelValues(spec.datasource, request, {
34
+ enabled: needsVariableValuesFor.size === 0,
35
+ });
36
+ const data = useMemoized(() => { var _a; return (_a = response === null || response === void 0 ? void 0 : response.data) !== null && _a !== void 0 ? _a : []; }, [response]);
37
+ return {
38
+ data: data,
39
+ loading: loading || needsVariableValuesFor.size > 0,
40
+ error: error !== null && error !== void 0 ? error : undefined,
41
+ };
42
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@perses-dev/prometheus-plugin",
3
+ "version": "0.1.0",
4
+ "description": "Prometheus plugin for Perses",
5
+ "module": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "clean": "rimraf dist/",
9
+ "build": "tsc",
10
+ "test": "echo 'no test to run' && exit 0",
11
+ "lint": "eslint src --ext .ts,.tsx",
12
+ "lint:fix": "eslint --fix src --ext .ts,.tsx"
13
+ },
14
+ "dependencies": {
15
+ "@perses-dev/core": "^0.1.0",
16
+ "date-fns": "^2.28.0",
17
+ "lezer": "^0.13.5",
18
+ "lezer-promql": "^0.20.0",
19
+ "react": "^17.0.2",
20
+ "react-query": "^3.34.8"
21
+ },
22
+ "perses": {
23
+ "kind": "Plugin",
24
+ "metadata": {
25
+ "name": "Prometheus"
26
+ },
27
+ "spec": {
28
+ "supported_kinds": {
29
+ "PrometheusLabelNames": "Variable",
30
+ "PrometheusLabelValues": "Variable",
31
+ "Interval": "Variable",
32
+ "PrometheusGraphQuery": "GraphQuery"
33
+ },
34
+ "plugin_module_path": "./dist/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist"
39
+ ],
40
+ "license": "Apache-2.0"
41
+ }