@red-hat-developer-hub/backstage-plugin-scorecard-backend 2.7.4 → 2.7.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @red-hat-developer-hub/backstage-plugin-scorecard-backend
2
2
 
3
+ ## 2.7.5
4
+
5
+ ### Patch Changes
6
+
7
+ - 5115044: ### Threshold validation
8
+
9
+ Implemented threshold interval validation for Scorecard: joint coverage on the real line, gap detection and error messages, and overlap handling versus rule order (including aggregation KPI `options.thresholds` for `average`).
10
+
11
+ ### Aggregation
12
+
13
+ For **`type: average`** aggregations, **`result.averageScore`** returned by **`GET /aggregations/:aggregationId`** (and the same shape wherever it appears) is a **portfolio percentage in \[0, 100\]** with **one decimal place** — the same scale used for **`options.thresholds`** evaluation and the homepage donut.
14
+
15
+ Previously **`averageScore`** was a **normalized ratio in \[0, 1\]** (rounded to **three** decimal places). Any consumer that treated the old value as a fraction and multiplied by **100** for display, or compared it to thresholds on a 0–100 scale without converting, must **stop scaling**: use **`averageScore`** directly as the percentage. If you stored historical API payloads, recompute or re-fetch rather than assuming the old fractional scale.
16
+
17
+ - Updated dependencies [5115044]
18
+ - @red-hat-developer-hub/backstage-plugin-scorecard-node@2.7.5
19
+ - @red-hat-developer-hub/backstage-plugin-scorecard-common@2.7.5
20
+
3
21
  ## 2.7.4
4
22
 
5
23
  ### Patch Changes
package/README.md CHANGED
@@ -116,9 +116,9 @@ Thresholds define conditions to assign metric values to specific visual categori
116
116
  - **App Configuration**: Override defaults through `app-config.yaml`
117
117
  - **Entity Annotations**: Override specific thresholds per entity using catalog annotations
118
118
 
119
- Thresholds are evaluated in order, and the first matching rule determines the category. The plugin supports various operators for number metrics (`>`, `>=`, `<`, `<=`, `==`, `!=`, `-` (range)) and boolean metrics (`==`, `!=`).
119
+ Thresholds are evaluated in order, and the first matching rule determines the category. The plugin supports various operators for number metrics (`>`, `>=`, `<`, `<=`, `==`, `!=`, `-` (range)) and boolean metrics (`==`, `!=`). For **number** metrics, configurations loaded through validated paths must cover the **entire real line** when two or more rules are defined (no gaps between intervals); **`average`** KPI **`options.thresholds`** follow the same rule.
120
120
 
121
- For comprehensive threshold configuration guide, examples, best practices, and **aggregation KPI result thresholds** for **`type: average`**, see [thresholds.md](./docs/thresholds.md).
121
+ For comprehensive threshold configuration guide, examples, best practices, interval validation, and **aggregation KPI result thresholds** for **`type: average`**, see [thresholds.md](./docs/thresholds.md).
122
122
 
123
123
  ## Aggregation KPIs (homepage and `GET /aggregations`)
124
124
 
@@ -154,20 +154,20 @@ scorecard:
154
154
  expression: '>=75'
155
155
  color: success.main
156
156
  - key: warning
157
- expression: '10-74'
157
+ expression: '10-75'
158
158
  color: warning.main
159
159
  - key: error
160
160
  expression: '<10'
161
161
  color: error.main
