@perses-dev/prometheus-plugin 0.48.0 → 0.49.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/components/PromQLEditor.js +209 -0
- package/dist/cjs/components/TreeNode.js +147 -0
- package/dist/cjs/components/index.js +1 -1
- package/dist/cjs/components/parse.js +42 -0
- package/dist/cjs/components/promql/ast.js +143 -0
- package/dist/cjs/components/promql/format.js +432 -0
- package/dist/cjs/components/promql/utils.js +109 -0
- package/dist/cjs/model/prometheus-client.js +10 -2
- package/dist/cjs/plugins/PrometheusDatasourceEditor.js +4 -0
- package/dist/cjs/plugins/prometheus-datasource.js +4 -0
- package/dist/cjs/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.js +6 -5
- package/dist/cjs/plugins/prometheus-variables.js +4 -2
- package/dist/components/PromQLEditor.d.ts +9 -0
- package/dist/components/PromQLEditor.d.ts.map +1 -0
- package/dist/components/PromQLEditor.js +196 -0
- package/dist/components/PromQLEditor.js.map +1 -0
- package/dist/components/TreeNode.d.ts +10 -0
- package/dist/components/TreeNode.d.ts.map +1 -0
- package/dist/components/TreeNode.js +139 -0
- package/dist/components/TreeNode.js.map +1 -0
- package/dist/components/index.d.ts +1 -1
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/index.js +1 -1
- package/dist/components/index.js.map +1 -1
- package/dist/components/parse.d.ts +4 -0
- package/dist/components/parse.d.ts.map +1 -0
- package/dist/components/parse.js +34 -0
- package/dist/components/parse.js.map +1 -0
- package/dist/components/promql/ast.d.ts +161 -0
- package/dist/components/promql/ast.d.ts.map +1 -0
- package/dist/components/promql/ast.js +106 -0
- package/dist/components/promql/ast.js.map +1 -0
- package/dist/components/promql/format.d.ts +5 -0
- package/dist/components/promql/format.d.ts.map +1 -0
- package/dist/components/promql/format.js +411 -0
- package/dist/components/promql/format.js.map +1 -0
- package/dist/components/promql/utils.d.ts +5 -0
- package/dist/components/promql/utils.d.ts.map +1 -0
- package/dist/components/promql/utils.js +90 -0
- package/dist/components/promql/utils.js.map +1 -0
- package/dist/model/api-types.d.ts +5 -0
- package/dist/model/api-types.d.ts.map +1 -1
- package/dist/model/api-types.js.map +1 -1
- package/dist/model/prometheus-client.d.ts +6 -1
- package/dist/model/prometheus-client.d.ts.map +1 -1
- package/dist/model/prometheus-client.js +9 -2
- package/dist/model/prometheus-client.js.map +1 -1
- package/dist/plugins/PrometheusDatasourceEditor.d.ts.map +1 -1
- package/dist/plugins/PrometheusDatasourceEditor.js +4 -0
- package/dist/plugins/PrometheusDatasourceEditor.js.map +1 -1
- package/dist/plugins/prometheus-datasource.d.ts.map +1 -1
- package/dist/plugins/prometheus-datasource.js +5 -1
- package/dist/plugins/prometheus-datasource.js.map +1 -1
- package/dist/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.d.ts.map +1 -1
- package/dist/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.js +6 -5
- package/dist/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.js.map +1 -1
- package/dist/plugins/prometheus-variables.d.ts.map +1 -1
- package/dist/plugins/prometheus-variables.js +4 -2
- package/dist/plugins/prometheus-variables.js.map +1 -1
- package/package.json +4 -4
- package/dist/cjs/components/PromQL.js +0 -58
- package/dist/components/PromQL.d.ts +0 -7
- package/dist/components/PromQL.d.ts.map +0 -1
- package/dist/components/PromQL.js +0 -45
- package/dist/components/PromQL.js.map +0 -1
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Copyright 2024 The Perses Authors
|
|
2
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
3
|
+
// you may not use this file except in compliance with the License.
|
|
4
|
+
// You may obtain a copy of the License at
|
|
5
|
+
//
|
|
6
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
//
|
|
8
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
10
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
// See the License for the specific language governing permissions and
|
|
12
|
+
// limitations under the License.
|
|
13
|
+
// Forked from https://github.com/prometheus/prometheus/blob/65f610353919b1c7b42d3776c3a95b68046a6bba/web/ui/mantine-ui/src/promql/utils.ts
|
|
14
|
+
import { binaryOperatorType, nodeType } from './ast';
|
|
15
|
+
const binOpPrecedence = {
|
|
16
|
+
[binaryOperatorType.add]: 3,
|
|
17
|
+
[binaryOperatorType.sub]: 3,
|
|
18
|
+
[binaryOperatorType.mul]: 2,
|
|
19
|
+
[binaryOperatorType.div]: 2,
|
|
20
|
+
[binaryOperatorType.mod]: 2,
|
|
21
|
+
[binaryOperatorType.pow]: 1,
|
|
22
|
+
[binaryOperatorType.eql]: 4,
|
|
23
|
+
[binaryOperatorType.neq]: 4,
|
|
24
|
+
[binaryOperatorType.gtr]: 4,
|
|
25
|
+
[binaryOperatorType.lss]: 4,
|
|
26
|
+
[binaryOperatorType.gte]: 4,
|
|
27
|
+
[binaryOperatorType.lte]: 4,
|
|
28
|
+
[binaryOperatorType.and]: 5,
|
|
29
|
+
[binaryOperatorType.or]: 6,
|
|
30
|
+
[binaryOperatorType.unless]: 5,
|
|
31
|
+
[binaryOperatorType.atan2]: 2
|
|
32
|
+
};
|
|
33
|
+
export const maybeParenthesizeBinopChild = (op, child)=>{
|
|
34
|
+
if (child.type !== nodeType.binaryExpr) {
|
|
35
|
+
return child;
|
|
36
|
+
}
|
|
37
|
+
if (binOpPrecedence[op] > binOpPrecedence[child.op]) {
|
|
38
|
+
return child;
|
|
39
|
+
}
|
|
40
|
+
// TODO: Parens aren't necessary for left-associativity within same precedence,
|
|
41
|
+
// or right-associativity between two power operators.
|
|
42
|
+
return {
|
|
43
|
+
type: nodeType.parenExpr,
|
|
44
|
+
expr: child
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
export const getNodeChildren = (node)=>{
|
|
48
|
+
switch(node.type){
|
|
49
|
+
case nodeType.aggregation:
|
|
50
|
+
return node.param === null ? [
|
|
51
|
+
node.expr
|
|
52
|
+
] : [
|
|
53
|
+
node.param,
|
|
54
|
+
node.expr
|
|
55
|
+
];
|
|
56
|
+
case nodeType.subquery:
|
|
57
|
+
return [
|
|
58
|
+
node.expr
|
|
59
|
+
];
|
|
60
|
+
case nodeType.parenExpr:
|
|
61
|
+
return [
|
|
62
|
+
node.expr
|
|
63
|
+
];
|
|
64
|
+
case nodeType.call:
|
|
65
|
+
return node.args;
|
|
66
|
+
case nodeType.matrixSelector:
|
|
67
|
+
case nodeType.vectorSelector:
|
|
68
|
+
case nodeType.numberLiteral:
|
|
69
|
+
case nodeType.stringLiteral:
|
|
70
|
+
return [];
|
|
71
|
+
case nodeType.placeholder:
|
|
72
|
+
return node.children;
|
|
73
|
+
case nodeType.unaryExpr:
|
|
74
|
+
return [
|
|
75
|
+
node.expr
|
|
76
|
+
];
|
|
77
|
+
case nodeType.binaryExpr:
|
|
78
|
+
return [
|
|
79
|
+
node.lhs,
|
|
80
|
+
node.rhs
|
|
81
|
+
];
|
|
82
|
+
default:
|
|
83
|
+
throw new Error('unsupported node type');
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
export const escapeString = (str)=>{
|
|
87
|
+
return str.replace(/([\\"])/g, '\\$1');
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/components/promql/utils.ts"],"sourcesContent":["// Copyright 2024 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Forked from https://github.com/prometheus/prometheus/blob/65f610353919b1c7b42d3776c3a95b68046a6bba/web/ui/mantine-ui/src/promql/utils.ts\n\nimport ASTNode, { binaryOperatorType, nodeType } from './ast';\n\nconst binOpPrecedence = {\n [binaryOperatorType.add]: 3,\n [binaryOperatorType.sub]: 3,\n [binaryOperatorType.mul]: 2,\n [binaryOperatorType.div]: 2,\n [binaryOperatorType.mod]: 2,\n [binaryOperatorType.pow]: 1,\n [binaryOperatorType.eql]: 4,\n [binaryOperatorType.neq]: 4,\n [binaryOperatorType.gtr]: 4,\n [binaryOperatorType.lss]: 4,\n [binaryOperatorType.gte]: 4,\n [binaryOperatorType.lte]: 4,\n [binaryOperatorType.and]: 5,\n [binaryOperatorType.or]: 6,\n [binaryOperatorType.unless]: 5,\n [binaryOperatorType.atan2]: 2,\n};\n\nexport const maybeParenthesizeBinopChild = (op: binaryOperatorType, child: ASTNode): ASTNode => {\n if (child.type !== nodeType.binaryExpr) {\n return child;\n }\n\n if (binOpPrecedence[op] > binOpPrecedence[child.op]) {\n return child;\n }\n\n // TODO: Parens aren't necessary for left-associativity within same precedence,\n // or right-associativity between two power operators.\n return {\n type: nodeType.parenExpr,\n expr: child,\n };\n};\n\nexport const getNodeChildren = (node: ASTNode): ASTNode[] => {\n switch (node.type) {\n case nodeType.aggregation:\n return node.param === null ? [node.expr] : [node.param, node.expr];\n case nodeType.subquery:\n return [node.expr];\n case nodeType.parenExpr:\n return [node.expr];\n case nodeType.call:\n return node.args;\n case nodeType.matrixSelector:\n case nodeType.vectorSelector:\n case nodeType.numberLiteral:\n case nodeType.stringLiteral:\n return [];\n case nodeType.placeholder:\n return node.children;\n case nodeType.unaryExpr:\n return [node.expr];\n case nodeType.binaryExpr:\n return [node.lhs, node.rhs];\n default:\n throw new Error('unsupported node type');\n }\n};\n\nexport const escapeString = (str: string) => {\n return str.replace(/([\\\\\"])/g, '\\\\$1');\n};\n"],"names":["binaryOperatorType","nodeType","binOpPrecedence","add","sub","mul","div","mod","pow","eql","neq","gtr","lss","gte","lte","and","or","unless","atan2","maybeParenthesizeBinopChild","op","child","type","binaryExpr","parenExpr","expr","getNodeChildren","node","aggregation","param","subquery","call","args","matrixSelector","vectorSelector","numberLiteral","stringLiteral","placeholder","children","unaryExpr","lhs","rhs","Error","escapeString","str","replace"],"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,2IAA2I;AAE3I,SAAkBA,kBAAkB,EAAEC,QAAQ,QAAQ,QAAQ;AAE9D,MAAMC,kBAAkB;IACtB,CAACF,mBAAmBG,GAAG,CAAC,EAAE;IAC1B,CAACH,mBAAmBI,GAAG,CAAC,EAAE;IAC1B,CAACJ,mBAAmBK,GAAG,CAAC,EAAE;IAC1B,CAACL,mBAAmBM,GAAG,CAAC,EAAE;IAC1B,CAACN,mBAAmBO,GAAG,CAAC,EAAE;IAC1B,CAACP,mBAAmBQ,GAAG,CAAC,EAAE;IAC1B,CAACR,mBAAmBS,GAAG,CAAC,EAAE;IAC1B,CAACT,mBAAmBU,GAAG,CAAC,EAAE;IAC1B,CAACV,mBAAmBW,GAAG,CAAC,EAAE;IAC1B,CAACX,mBAAmBY,GAAG,CAAC,EAAE;IAC1B,CAACZ,mBAAmBa,GAAG,CAAC,EAAE;IAC1B,CAACb,mBAAmBc,GAAG,CAAC,EAAE;IAC1B,CAACd,mBAAmBe,GAAG,CAAC,EAAE;IAC1B,CAACf,mBAAmBgB,EAAE,CAAC,EAAE;IACzB,CAAChB,mBAAmBiB,MAAM,CAAC,EAAE;IAC7B,CAACjB,mBAAmBkB,KAAK,CAAC,EAAE;AAC9B;AAEA,OAAO,MAAMC,8BAA8B,CAACC,IAAwBC;IAClE,IAAIA,MAAMC,IAAI,KAAKrB,SAASsB,UAAU,EAAE;QACtC,OAAOF;IACT;IAEA,IAAInB,eAAe,CAACkB,GAAG,GAAGlB,eAAe,CAACmB,MAAMD,EAAE,CAAC,EAAE;QACnD,OAAOC;IACT;IAEA,+EAA+E;IAC/E,sDAAsD;IACtD,OAAO;QACLC,MAAMrB,SAASuB,SAAS;QACxBC,MAAMJ;IACR;AACF,EAAE;AAEF,OAAO,MAAMK,kBAAkB,CAACC;IAC9B,OAAQA,KAAKL,IAAI;QACf,KAAKrB,SAAS2B,WAAW;YACvB,OAAOD,KAAKE,KAAK,KAAK,OAAO;gBAACF,KAAKF,IAAI;aAAC,GAAG;gBAACE,KAAKE,KAAK;gBAAEF,KAAKF,IAAI;aAAC;QACpE,KAAKxB,SAAS6B,QAAQ;YACpB,OAAO;gBAACH,KAAKF,IAAI;aAAC;QACpB,KAAKxB,SAASuB,SAAS;YACrB,OAAO;gBAACG,KAAKF,IAAI;aAAC;QACpB,KAAKxB,SAAS8B,IAAI;YAChB,OAAOJ,KAAKK,IAAI;QAClB,KAAK/B,SAASgC,cAAc;QAC5B,KAAKhC,SAASiC,cAAc;QAC5B,KAAKjC,SAASkC,aAAa;QAC3B,KAAKlC,SAASmC,aAAa;YACzB,OAAO,EAAE;QACX,KAAKnC,SAASoC,WAAW;YACvB,OAAOV,KAAKW,QAAQ;QACtB,KAAKrC,SAASsC,SAAS;YACrB,OAAO;gBAACZ,KAAKF,IAAI;aAAC;QACpB,KAAKxB,SAASsB,UAAU;YACtB,OAAO;gBAACI,KAAKa,GAAG;gBAAEb,KAAKc,GAAG;aAAC;QAC7B;YACE,MAAM,IAAIC,MAAM;IACpB;AACF,EAAE;AAEF,OAAO,MAAMC,eAAe,CAACC;IAC3B,OAAOA,IAAIC,OAAO,CAAC,YAAY;AACjC,EAAE"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DurationString } from '@perses-dev/core';
|
|
2
|
+
import ASTNode from '../components/promql/ast';
|
|
2
3
|
export type { DurationString };
|
|
3
4
|
export interface SuccessResponse<T> {
|
|
4
5
|
status: 'success';
|
|
@@ -81,4 +82,8 @@ export interface MetricMetadataRequestParameters {
|
|
|
81
82
|
metric?: string;
|
|
82
83
|
}
|
|
83
84
|
export type MetricMetadataResponse = ApiResponse<Record<string, MetricMetadata[]>>;
|
|
85
|
+
export interface ParseQueryRequestParameters {
|
|
86
|
+
query: string;
|
|
87
|
+
}
|
|
88
|
+
export type ParseQueryResponse = ApiResponse<ASTNode>;
|
|
84
89
|
//# sourceMappingURL=api-types.d.ts.map
|
|
@@ -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;
|
|
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;AAClD,OAAO,OAAO,MAAM,0BAA0B,CAAC;AAG/C,YAAY,EAAE,cAAc,EAAE,CAAC;AAE/B,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,MAAM,EAAE,SAAS,CAAC;IAClB,IAAI,EAAE,CAAC,CAAC;IACR,WAAW,CAAC,EAAE,QAAQ,CAAC;IACvB,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,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,eAAe,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,CAAC;AAEnE,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC;AAErC,MAAM,MAAM,oBAAoB,GAAG,MAAM,CAAC;AAE1C,MAAM,MAAM,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AAM,CAAC;CAChB;AAED,MAAM,MAAM,cAAc,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC;AAEnD,MAAM,WAAW,2BAA2B;IAC1C,KAAK,CAAC,EAAE,oBAAoB,CAAC;IAC7B,GAAG,CAAC,EAAE,oBAAoB,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,kBAAkB,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC;AAEvD,MAAM,WAAW,4BAA4B;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,oBAAoB,CAAC;IAC7B,GAAG,CAAC,EAAE,oBAAoB,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC;AAExD,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,+BAA+B;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,MAAM,sBAAsB,GAAG,WAAW,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;AAGnF,MAAM,WAAW,2BAA2B;IAC1C,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,kBAAkB,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/model/api-types.ts"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DurationString } from '@perses-dev/core';\n\n// Just reuse dashboard model's type and re-export\nexport type { DurationString };\n\nexport interface SuccessResponse<T> {\n status: 'success';\n data: T;\n 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 limit?: number;\n}\n\nexport type SeriesResponse = ApiResponse<Metric[]>;\n\nexport interface LabelNamesRequestParameters {\n start?: UnixTimestampSeconds;\n end?: UnixTimestampSeconds;\n 'match[]'?: string[];\n limit?: number;\n}\n\nexport type LabelNamesResponse = ApiResponse<string[]>;\n\nexport interface LabelValuesRequestParameters {\n labelName: string;\n start?: UnixTimestampSeconds;\n end?: UnixTimestampSeconds;\n 'match[]'?: string[];\n limit?: number;\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;
|
|
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';\nimport ASTNode from '../components/promql/ast';\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 limit?: number;\n}\n\nexport type SeriesResponse = ApiResponse<Metric[]>;\n\nexport interface LabelNamesRequestParameters {\n start?: UnixTimestampSeconds;\n end?: UnixTimestampSeconds;\n 'match[]'?: string[];\n limit?: number;\n}\n\nexport type LabelNamesResponse = ApiResponse<string[]>;\n\nexport interface LabelValuesRequestParameters {\n labelName: string;\n start?: UnixTimestampSeconds;\n end?: UnixTimestampSeconds;\n 'match[]'?: string[];\n limit?: number;\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\n// ref: https://prometheus.io/docs/prometheus/3.0/querying/api/#parsing-a-promql-expressions-into-a-abstract-syntax-tree-ast\nexport interface ParseQueryRequestParameters {\n query: string;\n}\n\nexport type ParseQueryResponse = ApiResponse<ASTNode>;\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;AAqHjC,WAAsD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { RequestHeaders } from '@perses-dev/core';
|
|
2
2
|
import { DatasourceClient } from '@perses-dev/plugin-system';
|
|
3
|
-
import { InstantQueryRequestParameters, InstantQueryResponse, LabelNamesRequestParameters, LabelNamesResponse, LabelValuesRequestParameters, LabelValuesResponse, MetricMetadataRequestParameters, MetricMetadataResponse, RangeQueryRequestParameters, RangeQueryResponse, SeriesRequestParameters, SeriesResponse } from './api-types';
|
|
3
|
+
import { InstantQueryRequestParameters, InstantQueryResponse, LabelNamesRequestParameters, LabelNamesResponse, LabelValuesRequestParameters, LabelValuesResponse, MetricMetadataRequestParameters, MetricMetadataResponse, ParseQueryRequestParameters, ParseQueryResponse, RangeQueryRequestParameters, RangeQueryResponse, SeriesRequestParameters, SeriesResponse } from './api-types';
|
|
4
4
|
interface PrometheusClientOptions {
|
|
5
5
|
datasourceUrl: string;
|
|
6
6
|
headers?: RequestHeaders;
|
|
@@ -13,6 +13,7 @@ export interface PrometheusClient extends DatasourceClient {
|
|
|
13
13
|
labelValues(params: LabelValuesRequestParameters, headers?: RequestHeaders): Promise<LabelValuesResponse>;
|
|
14
14
|
metricMetadata(params: MetricMetadataRequestParameters, headers?: RequestHeaders): Promise<MetricMetadataResponse>;
|
|
15
15
|
series(params: SeriesRequestParameters, headers?: RequestHeaders): Promise<SeriesResponse>;
|
|
16
|
+
parseQuery(params: ParseQueryRequestParameters, headers?: RequestHeaders): Promise<ParseQueryResponse>;
|
|
16
17
|
}
|
|
17
18
|
export interface QueryOptions {
|
|
18
19
|
datasourceUrl: string;
|
|
@@ -52,6 +53,10 @@ export declare function metricMetadata(params: MetricMetadataRequestParameters,
|
|
|
52
53
|
* Calls the `/api/v1/series` endpoint to finding series by label matchers.
|
|
53
54
|
*/
|
|
54
55
|
export declare function series(params: SeriesRequestParameters, queryOptions: QueryOptions): Promise<SeriesResponse>;
|
|
56
|
+
/**
|
|
57
|
+
* Calls the `/api/v1/parse_query` to parse the given promQL expresion into an abstract syntax tree (AST).
|
|
58
|
+
*/
|
|
59
|
+
export declare function parseQuery(params: ParseQueryRequestParameters, queryOptions: QueryOptions): Promise<ParseQueryResponse>;
|
|
55
60
|
/**
|
|
56
61
|
* Fetch JSON and parse warnings for query inspector
|
|
57
62
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prometheus-client.d.ts","sourceRoot":"","sources":["../../src/model/prometheus-client.ts"],"names":[],"mappings":"AAaA,OAAO,EAAoB,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EACL,6BAA6B,EAC7B,oBAAoB,EACpB,2BAA2B,EAC3B,kBAAkB,EAClB,4BAA4B,EAC5B,mBAAmB,EACnB,+BAA+B,EAC/B,sBAAsB,EACtB,2BAA2B,EAC3B,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,EAEf,MAAM,aAAa,CAAC;AAErB,UAAU,uBAAuB;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,cAAc,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAiB,SAAQ,gBAAgB;IACxD,OAAO,EAAE,uBAAuB,CAAC;IACjC,YAAY,CAAC,MAAM,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAC7G,UAAU,CAAC,MAAM,EAAE,2BAA2B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACvG,UAAU,CAAC,MAAM,EAAE,2BAA2B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACvG,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CAG3G;AAED;;GAEG;AACH,wBAAgB,UAAU,CACxB,MAAM,EAAE,2BAA2B,EACnC,YAAY,EAAE,YAAY,GACzB,OAAO,CAAC,kBAAkB,CAAC,CAG7B;AA+DD;;GAEG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,MAAM,CAAC,KAAK,CAAC;;GAI7E"}
|
|
@@ -69,15 +69,22 @@ import { fetch, fetchJson } from '@perses-dev/core';
|
|
|
69
69
|
const apiURI = `/api/v1/series`;
|
|
70
70
|
return fetchWithPost(apiURI, params, queryOptions);
|
|
71
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* Calls the `/api/v1/parse_query` to parse the given promQL expresion into an abstract syntax tree (AST).
|
|
74
|
+
*/ export function parseQuery(params, queryOptions) {
|
|
75
|
+
const apiURI = `/api/v1/parse_query`;
|
|
76
|
+
return fetchWithPost(apiURI, params, queryOptions);
|
|
77
|
+
}
|
|
72
78
|
function fetchWithGet(apiURI, params, queryOptions) {
|
|
73
|
-
const { datasourceUrl } = queryOptions;
|
|
79
|
+
const { datasourceUrl, headers } = queryOptions;
|
|
74
80
|
let url = `${datasourceUrl}${apiURI}`;
|
|
75
81
|
const urlParams = createSearchParams(params).toString();
|
|
76
82
|
if (urlParams !== '') {
|
|
77
83
|
url += `?${urlParams}`;
|
|
78
84
|
}
|
|
79
85
|
return fetchJson(url, {
|
|
80
|
-
method: 'GET'
|
|
86
|
+
method: 'GET',
|
|
87
|
+
headers
|
|
81
88
|
});
|
|
82
89
|
}
|
|
83
90
|
function fetchWithPost(apiURI, params, queryOptions) {
|
|
@@ -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 { 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 MetricMetadataRequestParameters,\n MetricMetadataResponse,\n RangeQueryRequestParameters,\n RangeQueryResponse,\n SeriesRequestParameters,\n SeriesResponse,\n SuccessResponse,\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 metricMetadata(params: MetricMetadataRequestParameters, headers?: RequestHeaders): Promise<MetricMetadataResponse>;\n series(params: SeriesRequestParameters, headers?: RequestHeaders): Promise<SeriesResponse>;\n}\n\nexport interface QueryOptions {\n datasourceUrl: string;\n headers?: RequestHeaders;\n}\n\n/**\n * Calls the `/-/healthy` endpoint to check if the datasource is healthy.\n */\nexport function healthCheck(queryOptions: QueryOptions) {\n return async () => {\n const url = `${queryOptions.datasourceUrl}/-/healthy`;\n\n try {\n const resp = await fetch(url, { headers: queryOptions.headers });\n return resp.status === 200;\n } catch {\n return false;\n }\n };\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(\n params: LabelValuesRequestParameters,\n queryOptions: QueryOptions\n): Promise<LabelValuesResponse> {\n const { labelName, ...searchParams } = params;\n\n // In case label name is empty, we'll receive a 404, so we can replace it by an empty list, which is less confusing.\n // Note that an empty list is the prometheus result if the label does not exist.\n if (labelName.length === 0) {\n return new Promise((resolve) => {\n resolve({ data: [] as string[] } as SuccessResponse<string[]>);\n });\n }\n\n const apiURI = `/api/v1/label/${encodeURIComponent(labelName)}/values`;\n return fetchWithGet<typeof searchParams, LabelValuesResponse>(apiURI, searchParams, 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 metricMetadata(\n params: MetricMetadataRequestParameters,\n queryOptions: QueryOptions\n): Promise<MetricMetadataResponse> {\n const apiURI = `/api/v1/metadata`;\n return fetchWithGet<MetricMetadataRequestParameters, MetricMetadataResponse>(apiURI, params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/series` endpoint to finding series by label matchers.\n */\nexport function series(params: SeriesRequestParameters, queryOptions: QueryOptions): Promise<SeriesResponse> {\n const apiURI = `/api/v1/series`;\n return fetchWithPost<SeriesRequestParameters, SeriesResponse>(apiURI, params, 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","healthCheck","queryOptions","url","datasourceUrl","resp","headers","status","instantQuery","params","fetchWithPost","rangeQuery","labelNames","labelValues","labelName","searchParams","length","Promise","resolve","data","apiURI","encodeURIComponent","fetchWithGet","metricMetadata","series","urlParams","createSearchParams","toString","method","init","body","fetchResults","URLSearchParams","key","value","undefined","append","val","args","response","json","rawResponse"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE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,MAAMU,OAAOH,MAAO;YACvBnB,aAAaqB,MAAM,CAACH,KAAKI;QAC3B;IACF;IACA,OAAOtB;AACT;AAEA;;CAEC,GACD,OAAO,eAAegB,aAAgB,GAAGO,IAAqC;IAC5E,MAAMC,WAAW,MAAMxC,SAASuC;IAChC,MAAME,OAAU,MAAMD,SAASC,IAAI;IACnC,OAAO;QAAE,GAAGA,IAAI;QAAEC,aAAaF;IAAS;AAC1C"}
|
|
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 MetricMetadataRequestParameters,\n MetricMetadataResponse,\n ParseQueryRequestParameters,\n ParseQueryResponse,\n RangeQueryRequestParameters,\n RangeQueryResponse,\n SeriesRequestParameters,\n SeriesResponse,\n SuccessResponse,\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 metricMetadata(params: MetricMetadataRequestParameters, headers?: RequestHeaders): Promise<MetricMetadataResponse>;\n series(params: SeriesRequestParameters, headers?: RequestHeaders): Promise<SeriesResponse>;\n parseQuery(params: ParseQueryRequestParameters, headers?: RequestHeaders): Promise<ParseQueryResponse>;\n}\n\nexport interface QueryOptions {\n datasourceUrl: string;\n headers?: RequestHeaders;\n}\n\n/**\n * Calls the `/-/healthy` endpoint to check if the datasource is healthy.\n */\nexport function healthCheck(queryOptions: QueryOptions) {\n return async () => {\n const url = `${queryOptions.datasourceUrl}/-/healthy`;\n\n try {\n const resp = await fetch(url, { headers: queryOptions.headers });\n return resp.status === 200;\n } catch {\n return false;\n }\n };\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(\n params: LabelValuesRequestParameters,\n queryOptions: QueryOptions\n): Promise<LabelValuesResponse> {\n const { labelName, ...searchParams } = params;\n\n // In case label name is empty, we'll receive a 404, so we can replace it by an empty list, which is less confusing.\n // Note that an empty list is the prometheus result if the label does not exist.\n if (labelName.length === 0) {\n return new Promise((resolve) => {\n resolve({ data: [] as string[] } as SuccessResponse<string[]>);\n });\n }\n\n const apiURI = `/api/v1/label/${encodeURIComponent(labelName)}/values`;\n return fetchWithGet<typeof searchParams, LabelValuesResponse>(apiURI, searchParams, 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 metricMetadata(\n params: MetricMetadataRequestParameters,\n queryOptions: QueryOptions\n): Promise<MetricMetadataResponse> {\n const apiURI = `/api/v1/metadata`;\n return fetchWithGet<MetricMetadataRequestParameters, MetricMetadataResponse>(apiURI, params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/series` endpoint to finding series by label matchers.\n */\nexport function series(params: SeriesRequestParameters, queryOptions: QueryOptions): Promise<SeriesResponse> {\n const apiURI = `/api/v1/series`;\n return fetchWithPost<SeriesRequestParameters, SeriesResponse>(apiURI, params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/parse_query` to parse the given promQL expresion into an abstract syntax tree (AST).\n */\nexport function parseQuery(\n params: ParseQueryRequestParameters,\n queryOptions: QueryOptions\n): Promise<ParseQueryResponse> {\n const apiURI = `/api/v1/parse_query`;\n return fetchWithPost<ParseQueryRequestParameters, ParseQueryResponse>(apiURI, params, queryOptions);\n}\n\nfunction fetchWithGet<T extends RequestParams<T>, TResponse>(apiURI: string, params: T, queryOptions: QueryOptions) {\n const { datasourceUrl, headers } = 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', headers });\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","healthCheck","queryOptions","url","datasourceUrl","resp","headers","status","instantQuery","params","fetchWithPost","rangeQuery","labelNames","labelValues","labelName","searchParams","length","Promise","resolve","data","apiURI","encodeURIComponent","fetchWithGet","metricMetadata","series","parseQuery","urlParams","createSearchParams","toString","method","init","body","fetchResults","URLSearchParams","key","value","undefined","append","val","args","response","json","rawResponse"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,KAAK,EAAEC,SAAS,QAAwB,mBAAmB;AAyCpE;;CAEC,GACD,OAAO,SAASC,YAAYC,YAA0B;IACpD,OAAO;QACL,MAAMC,MAAM,CAAC,EAAED,aAAaE,aAAa,CAAC,UAAU,CAAC;QAErD,IAAI;YACF,MAAMC,OAAO,MAAMN,MAAMI,KAAK;gBAAEG,SAASJ,aAAaI,OAAO;YAAC;YAC9D,OAAOD,KAAKE,MAAM,KA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IAAS;AAC1C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PrometheusDatasourceEditor.d.ts","sourceRoot":"","sources":["../../src/plugins/PrometheusDatasourceEditor.tsx"],"names":[],"mappings":"AAqBA,OAAO,EAA2B,wBAAwB,EAAE,MAAM,SAAS,CAAC;AAE5E,MAAM,WAAW,+BAA+B;IAC9C,KAAK,EAAE,wBAAwB,CAAC;IAChC,QAAQ,EAAE,CAAC,IAAI,EAAE,wBAAwB,KAAK,IAAI,CAAC;IACnD,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,+BAA+B,
|
|
1
|
+
{"version":3,"file":"PrometheusDatasourceEditor.d.ts","sourceRoot":"","sources":["../../src/plugins/PrometheusDatasourceEditor.tsx"],"names":[],"mappings":"AAqBA,OAAO,EAA2B,wBAAwB,EAAE,MAAM,SAAS,CAAC;AAE5E,MAAM,WAAW,+BAA+B;IAC9C,KAAK,EAAE,wBAAwB,CAAC;IAChC,QAAQ,EAAE,CAAC,IAAI,EAAE,wBAAwB,KAAK,IAAI,CAAC;IACnD,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,+BAA+B,2CAsehF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugins/PrometheusDatasourceEditor.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DurationString, RequestHeaders } from '@perses-dev/core';\nimport { OptionsEditorRadios } from '@perses-dev/plugin-system';\nimport { Grid, IconButton, MenuItem, TextField, Typography } from '@mui/material';\nimport React, { Fragment, useState } from 'react';\nimport { produce } from 'immer';\nimport { Controller } from 'react-hook-form';\nimport MinusIcon from 'mdi-material-ui/Minus';\nimport PlusIcon from 'mdi-material-ui/Plus';\nimport { DEFAULT_SCRAPE_INTERVAL, PrometheusDatasourceSpec } from './types';\n\nexport interface PrometheusDatasourceEditorProps {\n value: PrometheusDatasourceSpec;\n onChange: (next: PrometheusDatasourceSpec) => void;\n isReadonly?: boolean;\n}\n\nexport function PrometheusDatasourceEditor(props: PrometheusDatasourceEditorProps) {\n const { value, onChange, isReadonly } = props;\n const strDirect = 'Direct access';\n const strProxy = 'Proxy';\n\n // utilitary function used for headers when renaming a property\n // -> TODO it would be cleaner to manipulate headers as an intermediary list instead, to avoid doing this.\n const buildNewHeaders = (oldHeaders: RequestHeaders | undefined, oldName: string, newName: string) => {\n if (oldHeaders === undefined) return oldHeaders;\n const keys = Object.keys(oldHeaders);\n const newHeaders = keys.reduce<Record<string, string>>((acc, val) => {\n if (val === oldName) {\n acc[newName] = oldHeaders[oldName] || '';\n } else {\n acc[val] = oldHeaders[val] || '';\n }\n return acc;\n }, {});\n\n return { ...newHeaders };\n };\n\n const tabs = [\n {\n label: strDirect,\n content: (\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.directUrl || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n draft.directUrl = e.target.value;\n })\n );\n }}\n />\n )}\n />\n ),\n },\n {\n label: strProxy,\n content: (\n <>\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.proxy?.spec.url || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.url = e.target.value;\n }\n })\n );\n }}\n sx={{ mb: 2 }}\n />\n )}\n />\n <Typography variant=\"h4\" mb={2}>\n Allowed endpoints\n </Typography>\n <Grid container spacing={2} mb={2}>\n {value.proxy?.spec.allowedEndpoints && value.proxy?.spec.allowedEndpoints.length !== 0 ? (\n value.proxy.spec.allowedEndpoints.map(({ endpointPattern, method }, i) => {\n return (\n <Fragment key={i}>\n <Grid item xs={8}>\n <Controller\n name={`Endpoint pattern ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Endpoint pattern\"\n value={endpointPattern}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: e.target.value,\n method: item.method,\n };\n } else {\n return item;\n }\n }\n );\n }\n })\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={3}>\n <Controller\n name={`Method ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n select\n fullWidth\n label=\"Method\"\n value={method}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: item.endpointPattern,\n method: e.target.value,\n };\n } else {\n return item;\n }\n }\n );\n }\n })\n );\n }}\n >\n <MenuItem value=\"GET\">GET</MenuItem>\n <MenuItem value=\"POST\">POST</MenuItem>\n <MenuItem value=\"PUT\">PUT</MenuItem>\n <MenuItem value=\"PATCH\">PATCH</MenuItem>\n <MenuItem value=\"DELETE\">DELETE</MenuItem>\n </TextField>\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <Controller\n name={`Remove Endpoint ${i}`}\n render={({ field }) => (\n <IconButton\n {...field}\n disabled={isReadonly}\n // Remove the given allowed endpoint from the list\n onClick={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints?.filter((item, itemIndex) => {\n return itemIndex !== i;\n }) || []),\n ];\n }\n })\n );\n }}\n >\n <MinusIcon />\n </IconButton>\n )}\n />\n </Grid>\n </Fragment>\n );\n })\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton\n disabled={isReadonly}\n // Add a new (empty) allowed endpoint to the list\n onClick={() =>\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints ?? []),\n { endpointPattern: '', method: '' },\n ];\n }\n })\n )\n }\n >\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n <Typography variant=\"h4\" mb={2}>\n Request Headers\n </Typography>\n <Grid container spacing={2} mb={2}>\n {value.proxy?.spec.headers &&\n Object.keys(value.proxy.spec.headers).map((headerName, i) => {\n return (\n <Fragment key={i}>\n <Grid item xs={4}>\n <Controller\n name={`Header name ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Header name\"\n value={headerName}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = buildNewHeaders(\n draft.proxy.spec.headers,\n headerName,\n e.target.value\n );\n }\n })\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={7}>\n <Controller\n name={`Header value ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Header value\"\n value={value.proxy?.spec.headers?.[headerName]}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = {\n ...draft.proxy.spec.headers,\n [headerName]: e.target.value,\n };\n }\n })\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <Controller\n name={`Remove Header ${i}`}\n render={({ field }) => (\n <IconButton\n {...field}\n disabled={isReadonly}\n // Remove the given header from the list\n onClick={(e) => {\n field.onChange(e);\n const newHeaders = { ...value.proxy?.spec.headers };\n delete newHeaders[headerName];\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = newHeaders;\n }\n })\n );\n }}\n >\n <MinusIcon />\n </IconButton>\n )}\n />\n </Grid>\n </Fragment>\n );\n })}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton\n disabled={isReadonly}\n // Add a new (empty) header to the list\n onClick={() =>\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = { ...draft.proxy.spec.headers, '': '' };\n }\n })\n )\n }\n >\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n\n <Controller\n name=\"Secret\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Secret\"\n value={value.proxy?.spec.secret || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.secret = e.target.value;\n }\n })\n );\n }}\n />\n )}\n />\n </>\n ),\n },\n ];\n\n // Use of findIndex instead of providing hardcoded values to avoid desynchronisatio or\n // bug in case the tabs get eventually swapped in the future.\n const directModeId = tabs.findIndex((tab) => tab.label === strDirect);\n const proxyModeId = tabs.findIndex((tab) => tab.label === strProxy);\n\n // In \"update datasource\" case, set defaultTab to the mode that this datasource is currently relying on.\n // Otherwise (create datasource), set defaultTab to Direct access.\n const defaultTab = value.proxy ? proxyModeId : directModeId;\n\n const initialSpecDirect: PrometheusDatasourceSpec = {\n directUrl: '',\n };\n\n const initialSpecProxy: PrometheusDatasourceSpec = {\n proxy: {\n kind: 'HTTPProxy',\n spec: {\n allowedEndpoints: [\n // list of standard endpoints suggested by default\n {\n endpointPattern: '/api/v1/labels',\n method: 'POST',\n },\n {\n endpointPattern: '/api/v1/series',\n method: 'POST',\n },\n {\n endpointPattern: '/api/v1/metadata',\n method: 'GET',\n },\n {\n endpointPattern: '/api/v1/query',\n method: 'POST',\n },\n {\n endpointPattern: '/api/v1/query_range',\n method: 'POST',\n },\n {\n endpointPattern: '/api/v1/label/([a-zA-Z0-9_-]+)/values',\n method: 'GET',\n },\n ],\n url: '',\n },\n },\n };\n\n // For better user experience, save previous states in mind for both mode.\n // This avoids losing everything when the user changes their mind back.\n const [previousSpecDirect, setPreviousSpecDirect] = useState(initialSpecDirect);\n const [previousSpecProxy, setPreviousSpecProxy] = useState(initialSpecProxy);\n\n // When changing mode, remove previous mode's config + append default values for the new mode.\n const handleModeChange = (v: number) => {\n if (tabs[v]?.label === strDirect) {\n setPreviousSpecProxy(value);\n onChange(previousSpecDirect);\n } else if (tabs[v]?.label === strProxy) {\n setPreviousSpecDirect(value);\n onChange(previousSpecProxy);\n }\n };\n\n return (\n <>\n <Typography variant=\"h4\" mb={2}>\n General Settings\n </Typography>\n <TextField\n fullWidth\n label=\"Scrape Interval\"\n value={value.scrapeInterval || ''}\n placeholder={`Default: ${DEFAULT_SCRAPE_INTERVAL}`}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => onChange({ ...value, scrapeInterval: e.target.value as DurationString })}\n />\n <Typography variant=\"h4\" mt={2}>\n HTTP Settings\n </Typography>\n <OptionsEditorRadios\n isReadonly={isReadonly}\n tabs={tabs}\n defaultTab={defaultTab}\n onModeChange={handleModeChange}\n />\n </>\n );\n}\n"],"names":["OptionsEditorRadios","Grid","IconButton","MenuItem","TextField","Typography","React","Fragment","useState","produce","Controller","MinusIcon","PlusIcon","DEFAULT_SCRAPE_INTERVAL","PrometheusDatasourceEditor","props","value","onChange","isReadonly","strDirect","strProxy","buildNewHeaders","oldHeaders","oldName","newName","undefined","keys","Object","newHeaders","reduce","acc","val","tabs","label","content","name","render","field","fieldState","fullWidth","directUrl","error","helperText","message","InputProps","readOnly","InputLabelProps","shrink","e","draft","target","proxy","spec","url","sx","mb","variant","container","spacing","allowedEndpoints","length","map","endpointPattern","method","i","item","xs","itemIndex","select","disabled","onClick","filter","fontStyle","paddingTop","paddingLeft","headers","headerName","secret","directModeId","findIndex","tab","proxyModeId","defaultTab","initialSpecDirect","initialSpecProxy","kind","previousSpecDirect","setPreviousSpecDirect","previousSpecProxy","setPreviousSpecProxy","handleModeChange","v","scrapeInterval","placeholder","mt","onModeChange"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAA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Q;gBAAKD,IAAI;0BAAG;;0BAGhC,KAACnD;gBACCmC,SAAS;gBACTN,OAAM;gBACNjB,OAAOA,MAAM4E,cAAc,IAAI;gBAC/BC,aAAa,CAAC,SAAS,EAAEhF,wBAAwB,CAAC;gBAClD+B,YAAY;oBACVC,UAAU3B;gBACZ;gBACA4B,iBAAiB;oBAAEC,QAAQ7B,aAAa,OAAOO;gBAAU;gBACzDR,UAAU,CAAC+B,IAAM/B,SAAS;wBAAE,GAAGD,KAAK;wBAAE4E,gBAAgB5C,EAAEE,MAAM,CAAClC,KAAK;oBAAmB;;0BAEzF,KAACX;gBAAWmD,SAAQ;gBAAKsC,IAAI;0BAAG;;0BAGhC,KAAC9F;gBACCkB,YAAYA;gBACZc,MAAMA;gBACNkD,YAAYA;gBACZa,cAAcL;;;;AAItB"}
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/PrometheusDatasourceEditor.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DurationString, RequestHeaders } from '@perses-dev/core';\nimport { OptionsEditorRadios } from '@perses-dev/plugin-system';\nimport { Grid, IconButton, MenuItem, TextField, Typography } from '@mui/material';\nimport React, { Fragment, useState } from 'react';\nimport { produce } from 'immer';\nimport { Controller } from 'react-hook-form';\nimport MinusIcon from 'mdi-material-ui/Minus';\nimport PlusIcon from 'mdi-material-ui/Plus';\nimport { DEFAULT_SCRAPE_INTERVAL, PrometheusDatasourceSpec } from './types';\n\nexport interface PrometheusDatasourceEditorProps {\n value: PrometheusDatasourceSpec;\n onChange: (next: PrometheusDatasourceSpec) => void;\n isReadonly?: boolean;\n}\n\nexport function PrometheusDatasourceEditor(props: PrometheusDatasourceEditorProps) {\n const { value, onChange, isReadonly } = props;\n const strDirect = 'Direct access';\n const strProxy = 'Proxy';\n\n // utilitary function used for headers when renaming a property\n // -> TODO it would be cleaner to manipulate headers as an intermediary list instead, to avoid doing this.\n const buildNewHeaders = (oldHeaders: RequestHeaders | undefined, oldName: string, newName: string) => {\n if (oldHeaders === undefined) return oldHeaders;\n const keys = Object.keys(oldHeaders);\n const newHeaders = keys.reduce<Record<string, string>>((acc, val) => {\n if (val === oldName) {\n acc[newName] = oldHeaders[oldName] || '';\n } else {\n acc[val] = oldHeaders[val] || '';\n }\n return acc;\n }, {});\n\n return { ...newHeaders };\n };\n\n const tabs = [\n {\n label: strDirect,\n content: (\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.directUrl || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n draft.directUrl = e.target.value;\n })\n );\n }}\n />\n )}\n />\n ),\n },\n {\n label: strProxy,\n content: (\n <>\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.proxy?.spec.url || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.url = e.target.value;\n }\n })\n );\n }}\n sx={{ mb: 2 }}\n />\n )}\n />\n <Typography variant=\"h4\" mb={2}>\n Allowed endpoints\n </Typography>\n <Grid container spacing={2} mb={2}>\n {value.proxy?.spec.allowedEndpoints && value.proxy?.spec.allowedEndpoints.length !== 0 ? (\n value.proxy.spec.allowedEndpoints.map(({ endpointPattern, method }, i) => {\n return (\n <Fragment key={i}>\n <Grid item xs={8}>\n <Controller\n name={`Endpoint pattern ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Endpoint pattern\"\n value={endpointPattern}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: e.target.value,\n method: item.method,\n };\n } else {\n return item;\n }\n }\n );\n }\n })\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={3}>\n <Controller\n name={`Method ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n select\n fullWidth\n label=\"Method\"\n value={method}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: item.endpointPattern,\n method: e.target.value,\n };\n } else {\n return item;\n }\n }\n );\n }\n })\n );\n }}\n >\n <MenuItem value=\"GET\">GET</MenuItem>\n <MenuItem value=\"POST\">POST</MenuItem>\n <MenuItem value=\"PUT\">PUT</MenuItem>\n <MenuItem value=\"PATCH\">PATCH</MenuItem>\n <MenuItem value=\"DELETE\">DELETE</MenuItem>\n </TextField>\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <Controller\n name={`Remove Endpoint ${i}`}\n render={({ field }) => (\n <IconButton\n {...field}\n disabled={isReadonly}\n // Remove the given allowed endpoint from the list\n onClick={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints?.filter((item, itemIndex) => {\n return itemIndex !== i;\n }) || []),\n ];\n }\n })\n );\n }}\n >\n <MinusIcon />\n </IconButton>\n )}\n />\n </Grid>\n </Fragment>\n );\n })\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton\n disabled={isReadonly}\n // Add a new (empty) allowed endpoint to the list\n onClick={() =>\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints ?? []),\n { endpointPattern: '', method: '' },\n ];\n }\n })\n )\n }\n >\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n <Typography variant=\"h4\" mb={2}>\n Request Headers\n </Typography>\n <Grid container spacing={2} mb={2}>\n {value.proxy?.spec.headers &&\n Object.keys(value.proxy.spec.headers).map((headerName, i) => {\n return (\n <Fragment key={i}>\n <Grid item xs={4}>\n <Controller\n name={`Header name ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Header name\"\n value={headerName}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = buildNewHeaders(\n draft.proxy.spec.headers,\n headerName,\n e.target.value\n );\n }\n })\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={7}>\n <Controller\n name={`Header value ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Header value\"\n value={value.proxy?.spec.headers?.[headerName]}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = {\n ...draft.proxy.spec.headers,\n [headerName]: e.target.value,\n };\n }\n })\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <Controller\n name={`Remove Header ${i}`}\n render={({ field }) => (\n <IconButton\n {...field}\n disabled={isReadonly}\n // Remove the given header from the list\n onClick={(e) => {\n field.onChange(e);\n const newHeaders = { ...value.proxy?.spec.headers };\n delete newHeaders[headerName];\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = newHeaders;\n }\n })\n );\n }}\n >\n <MinusIcon />\n </IconButton>\n )}\n />\n </Grid>\n </Fragment>\n );\n })}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton\n disabled={isReadonly}\n // Add a new (empty) header to the list\n onClick={() =>\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = { ...draft.proxy.spec.headers, '': '' };\n }\n })\n )\n }\n >\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n\n <Controller\n name=\"Secret\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Secret\"\n value={value.proxy?.spec.secret || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.secret = e.target.value;\n }\n })\n );\n }}\n />\n )}\n />\n </>\n ),\n },\n ];\n\n // Use of findIndex instead of providing hardcoded values to avoid desynchronisatio or\n // bug in case the tabs get eventually swapped in the future.\n const directModeId = tabs.findIndex((tab) => tab.label === strDirect);\n const proxyModeId = tabs.findIndex((tab) => tab.label === strProxy);\n\n // In \"update datasource\" case, set defaultTab to the mode that this datasource is currently relying on.\n // Otherwise (create datasource), set defaultTab to Direct access.\n const defaultTab = value.proxy ? proxyModeId : directModeId;\n\n const initialSpecDirect: PrometheusDatasourceSpec = {\n directUrl: '',\n };\n\n const initialSpecProxy: PrometheusDatasourceSpec = {\n proxy: {\n kind: 'HTTPProxy',\n spec: {\n allowedEndpoints: [\n // list of standard endpoints suggested by default\n {\n endpointPattern: '/api/v1/labels',\n method: 'POST',\n },\n {\n endpointPattern: '/api/v1/series',\n method: 'POST',\n },\n {\n endpointPattern: '/api/v1/metadata',\n method: 'GET',\n },\n {\n endpointPattern: '/api/v1/query',\n method: 'POST',\n },\n {\n endpointPattern: '/api/v1/query_range',\n method: 'POST',\n },\n {\n endpointPattern: '/api/v1/label/([a-zA-Z0-9_-]+)/values',\n method: 'GET',\n },\n {\n endpointPattern: '/api/v1/parse_query',\n method: 'POST',\n },\n ],\n url: '',\n },\n },\n };\n\n // For better user experience, save previous states in mind for both mode.\n // This avoids losing everything when the user changes their mind back.\n const [previousSpecDirect, setPreviousSpecDirect] = useState(initialSpecDirect);\n const [previousSpecProxy, setPreviousSpecProxy] = useState(initialSpecProxy);\n\n // When changing mode, remove previous mode's config + append default values for the new mode.\n const handleModeChange = (v: number) => {\n if (tabs[v]?.label === strDirect) {\n setPreviousSpecProxy(value);\n onChange(previousSpecDirect);\n } else if (tabs[v]?.label === strProxy) {\n setPreviousSpecDirect(value);\n onChange(previousSpecProxy);\n }\n };\n\n return (\n <>\n <Typography variant=\"h4\" mb={2}>\n General Settings\n </Typography>\n <TextField\n fullWidth\n label=\"Scrape Interval\"\n value={value.scrapeInterval || ''}\n placeholder={`Default: ${DEFAULT_SCRAPE_INTERVAL}`}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => onChange({ ...value, scrapeInterval: e.target.value as DurationString })}\n />\n <Typography variant=\"h4\" mt={2}>\n HTTP Settings\n </Typography>\n <OptionsEditorRadios\n isReadonly={isReadonly}\n tabs={tabs}\n defaultTab={defaultTab}\n onModeChange={handleModeChange}\n />\n </>\n );\n}\n"],"names":["OptionsEditorRadios","Grid","IconButton","MenuItem","TextField","Typography","React","Fragment","useState","produce","Controller","MinusIcon","PlusIcon","DEFAULT_SCRAPE_INTERVAL","PrometheusDatasourceEditor","props","value","onChange","isReadonly","strDirect","strProxy","buildNewHeaders","oldHeaders","oldName","newName","undefined","keys","Object","newHeaders","reduce","acc","val","tabs","label","content","name","render","field","fieldState","fullWidth","directUrl","error","helperText","message","InputProps","readOnly","InputLabelProps","shrink","e","draft","target","proxy","spec","url","sx","mb","variant","container","spacing","allowedEndpoints","length","map","endpointPattern","method","i","item","xs","itemIndex","select","disabled","onClick","filter","fontStyle","paddingTop","paddingLeft","headers","headerName","secret","directModeId","findIndex","tab","proxyModeId","defaultTab","initialSpecDirect","initialSpecProxy","kind","previousSpecDirect","setPreviousSpecDirect","previousSpecProxy","setPreviousSpecProxy","handleModeChange","v","scrapeInterval","placeholder","mt","onModeChange"],"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,mBAAmB,QAAQ,4BAA4B;AAChE,SAASC,IAAI,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,SAAS,EAAEC,UAAU,QAAQ,gBAAgB;AAClF,OAAOC,SAASC,QAAQ,EAAEC,QAAQ,QAAQ,QAAQ;AAClD,SAASC,OAAO,QAAQ,QA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aAAa,OAAOO;gBAAU;gBACzDR,UAAU,CAAC+B,IAAM/B,SAAS;wBAAE,GAAGD,KAAK;wBAAE4E,gBAAgB5C,EAAEE,MAAM,CAAClC,KAAK;oBAAmB;;0BAEzF,KAACX;gBAAWmD,SAAQ;gBAAKsC,IAAI;0BAAG;;0BAGhC,KAAC9F;gBACCkB,YAAYA;gBACZc,MAAMA;gBACNkD,YAAYA;gBACZa,cAAcL;;;;AAItB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prometheus-datasource.d.ts","sourceRoot":"","sources":["../../src/plugins/prometheus-datasource.tsx"],"names":[],"mappings":"AAcA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAML,gBAAgB,
|
|
1
|
+
{"version":3,"file":"prometheus-datasource.d.ts","sourceRoot":"","sources":["../../src/plugins/prometheus-datasource.tsx"],"names":[],"mappings":"AAcA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAML,gBAAgB,EAIjB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAC;AAiFnD,eAAO,MAAM,oBAAoB,EAAE,gBAAgB,CAAC,wBAAwB,EAAE,gBAAgB,CAK7F,CAAC"}
|
|
@@ -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 { healthCheck, instantQuery, rangeQuery, labelNames, labelValues, metricMetadata, series } from '../model';
|
|
13
|
+
import { healthCheck, instantQuery, rangeQuery, labelNames, labelValues, metricMetadata, series, parseQuery } from '../model';
|
|
14
14
|
import { PrometheusDatasourceEditor } from './PrometheusDatasourceEditor';
|
|
15
15
|
/**
|
|
16
16
|
* Creates a PrometheusClient for a specific datasource spec.
|
|
@@ -55,6 +55,10 @@ import { PrometheusDatasourceEditor } from './PrometheusDatasourceEditor';
|
|
|
55
55
|
series: (params, headers)=>series(params, {
|
|
56
56
|
datasourceUrl,
|
|
57
57
|
headers: headers !== null && headers !== void 0 ? headers : specHeaders
|
|
58
|
+
}),
|
|
59
|
+
parseQuery: (params, headers)=>parseQuery(params, {
|
|
60
|
+
datasourceUrl,
|
|
61
|
+
headers: headers !== null && headers !== void 0 ? headers : specHeaders
|
|
58
62
|
})
|
|
59
63
|
};
|
|
60
64
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugins/prometheus-datasource.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { BuiltinVariableDefinition } from '@perses-dev/core';\nimport { DatasourcePlugin } from '@perses-dev/plugin-system';\nimport {\n healthCheck,\n instantQuery,\n rangeQuery,\n labelNames,\n labelValues,\n PrometheusClient,\n metricMetadata,\n series,\n} from '../model';\nimport { PrometheusDatasourceSpec } from './types';\nimport { PrometheusDatasourceEditor } from './PrometheusDatasourceEditor';\n\n/**\n * Creates a PrometheusClient for a specific datasource spec.\n */\nconst createClient: DatasourcePlugin<PrometheusDatasourceSpec, PrometheusClient>['createClient'] = (spec, options) => {\n const { directUrl, proxy } = 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 = directUrl ?? proxyUrl;\n if (datasourceUrl === undefined) {\n throw new Error('No URL specified for Prometheus client. You can use directUrl in the spec to configure it.');\n }\n\n const specHeaders = proxy?.spec.headers;\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 healthCheck: healthCheck({ datasourceUrl, headers: specHeaders }),\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 metricMetadata: (params, headers) => metricMetadata(params, { datasourceUrl, headers: headers ?? specHeaders }),\n series: (params, headers) => series(params, { datasourceUrl, headers: headers ?? specHeaders }),\n };\n};\n\nconst getBuiltinVariableDefinitions: () => BuiltinVariableDefinition[] = () => {\n return [\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__interval',\n value: () => '$__interval', // will be overriden when time series query is called\n source: 'Prometheus',\n display: {\n name: '__interval',\n description:\n 'Interval that can be used to group by time in queries. When there are more data points than can be shown on a graph then queries can be made more efficient by grouping by a larger interval.',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__interval_ms',\n value: () => '$__interval_ms', // will be overriden when time series query is called\n source: 'Prometheus',\n display: {\n name: '__interval_ms',\n description:\n 'Interval in millisecond that can be used to group by time in queries. When there are more data points than can be shown on a graph then queries can be made more efficient by grouping by a larger interval.',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__rate_interval',\n value: () => '$__rate_interval', // will be overriden when time series query is called\n source: 'Prometheus',\n display: {\n name: '__rate_interval',\n description:\n \"Interval at least four times the value of the scrape interval. It avoids problems specific to Prometheus when using 'rate' and 'increase' functions.\",\n hidden: true,\n },\n },\n },\n ] as BuiltinVariableDefinition[];\n};\n\nexport const PrometheusDatasource: DatasourcePlugin<PrometheusDatasourceSpec, PrometheusClient> = {\n createClient,\n getBuiltinVariableDefinitions,\n OptionsEditorComponent: PrometheusDatasourceEditor,\n createInitialOptions: () => ({ directUrl: '' }),\n};\n"],"names":["healthCheck","instantQuery","rangeQuery","labelNames","labelValues","metricMetadata","series","PrometheusDatasourceEditor","createClient","spec","options","directUrl","proxy","proxyUrl","datasourceUrl","undefined","Error","specHeaders","headers","params","getBuiltinVariableDefinitions","kind","name","value","source","display","description","hidden","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,SACEA,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,UAAU,EACVC,WAAW,EAEXC,cAAc,EACdC,MAAM,
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/prometheus-datasource.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { BuiltinVariableDefinition } from '@perses-dev/core';\nimport { DatasourcePlugin } from '@perses-dev/plugin-system';\nimport {\n healthCheck,\n instantQuery,\n rangeQuery,\n labelNames,\n labelValues,\n PrometheusClient,\n metricMetadata,\n series,\n parseQuery,\n} from '../model';\nimport { PrometheusDatasourceSpec } from './types';\nimport { PrometheusDatasourceEditor } from './PrometheusDatasourceEditor';\n\n/**\n * Creates a PrometheusClient for a specific datasource spec.\n */\nconst createClient: DatasourcePlugin<PrometheusDatasourceSpec, PrometheusClient>['createClient'] = (spec, options) => {\n const { directUrl, proxy } = 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 = directUrl ?? proxyUrl;\n if (datasourceUrl === undefined) {\n throw new Error('No URL specified for Prometheus client. You can use directUrl in the spec to configure it.');\n }\n\n const specHeaders = proxy?.spec.headers;\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 healthCheck: healthCheck({ datasourceUrl, headers: specHeaders }),\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 metricMetadata: (params, headers) => metricMetadata(params, { datasourceUrl, headers: headers ?? specHeaders }),\n series: (params, headers) => series(params, { datasourceUrl, headers: headers ?? specHeaders }),\n parseQuery: (params, headers) => parseQuery(params, { datasourceUrl, headers: headers ?? specHeaders }),\n };\n};\n\nconst getBuiltinVariableDefinitions: () => BuiltinVariableDefinition[] = () => {\n return [\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__interval',\n value: () => '$__interval', // will be overriden when time series query is called\n source: 'Prometheus',\n display: {\n name: '__interval',\n description:\n 'Interval that can be used to group by time in queries. When there are more data points than can be shown on a graph then queries can be made more efficient by grouping by a larger interval.',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__interval_ms',\n value: () => '$__interval_ms', // will be overriden when time series query is called\n source: 'Prometheus',\n display: {\n name: '__interval_ms',\n description:\n 'Interval in millisecond that can be used to group by time in queries. When there are more data points than can be shown on a graph then queries can be made more efficient by grouping by a larger interval.',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__rate_interval',\n value: () => '$__rate_interval', // will be overriden when time series query is called\n source: 'Prometheus',\n display: {\n name: '__rate_interval',\n description:\n \"Interval at least four times the value of the scrape interval. It avoids problems specific to Prometheus when using 'rate' and 'increase' functions.\",\n hidden: true,\n },\n },\n },\n ] as BuiltinVariableDefinition[];\n};\n\nexport const PrometheusDatasource: DatasourcePlugin<PrometheusDatasourceSpec, PrometheusClient> = {\n createClient,\n getBuiltinVariableDefinitions,\n OptionsEditorComponent: PrometheusDatasourceEditor,\n createInitialOptions: () => ({ directUrl: '' }),\n};\n"],"names":["healthCheck","instantQuery","rangeQuery","labelNames","labelValues","metricMetadata","series","parseQuery","PrometheusDatasourceEditor","createClient","spec","options","directUrl","proxy","proxyUrl","datasourceUrl","undefined","Error","specHeaders","headers","params","getBuiltinVariableDefinitions","kind","name","value","source","display","description","hidden","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,SACEA,WAAW,EACXC,YAAY,EACZC,UAAU,EACVC,UAAU,EACVC,WAAW,EAEXC,cAAc,EACdC,MAAM,EACNC,UAAU,QACL,WAAW;AAElB,SAASC,0BAA0B,QAAQ,+BAA+B;AAE1E;;CAEC,GACD,MAAMC,eAA6F,CAACC,MAAMC;IACxG,MAAM,EAAEC,SAAS,EAAEC,KAAK,EAAE,GAAGH;IAC7B,MAAM,EAAEI,QAAQ,EAAE,GAAGH;IAErB,4FAA4F;IAC5F,MAAMI,gBAAgBH,sBAAAA,uBAAAA,YAAaE;IACnC,IAAIC,kBAAkBC,WAAW;QAC/B,MAAM,IAAIC,MAAM;IAClB;IAEA,MAAMC,cAAcL,kBAAAA,4BAAAA,MAAOH,IAAI,CAACS,OAAO;IAEvC,qFAAqF;IACrF,OAAO;QACLR,SAAS;YACPI;QACF;QACAf,aAAaA,YAAY;YAAEe;YAAeI,SAASD;QAAY;QAC/DjB,cA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AqF;IAChGpB;IACAY;IACAS,wBAAwBtB;IACxBuB,sBAAsB,IAAO,CAAA;YAAEnB,WAAW;QAAG,CAAA;AAC/C,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PrometheusTimeSeriesQueryEditor.d.ts","sourceRoot":"","sources":["../../../src/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.tsx"],"names":[],"mappings":"AA0BA,OAAO,EACL,oCAAoC,EAIrC,MAAM,sBAAsB,CAAC;AAE9B;;GAEG;AACH,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,oCAAoC,
|
|
1
|
+
{"version":3,"file":"PrometheusTimeSeriesQueryEditor.d.ts","sourceRoot":"","sources":["../../../src/plugins/prometheus-time-series-query/PrometheusTimeSeriesQueryEditor.tsx"],"names":[],"mappings":"AA0BA,OAAO,EACL,oCAAoC,EAIrC,MAAM,sBAAsB,CAAC;AAE9B;;GAEG;AACH,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,oCAAoC,2CA0E1F"}
|
|
@@ -28,7 +28,7 @@ import { useQueryState, useFormatState, useMinStepState } from './query-editor-m
|
|
|
28
28
|
const { data: client } = useDatasourceClient(selectedDatasource);
|
|
29
29
|
const promURL = client === null || client === void 0 ? void 0 : client.options.datasourceUrl;
|
|
30
30
|
const { data: datasourceResource } = useDatasource(selectedDatasource);
|
|
31
|
-
const {
|
|
31
|
+
const { handleQueryChange, handleQueryBlur } = useQueryState(props);
|
|
32
32
|
const { format, handleFormatChange, handleFormatBlur } = useFormatState(props);
|
|
33
33
|
const { minStep, handleMinStepChange, handleMinStepBlur } = useMinStepState(props);
|
|
34
34
|
var _ref;
|
|
@@ -70,7 +70,8 @@ import { useQueryState, useFormatState, useMinStepState } from './query-editor-m
|
|
|
70
70
|
url: promURL
|
|
71
71
|
}
|
|
72
72
|
},
|
|
73
|
-
value: query,
|
|
73
|
+
value: value.query,
|
|
74
|
+
datasource: selectedDatasource,
|
|
74
75
|
onChange: handleQueryChange,
|
|
75
76
|
onBlur: handleQueryBlur
|
|
76
77
|
}),
|
|
@@ -80,9 +81,9 @@ import { useQueryState, useFormatState, useMinStepState } from './query-editor-m
|
|
|
80
81
|
children: [
|
|
81
82
|
/*#__PURE__*/ _jsx(TextField, {
|
|
82
83
|
fullWidth: true,
|
|
83
|
-
label: "Legend
|
|
84
|
-
placeholder: "
|
|
85
|
-
helperText: "
|
|
84
|
+
label: "Legend",
|
|
85
|
+
placeholder: "Example: '{{instance}}' will generate series names like 'webserver-123', 'webserver-456'...",
|
|
86
|
+
helperText: "Text to be displayed in the legend and the tooltip. Use {{label_name}} to interpolate label values.",
|
|
86
87
|
value: format !== null && format !== void 0 ? format : '',
|
|
87
88
|
onChange: (e)=>handleFormatChange(e.target.value),
|
|
88
89
|
onBlur: handleFormatBlur
|