162
162
  ```
163
163
 
164
- | Field | Description |
165
- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
166
- | `title` | Display title for this aggregation (returned in API metadata). |
167
- | `description` | Display description for this aggregation. |
168
- | `type` | Aggregation algorithm: `statusGrouped` (counts per threshold status) or `average` (normalized weighted score). |
169
- | `metricId` | Metric provider id used to load thresholds and compute counts. |
170
- | `options` | Optional for `statusGrouped`. **Required** for `average`: must include **`options.statusScores`** — map status keys to numeric weights (typically one entry per **metric threshold rule key**). Optionally **`options.thresholds`** (same shape as metric thresholds; see [thresholds.md — Aggregation KPI result thresholds](./docs/thresholds.md#4-aggregation-kpi-result-thresholds-average-type)); evaluated on **`averageScore × 100`**; first match sets **`aggregationChartDisplayColor`**. The API includes **`averageScore`** (ratio **0–1**, **one decimal**), **`averageWeightedSum`**, **`averageMaxPossible`**, and **`aggregationChartDisplayColor`** (from configured or default result thresholds). |
164
+ | Field | Description |
165
+ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
166
+ | `title` | Display title for this aggregation (returned in API metadata). |
167
+ | `description` | Display description for this aggregation. |
168
+ | `type` | Aggregation algorithm: `statusGrouped` (counts per threshold status) or `average` (normalized weighted score). |
169
+ | `metricId` | Metric provider id used to load thresholds and compute counts. |
170
+ | `options` | Optional for `statusGrouped`. **Required** for `average`: must include **`options.statusScores`** — map status keys to numeric weights (typically one entry per **metric threshold rule key**). Optionally **`options.thresholds`** (same shape as metric thresholds; see [thresholds.md — Aggregation KPI result thresholds](./docs/thresholds.md#4-aggregation-kpi-result-thresholds-average-type)); evaluated on **`averageScore`** (**0–100** portfolio percentage, **one decimal**); first match sets **`aggregationChartDisplayColor`**. The API includes **`averageScore`**, **`averageWeightedSum`**, **`averageMaxPossible`**, and **`aggregationChartDisplayColor`** (from configured or default result thresholds). |
171
171
 
172
172
  - **Path**: `scorecard.aggregationKPIs.<aggregationId>`.
173
173
  - If **`aggregationKPIs` is omitted** or a given id is not listed, **`GET /aggregations/:aggregationId`** still works when **`aggregationId` equals the metric id** (e.g. `github.open_prs`): the backend uses that metric with the default `statusGrouped` aggregation and metric-defined title/description.
@@ -12,7 +12,7 @@ const DEFAULT_AVERAGE_KPI_RESULT_THRESHOLDS = {
12
12
  },
13
13
  {
14
14
  key: "warning",
15
- expression: "30-79",
15
+ expression: "30-80",
16
16
  color: backstagePluginScorecardCommon.ScorecardThresholdRuleColors.WARNING
17
17
  },
18
18
  {
@@ -1 +1 @@
1
- {"version":3,"file":"aggregationKPIs.cjs.js","sources":["../../src/constants/aggregationKPIs.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\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\nimport {\n type ThresholdConfig,\n ScorecardThresholdRuleColors,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\n\nexport const AGGREGATION_KPIS_CONFIG_PATH =\n 'scorecard.aggregationKPIs' as const;\n\n/**\n * Default applied by `AverageAggregationStrategy` when `options.thresholds` is omitted\n * from app-config. Higher headline percentage (0–100) = better. Evaluated in order; first match wins.\n */\nexport const DEFAULT_AVERAGE_KPI_RESULT_THRESHOLDS: ThresholdConfig = {\n rules: [\n {\n key: 'success',\n expression: '>=80',\n color: ScorecardThresholdRuleColors.SUCCESS,\n },\n {\n key: 'warning',\n expression: '30-79',\n color: ScorecardThresholdRuleColors.WARNING,\n },\n {\n key: 'error',\n expression: '<30',\n color: ScorecardThresholdRuleColors.ERROR,\n },\n ],\n};\n"],"names":["ScorecardThresholdRuleColors"],"mappings":";;;;AAqBO,MAAM,4BACX,GAAA;AAMK,MAAM,qCAAyD,GAAA;AAAA,EACpE,KAAO,EAAA;AAAA,IACL;AAAA,MACE,GAAK,EAAA,SAAA;AAAA,MACL,UAAY,EAAA,MAAA;AAAA,MACZ,OAAOA,2DAA6B,CAAA;AAAA,KACtC;AAAA,IACA;AAAA,MACE,GAAK,EAAA,SAAA;AAAA,MACL,UAAY,EAAA,OAAA;AAAA,MACZ,OAAOA,2DAA6B,CAAA;AAAA,KACtC;AAAA,IACA;AAAA,MACE,GAAK,EAAA,OAAA;AAAA,MACL,UAAY,EAAA,KAAA;AAAA,MACZ,OAAOA,2DAA6B,CAAA;AAAA;AACtC;AAEJ;;;;;"}
1
+ {"version":3,"file":"aggregationKPIs.cjs.js","sources":["../../src/constants/aggregationKPIs.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\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\nimport {\n type ThresholdConfig,\n ScorecardThresholdRuleColors,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\n\nexport const AGGREGATION_KPIS_CONFIG_PATH =\n 'scorecard.aggregationKPIs' as const;\n\n/**\n * Default applied by `AverageAggregationStrategy` when `options.thresholds` is omitted\n * from app-config. Higher headline percentage (0–100) = better. Evaluated in order; first match wins.\n */\nexport const DEFAULT_AVERAGE_KPI_RESULT_THRESHOLDS: ThresholdConfig = {\n rules: [\n {\n key: 'success',\n expression: '>=80',\n color: ScorecardThresholdRuleColors.SUCCESS,\n },\n {\n key: 'warning',\n expression: '30-80',\n color: ScorecardThresholdRuleColors.WARNING,\n },\n {\n key: 'error',\n expression: '<30',\n color: ScorecardThresholdRuleColors.ERROR,\n },\n ],\n};\n"],"names":["ScorecardThresholdRuleColors"],"mappings":";;;;AAqBO,MAAM,4BACX,GAAA;AAMK,MAAM,qCAAyD,GAAA;AAAA,EACpE,KAAO,EAAA;AAAA,IACL;AAAA,MACE,GAAK,EAAA,SAAA;AAAA,MACL,UAAY,EAAA,MAAA;AAAA,MACZ,OAAOA,2DAA6B,CAAA;AAAA,KACtC;AAAA,IACA;AAAA,MACE,GAAK,EAAA,SAAA;AAAA,MACL,UAAY,EAAA,OAAA;AAAA,MACZ,OAAOA,2DAA6B,CAAA;AAAA,KACtC;AAAA,IACA;AAAA,MACE,GAAK,EAAA,OAAA;AAAA,MACL,UAAY,EAAA,KAAA;AAAA,MACZ,OAAOA,2DAA6B,CAAA;AAAA;AACtC;AAEJ;;;;;"}
@@ -44,14 +44,13 @@ class AverageAggregationStrategy {
44
44
  thresholds.rules,
45
45
  weightedSum
46
46
  );
47
- const scorePercent = averageScore * 100;
48
47
  const aggregationChartDisplayColor = this.getAggregationChartDisplayColor(
49
- scorePercent,
48
+ averageScore,
50
49
  headlineThresholds
51
50
  );
52
51
  if (!aggregationChartDisplayColor) {
53
52
  throw new Error(
54
- `The color for percentage '${scorePercent}' metric '${metric.id}' is not configured. Check the 'scorecard.aggregationKPIs.${aggregationConfig.id}.options.thresholds' configuration.`
53
+ `The color for percentage '${averageScore}' metric '${metric.id}' is not configured. Check the 'scorecard.aggregationKPIs.${aggregationConfig.id}.options.thresholds' configuration.`
55
54
  );
56
55
  }
57
56
  const result = {
@@ -102,8 +101,7 @@ class AverageAggregationStrategy {
102
101
  const statusScoresValues = rules.map((r) => statusScores[r.key] ?? 0);
103
102
  const maxScore = Math.max(0, ...statusScoresValues);
104
103
  const maxPossibleScore = maxScore * numberOfEntities;
105
- const precision = 1e3;
106
- const averageScore = numberOfEntities > 0 && maxPossibleScore > 0 ? Math.round(weightedSum / maxPossibleScore * precision) / precision : 0;
104
+ const averageScore = numberOfEntities > 0 && maxPossibleScore > 0 ? Math.round(weightedSum / maxPossibleScore * 1e3) / 10 : 0;
107
105
  return { averageScore, maxPossibleScore };
108
106
  }
109
107
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AverageAggregationStrategy.cjs.js","sources":["../../../../src/service/aggregations/strategies/AverageAggregationStrategy.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\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\nimport {\n type AggregatedMetric,\n type AggregatedMetricAverageResult,\n type AggregatedMetricResult,\n type ThresholdConfig,\n ThresholdRule,\n type AggregationConfigOptions,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\nimport { DEFAULT_AVERAGE_KPI_RESULT_THRESHOLDS } from '../../../constants/aggregationKPIs';\nimport { AggregatedMetricMapper } from '../../mappers';\nimport type { AggregatedMetricLoader } from '../AggregatedMetricLoader';\nimport type { AggregationOptions } from '../types';\nimport type { AggregationStrategy } from './types';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { ThresholdEvaluator } from '../../../threshold/ThresholdEvaluator';\n\nexport class AverageAggregationStrategy implements AggregationStrategy {\n constructor(\n private readonly loader: AggregatedMetricLoader,\n private readonly logger: LoggerService,\n ) {}\n\n async aggregate({\n entityRefs,\n metric,\n thresholds,\n aggregationConfig,\n }: AggregationOptions): Promise<AggregatedMetricResult> {\n const { options } = aggregationConfig;\n\n if (!options?.statusScores) {\n throw new Error(\n `The \"scorecard.aggregationKPIs.${aggregationConfig.id}.options.statusScores\" is required for average aggregation`,\n );\n }\n\n if (!options.thresholds) {\n this.logger.info(\n `The \"scorecard.aggregationKPIs.${aggregationConfig.id}.options.thresholds\" is not configured for average aggregation; ` +\n 'using the default 0–100% health scale (higher is better).',\n );\n }\n\n const headlineThresholds =\n options.thresholds ?? DEFAULT_AVERAGE_KPI_RESULT_THRESHOLDS;\n\n const aggregatedMetric =\n await this.loader.loadStatusGroupedMetricByEntityRefs(\n entityRefs,\n metric.id,\n );\n\n const weightedSum = this.calculateWeightedSum(\n aggregatedMetric.values,\n options.statusScores,\n metric.id,\n );\n\n const { averageScore, maxPossibleScore } = this.prepareScoreValues(\n aggregatedMetric.total,\n options.statusScores,\n thresholds.rules,\n weightedSum,\n );\n\n const scorePercent = averageScore * 100;\n\n const aggregationChartDisplayColor = this.getAggregationChartDisplayColor(\n scorePercent,\n headlineThresholds,\n );\n\n if (!aggregationChartDisplayColor) {\n throw new Error(\n `The color for percentage '${scorePercent}' metric '${metric.id}' is not configured. Check the 'scorecard.aggregationKPIs.${aggregationConfig.id}.options.thresholds' configuration.`,\n );\n }\n\n const result = {\n total: aggregatedMetric.total,\n timestamp: aggregatedMetric.timestamp,\n entitiesConsidered: aggregatedMetric.entitiesConsidered,\n calculationErrorCount: aggregatedMetric.calculationErrorCount,\n values: thresholds.rules.map(rule => ({\n name: rule.key,\n count: aggregatedMetric.values[rule.key] ?? 0,\n score: options.statusScores[rule.key] ?? 0,\n })),\n thresholds,\n averageScore,\n averageWeightedSum: weightedSum,\n averageMaxPossible: maxPossibleScore,\n aggregationChartDisplayColor,\n } as AggregatedMetricAverageResult;\n\n return AggregatedMetricMapper.toAggregatedMetricResult(\n metric,\n result,\n aggregationConfig,\n );\n }\n\n private calculateWeightedSum(\n values: Pick<AggregatedMetric, 'values'>['values'],\n statusScores: AggregationConfigOptions['statusScores'],\n metricId: string,\n ): number {\n let weightedSum = 0;\n for (const [status, count] of Object.entries(values)) {\n const score = statusScores[status];\n\n if (score === undefined) {\n this.logger.warn(\n `The status \"${status}\" is not in the statusScores for average aggregation of metric \"${metricId}\"`,\n );\n }\n weightedSum += count * (score ?? 0);\n }\n return weightedSum;\n }\n\n private getAggregationChartDisplayColor(\n scorePercent: number,\n thresholds: ThresholdConfig,\n ): string | undefined {\n const thresholdEvaluator = new ThresholdEvaluator();\n\n const matchedThresholdKey = thresholdEvaluator.getFirstMatchingThreshold(\n scorePercent,\n 'number',\n thresholds,\n );\n\n return thresholds.rules.find(r => r.key === matchedThresholdKey)?.color;\n }\n\n private prepareScoreValues(\n numberOfEntities: Pick<AggregatedMetric, 'total'>['total'],\n statusScores: AggregationConfigOptions['statusScores'],\n rules: ThresholdRule[],\n weightedSum: number,\n ): { averageScore: number; maxPossibleScore: number } {\n const statusScoresValues = rules.map(r => statusScores[r.key] ?? 0);\n\n const maxScore = Math.max(0, ...statusScoresValues);\n\n const maxPossibleScore = maxScore * numberOfEntities;\n\n const precision = 1000;\n\n const averageScore =\n numberOfEntities > 0 && maxPossibleScore > 0\n ? Math.round((weightedSum / maxPossibleScore) * precision) / precision\n : 0;\n\n return { averageScore, maxPossibleScore };\n }\n}\n"],"names":["DEFAULT_AVERAGE_KPI_RESULT_THRESHOLDS","AggregatedMetricMapper","ThresholdEvaluator"],"mappings":";;;;;;AAgCO,MAAM,0BAA0D,CAAA;AAAA,EACrE,WAAA,CACmB,QACA,MACjB,EAAA;AAFiB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA;AAChB,EAFgB,MAAA;AAAA,EACA,MAAA;AAAA,EAGnB,MAAM,SAAU,CAAA;AAAA,IACd,UAAA;AAAA,IACA,MAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACsD,EAAA;AACtD,IAAM,MAAA,EAAE,SAAY,GAAA,iBAAA;AAEpB,IAAI,IAAA,CAAC,SAAS,YAAc,EAAA;AAC1B,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,+BAAA,EAAkC,kBAAkB,EAAE,CAAA,0DAAA;AAAA,OACxD;AAAA;AAGF,IAAI,IAAA,CAAC,QAAQ,UAAY,EAAA;AACvB,MAAA,IAAA,CAAK,MAAO,CAAA,IAAA;AAAA,QACV,CAAA,+BAAA,EAAkC,kBAAkB,EAAE,CAAA,8HAAA;AAAA,OAExD;AAAA;AAGF,IAAM,MAAA,kBAAA,GACJ,QAAQ,UAAc,IAAAA,qDAAA;AAExB,IAAM,MAAA,gBAAA,GACJ,MAAM,IAAA,CAAK,MAAO,CAAA,mCAAA;AAAA,MAChB,UAAA;AAAA,MACA,MAAO,CAAA;AAAA,KACT;AAEF,IAAA,MAAM,cAAc,IAAK,CAAA,oBAAA;AAAA,MACvB,gBAAiB,CAAA,MAAA;AAAA,MACjB,OAAQ,CAAA,YAAA;AAAA,MACR,MAAO,CAAA;AAAA,KACT;AAEA,IAAA,MAAM,EAAE,YAAA,EAAc,gBAAiB,EAAA,GAAI,IAAK,CAAA,kBAAA;AAAA,MAC9C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I,SAC3D,GAAA,CAAA;AAEN,IAAO,OAAA,EAAE,cAAc,gBAAiB,EAAA;AAAA;AAE5C;;;;"}
1
+ {"version":3,"file":"AverageAggregationStrategy.cjs.js","sources":["../../../../src/service/aggregations/strategies/AverageAggregationStrategy.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\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\nimport {\n type AggregatedMetric,\n type AggregatedMetricAverageResult,\n type AggregatedMetricResult,\n type ThresholdConfig,\n ThresholdRule,\n type AggregationConfigOptions,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\nimport { DEFAULT_AVERAGE_KPI_RESULT_THRESHOLDS } from '../../../constants/aggregationKPIs';\nimport { AggregatedMetricMapper } from '../../mappers';\nimport type { AggregatedMetricLoader } from '../AggregatedMetricLoader';\nimport type { AggregationOptions } from '../types';\nimport type { AggregationStrategy } from './types';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { ThresholdEvaluator } from '../../../threshold/ThresholdEvaluator';\n\nexport class AverageAggregationStrategy implements AggregationStrategy {\n constructor(\n private readonly loader: AggregatedMetricLoader,\n private readonly logger: LoggerService,\n ) {}\n\n async aggregate({\n entityRefs,\n metric,\n thresholds,\n aggregationConfig,\n }: AggregationOptions): Promise<AggregatedMetricResult> {\n const { options } = aggregationConfig;\n\n if (!options?.statusScores) {\n throw new Error(\n `The \"scorecard.aggregationKPIs.${aggregationConfig.id}.options.statusScores\" is required for average aggregation`,\n );\n }\n\n if (!options.thresholds) {\n this.logger.info(\n `The \"scorecard.aggregationKPIs.${aggregationConfig.id}.options.thresholds\" is not configured for average aggregation; ` +\n 'using the default 0–100% health scale (higher is better).',\n );\n }\n\n const headlineThresholds =\n options.thresholds ?? DEFAULT_AVERAGE_KPI_RESULT_THRESHOLDS;\n\n const aggregatedMetric =\n await this.loader.loadStatusGroupedMetricByEntityRefs(\n entityRefs,\n metric.id,\n );\n\n const weightedSum = this.calculateWeightedSum(\n aggregatedMetric.values,\n options.statusScores,\n metric.id,\n );\n\n const { averageScore, maxPossibleScore } = this.prepareScoreValues(\n aggregatedMetric.total,\n options.statusScores,\n thresholds.rules,\n weightedSum,\n );\n\n const aggregationChartDisplayColor = this.getAggregationChartDisplayColor(\n averageScore,\n headlineThresholds,\n );\n\n if (!aggregationChartDisplayColor) {\n throw new Error(\n `The color for percentage '${averageScore}' metric '${metric.id}' is not configured. Check the 'scorecard.aggregationKPIs.${aggregationConfig.id}.options.thresholds' configuration.`,\n );\n }\n\n const result = {\n total: aggregatedMetric.total,\n timestamp: aggregatedMetric.timestamp,\n entitiesConsidered: aggregatedMetric.entitiesConsidered,\n calculationErrorCount: aggregatedMetric.calculationErrorCount,\n values: thresholds.rules.map(rule => ({\n name: rule.key,\n count: aggregatedMetric.values[rule.key] ?? 0,\n score: options.statusScores[rule.key] ?? 0,\n })),\n thresholds,\n averageScore,\n averageWeightedSum: weightedSum,\n averageMaxPossible: maxPossibleScore,\n aggregationChartDisplayColor,\n } as AggregatedMetricAverageResult;\n\n return AggregatedMetricMapper.toAggregatedMetricResult(\n metric,\n result,\n aggregationConfig,\n );\n }\n\n private calculateWeightedSum(\n values: Pick<AggregatedMetric, 'values'>['values'],\n statusScores: AggregationConfigOptions['statusScores'],\n metricId: string,\n ): number {\n let weightedSum = 0;\n for (const [status, count] of Object.entries(values)) {\n const score = statusScores[status];\n\n if (score === undefined) {\n this.logger.warn(\n `The status \"${status}\" is not in the statusScores for average aggregation of metric \"${metricId}\"`,\n );\n }\n weightedSum += count * (score ?? 0);\n }\n return weightedSum;\n }\n\n private getAggregationChartDisplayColor(\n scorePercent: number,\n thresholds: ThresholdConfig,\n ): string | undefined {\n const thresholdEvaluator = new ThresholdEvaluator();\n\n const matchedThresholdKey = thresholdEvaluator.getFirstMatchingThreshold(\n scorePercent,\n 'number',\n thresholds,\n );\n\n return thresholds.rules.find(r => r.key === matchedThresholdKey)?.color;\n }\n\n private prepareScoreValues(\n numberOfEntities: Pick<AggregatedMetric, 'total'>['total'],\n statusScores: AggregationConfigOptions['statusScores'],\n rules: ThresholdRule[],\n weightedSum: number,\n ): { averageScore: number; maxPossibleScore: number } {\n const statusScoresValues = rules.map(r => statusScores[r.key] ?? 0);\n\n const maxScore = Math.max(0, ...statusScoresValues);\n\n const maxPossibleScore = maxScore * numberOfEntities;\n\n const averageScore =\n numberOfEntities > 0 && maxPossibleScore > 0\n ? Math.round((weightedSum / maxPossibleScore) * 1000) / 10\n : 0;\n\n return { averageScore, maxPossibleScore };\n }\n}\n"],"names":["DEFAULT_AVERAGE_KPI_RESULT_THRESHOLDS","AggregatedMetricMapper","ThresholdEvaluator"],"mappings":";;;;;;AAgCO,MAAM,0BAA0D,CAAA;AAAA,EACrE,WAAA,CACmB,QACA,MACjB,EAAA;AAFiB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA;AAChB,EAFgB,MAAA;AAAA,EACA,MAAA;AAAA,EAGnB,MAAM,SAAU,CAAA;AAAA,IACd,UAAA;AAAA,IACA,MAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACsD,EAAA;AACtD,IAAM,MAAA,EAAE,SAAY,GAAA,iBAAA;AAEpB,IAAI,IAAA,CAAC,SAAS,YAAc,EAAA;AAC1B,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,+BAAA,EAAkC,kBAAkB,EAAE,CAAA,0DAAA;AAAA,OACxD;AAAA;AAGF,IAAI,IAAA,CAAC,QAAQ,UAAY,EAAA;AACvB,MAAA,IAAA,CAAK,MAAO,CAAA,IAAA;AAAA,QACV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A;AACpD,IAAM,MAAA,kBAAA,GAAqB,MAAM,GAAI,CAAA,CAAA,CAAA,KAAK,aAAa,CAAE,CAAA,GAAG,KAAK,CAAC,CAAA;AAElE,IAAA,MAAM,QAAW,GAAA,IAAA,CAAK,GAAI,CAAA,CAAA,EAAG,GAAG,kBAAkB,CAAA;AAElD,IAAA,MAAM,mBAAmB,QAAW,GAAA,gBAAA;AAEpC,IAAM,MAAA,YAAA,GACJ,gBAAmB,GAAA,CAAA,IAAK,gBAAmB,GAAA,CAAA,GACvC,IAAK,CAAA,KAAA,CAAO,WAAc,GAAA,gBAAA,GAAoB,GAAI,CAAA,GAAI,EACtD,GAAA,CAAA;AAEN,IAAO,OAAA,EAAE,cAAc,gBAAiB,EAAA;AAAA;AAE5C;;;;"}
@@ -18,6 +18,7 @@ function parseEntityAnnotationThresholds(entity, providerId) {
18
18
  return overrides;
19
19
  }
20
20
  function mergeEntityAndProviderThresholds(entity, provider) {
21
+ let isRulesMerged = false;
21
22
  const providerId = provider.getProviderId();
22
23
  const providerThresholds = provider.getMetricThresholds();
23
24
  const providerMetricType = provider.getMetricType();
@@ -40,6 +41,7 @@ function mergeEntityAndProviderThresholds(entity, provider) {
40
41
  const mergedRule = { ...mergedRules[foundKey], ...override };
41
42
  try {
42
43
  backstagePluginScorecardNode.validateThresholdsForMetric({ rules: [mergedRule] }, providerMetricType);
44
+ if (!isRulesMerged) isRulesMerged = true;
43
45
  } catch (e) {
44
46
  if (errors.isError(e)) {
45
47
  throw new backstagePluginScorecardNode.ThresholdConfigFormatError(
@@ -52,6 +54,9 @@ function mergeEntityAndProviderThresholds(entity, provider) {
52
54
  }
53
55
  mergedRules[foundKey] = mergedRule;
54
56
  }
57
+ if (isRulesMerged) {
58
+ backstagePluginScorecardNode.validateThresholdNumberIntervals(mergedRules, providerMetricType);
59
+ }
55
60
  return {
56
61
  rules: mergedRules
57
62
  };
@@ -1 +1 @@
1
- {"version":3,"file":"mergeEntityAndProviderThresholds.cjs.js","sources":["../../src/utils/mergeEntityAndProviderThresholds.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\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\nimport { stringifyEntityRef, type Entity } from '@backstage/catalog-model';\nimport type {\n ThresholdConfig,\n ThresholdRule,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\nimport {\n type MetricProvider,\n validateThresholdsForMetric,\n ThresholdConfigFormatError,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-node';\nimport { isError } from '@backstage/errors';\n\nconst thresholdRulesAnnotationPrefix = (providerId: string) =>\n `scorecard.io/${providerId}.thresholds.rules.`;\n\n/**\n * Extract threshold override rules from entity annotations for a given provider, doesn't validate rules.\n */\nfunction parseEntityAnnotationThresholds(\n entity: Entity,\n providerId: string,\n): ThresholdRule[] {\n const annotations = entity.metadata?.annotations || {};\n const prefix = thresholdRulesAnnotationPrefix(providerId);\n const overrides: ThresholdRule[] = [];\n\n for (const [annotationKey, expression] of Object.entries(annotations)) {\n if (annotationKey.startsWith(prefix) && expression) {\n const key = annotationKey.substring(prefix.length);\n overrides.push({ key, expression });\n }\n }\n\n return overrides;\n}\n\nexport function mergeEntityAndProviderThresholds(\n entity: Entity,\n provider: MetricProvider,\n): ThresholdConfig {\n const providerId = provider.getProviderId();\n const providerThresholds = provider.getMetricThresholds();\n const providerMetricType = provider.getMetricType();\n const entityAnnotationThresholds = parseEntityAnnotationThresholds(\n entity,\n providerId,\n );\n\n const mergedRules = [...providerThresholds.rules];\n for (const override of entityAnnotationThresholds) {\n const foundKey = mergedRules.findIndex(rule => rule.key === override.key);\n if (foundKey === -1) {\n throw new ThresholdConfigFormatError(\n `Unable to override ${stringifyEntityRef(\n entity,\n )} thresholds by ${JSON.stringify(\n override,\n )}, metric provider ${providerId} does not support key ${override.key}`,\n );\n }\n\n const mergedRule: ThresholdRule = { ...mergedRules[foundKey], ...override };\n try {\n validateThresholdsForMetric({ rules: [mergedRule] }, providerMetricType);\n } catch (e) {\n if (isError(e)) {\n throw new ThresholdConfigFormatError(\n `Invalid threshold annotation '${thresholdRulesAnnotationPrefix(\n providerId,\n )}${override.key}: ${\n override.expression\n }' in entity '${stringifyEntityRef(entity)}': ${e.message}`,\n );\n }\n throw e;\n }\n\n mergedRules[foundKey] = mergedRule;\n }\n\n return {\n rules: mergedRules,\n };\n}\n"],"names":["ThresholdConfigFormatError","stringifyEntityRef","validateThresholdsForMetric","isError"],"mappings":";;;;;;AA4BA,MAAM,8BAAiC,GAAA,CAAC,UACtC,KAAA,CAAA,aAAA,EAAgB,UAAU,CAAA,kBAAA,CAAA;AAK5B,SAAS,+BAAA,CACP,QACA,UACiB,EAAA;AACjB,EAAA,MAAM,WAAc,GAAA,MAAA,CAAO,QAAU,EAAA,WAAA,IAAe,EAAC;AACrD,EAAM,MAAA,MAAA,GAAS,+BAA+B,UAAU,CAAA;AACxD,EAAA,MAAM,YAA6B,EAAC;AAEpC,EAAA,KAAA,MAAW,CAAC,aAAe,EAAA,UAAU,KAAK,MAAO,CAAA,OAAA,CAAQ,WAAW,CAAG,EAAA;AACrE,IAAA,IAAI,aAAc,CAAA,UAAA,CAAW,MAAM,CAAA,IAAK,UAAY,EAAA;AAClD,MAAA,MAAM,GAAM,GAAA,aAAA,CAAc,SAAU,CAAA,MAAA,CAAO,MAAM,CAAA;AACjD,MAAA,SAAA,CAAU,IAAK,CAAA,EAAE,GAAK,EAAA,UAAA,EAAY,CAAA;AAAA;AACpC;AAGF,EAAO,OAAA,SAAA;AACT;AAEgB,SAAA,gCAAA,CACd,QACA,QACiB,EAAA;AACjB,EAAM,MAAA,UAAA,GAAa,SAA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WAAA,CAAY,QAAQ,CAAI,GAAA,UAAA;AAAA;AAG1B,EAAO,OAAA;AAAA,IACL,KAAO,EAAA;AAAA,GACT;AACF;;;;"}
1
+ {"version":3,"file":"mergeEntityAndProviderThresholds.cjs.js","sources":["../../src/utils/mergeEntityAndProviderThresholds.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\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\nimport { stringifyEntityRef, type Entity } from '@backstage/catalog-model';\nimport type {\n ThresholdConfig,\n ThresholdRule,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\nimport {\n type MetricProvider,\n validateThresholdsForMetric,\n ThresholdConfigFormatError,\n validateThresholdNumberIntervals,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-node';\nimport { isError } from '@backstage/errors';\n\nconst thresholdRulesAnnotationPrefix = (providerId: string) =>\n `scorecard.io/${providerId}.thresholds.rules.`;\n\n/**\n * Extract threshold override rules from entity annotations for a given provider, doesn't validate rules.\n */\nfunction parseEntityAnnotationThresholds(\n entity: Entity,\n providerId: string,\n): ThresholdRule[] {\n const annotations = entity.metadata?.annotations || {};\n const prefix = thresholdRulesAnnotationPrefix(providerId);\n const overrides: ThresholdRule[] = [];\n\n for (const [annotationKey, expression] of Object.entries(annotations)) {\n if (annotationKey.startsWith(prefix) && expression) {\n const key = annotationKey.substring(prefix.length);\n overrides.push({ key, expression });\n }\n }\n\n return overrides;\n}\n\nexport function mergeEntityAndProviderThresholds(\n entity: Entity,\n provider: MetricProvider,\n): ThresholdConfig {\n let isRulesMerged = false;\n\n const providerId = provider.getProviderId();\n const providerThresholds = provider.getMetricThresholds();\n const providerMetricType = provider.getMetricType();\n const entityAnnotationThresholds = parseEntityAnnotationThresholds(\n entity,\n providerId,\n );\n\n const mergedRules = [...providerThresholds.rules];\n for (const override of entityAnnotationThresholds) {\n const foundKey = mergedRules.findIndex(rule => rule.key === override.key);\n if (foundKey === -1) {\n throw new ThresholdConfigFormatError(\n `Unable to override ${stringifyEntityRef(\n entity,\n )} thresholds by ${JSON.stringify(\n override,\n )}, metric provider ${providerId} does not support key ${override.key}`,\n );\n }\n\n const mergedRule: ThresholdRule = { ...mergedRules[foundKey], ...override };\n try {\n validateThresholdsForMetric({ rules: [mergedRule] }, providerMetricType);\n\n if (!isRulesMerged) isRulesMerged = true;\n } catch (e) {\n if (isError(e)) {\n throw new ThresholdConfigFormatError(\n `Invalid threshold annotation '${thresholdRulesAnnotationPrefix(\n providerId,\n )}${override.key}: ${\n override.expression\n }' in entity '${stringifyEntityRef(entity)}': ${e.message}`,\n );\n }\n throw e;\n }\n\n mergedRules[foundKey] = mergedRule;\n }\n\n if (isRulesMerged) {\n validateThresholdNumberIntervals(mergedRules, providerMetricType);\n }\n\n return {\n rules: mergedRules,\n };\n}\n"],"names":["ThresholdConfigFormatError","stringifyEntityRef","validateThresholdsForMetric","isError","validateThresholdNumberIntervals"],"mappings":";;;;;;AA6BA,MAAM,8BAAiC,GAAA,CAAC,UACtC,KAAA,CAAA,aAAA,EAAgB,UAAU,CAAA,kBAAA,CAAA;AAK5B,SAAS,+BAAA,CACP,QACA,UACiB,EAAA;AACjB,EAAA,MAAM,WAAc,GAAA,MAAA,CAAO,QAAU,EAAA,WAAA,IAAe,EAAC;AACrD,EAAM,MAAA,MAAA,GAAS,+BAA+B,UAAU,CAAA;AACxD,EAAA,MAAM,YAA6B,EAAC;AAEpC,EAAA,KAAA,MAAW,CAAC,aAAe,EAAA,UAAU,KAAK,MAAO,CAAA,OAAA,CAAQ,WAAW,CAAG,EAAA;AACrE,IAAA,IAAI,aAAc,CAAA,UAAA,CAAW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GAAA,IAAA;AAAA,aAC7B,CAAG,EAAA;AACV,MAAI,IAAAC,cAAA,CAAQ,CAAC,CAAG,EAAA;AACd,QAAA,MAAM,IAAIH,uDAAA;AAAA,UACR,CAAiC,8BAAA,EAAA,8BAAA;AAAA,YAC/B;AAAA,WACD,CAAA,EAAG,QAAS,CAAA,GAAG,CACd,EAAA,EAAA,QAAA,CAAS,UACX,CAAA,aAAA,EAAgBC,+BAAmB,CAAA,MAAM,CAAC,CAAA,GAAA,EAAM,EAAE,OAAO,CAAA;AAAA,SAC3D;AAAA;AAEF,MAAM,MAAA,CAAA;AAAA;AAGR,IAAA,WAAA,CAAY,QAAQ,CAAI,GAAA,UAAA;AAAA;AAG1B,EAAA,IAAI,aAAe,EAAA;AACjB,IAAAG,6DAAA,CAAiC,aAAa,kBAAkB,CAAA;AAAA;AAGlE,EAAO,OAAA;AAAA,IACL,KAAO,EAAA;AAAA,GACT;AACF;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@red-hat-developer-hub/backstage-plugin-scorecard-backend",
3
- "version": "2.7.4",
3
+ "version": "2.7.5",
4
4
  "license": "Apache-2.0",
5
5
  "main": "dist/index.cjs.js",
6
6
  "types": "dist/index.d.ts",
@@ -47,8 +47,8 @@
47
47
  "@backstage/plugin-catalog-node": "^2.1.0",
48
48
  "@backstage/plugin-permission-common": "^0.9.7",
49
49
  "@backstage/plugin-permission-node": "^0.10.11",
50
- "@red-hat-developer-hub/backstage-plugin-scorecard-common": "^2.7.4",
51
- "@red-hat-developer-hub/backstage-plugin-scorecard-node": "^2.7.4",
50
+ "@red-hat-developer-hub/backstage-plugin-scorecard-common": "^2.7.5",
51
+ "@red-hat-developer-hub/backstage-plugin-scorecard-node": "^2.7.5",
52
52
  "express": "^4.17.1",
53
53
  "express-promise-router": "^4.1.0",
54
54
  "knex": "^3.1.0",