@red-hat-developer-hub/backstage-plugin-scorecard-backend 2.3.2 → 2.3.4
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 +20 -0
- package/README.md +8 -8
- package/dist/database/DatabaseMetricValues.cjs.js +9 -5
- package/dist/database/DatabaseMetricValues.cjs.js.map +1 -1
- package/dist/service/CatalogMetricService.cjs.js +12 -42
- package/dist/service/CatalogMetricService.cjs.js.map +1 -1
- package/dist/service/mappers.cjs.js +36 -0
- package/dist/service/mappers.cjs.js.map +1 -0
- package/dist/service/router.cjs.js +7 -9
- package/dist/service/router.cjs.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# @red-hat-developer-hub/backstage-plugin-scorecard-backend
|
|
2
2
|
|
|
3
|
+
## 2.3.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- c964f4f: Fixed an issue when PullMetricsByProviderTask would fail when no entities in Catalog supported metric provider that was processed
|
|
8
|
+
- 4a3369f: Fix aggregated scorecard widgets view when entities are missing value or metric fetching fails.
|
|
9
|
+
|
|
10
|
+
Refactor the /metrics/:metricId/catalog/aggregations endpoint to return an object of aggregated metrics instead of an array containing a single object.
|
|
11
|
+
|
|
12
|
+
- Updated dependencies [4a3369f]
|
|
13
|
+
- @red-hat-developer-hub/backstage-plugin-scorecard-common@2.3.4
|
|
14
|
+
- @red-hat-developer-hub/backstage-plugin-scorecard-node@2.3.4
|
|
15
|
+
|
|
16
|
+
## 2.3.3
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- @red-hat-developer-hub/backstage-plugin-scorecard-common@2.3.3
|
|
21
|
+
- @red-hat-developer-hub/backstage-plugin-scorecard-node@2.3.3
|
|
22
|
+
|
|
3
23
|
## 2.3.2
|
|
4
24
|
|
|
5
25
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -107,10 +107,10 @@ Returns a list of available metrics. Supports filtering by metric IDs or datasou
|
|
|
107
107
|
|
|
108
108
|
#### Query Parameters
|
|
109
109
|
|
|
110
|
-
| Parameter | Type | Required | Description
|
|
111
|
-
| ------------ | ------ | -------- |
|
|
112
|
-
| `metricIds` | string | No | Comma-separated list of metric IDs to filter by (e.g., `github.open_prs,
|
|
113
|
-
| `datasource` | string | No | Filter metrics by datasource ID (e.g., `github`, `jira`, `sonar`)
|
|
110
|
+
| Parameter | Type | Required | Description |
|
|
111
|
+
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------ |
|
|
112
|
+
| `metricIds` | string | No | Comma-separated list of metric IDs to filter by (e.g., `github.open_prs,jira.open_issues`) |
|
|
113
|
+
| `datasource` | string | No | Filter metrics by datasource ID (e.g., `github`, `jira`, `sonar`) |
|
|
114
114
|
|
|
115
115
|
#### Behavior
|
|
116
116
|
|
|
@@ -127,7 +127,7 @@ curl -X GET "{{url}}/api/scorecard/metrics" \
|
|
|
127
127
|
-H "Authorization: Bearer <token>"
|
|
128
128
|
|
|
129
129
|
# Get specific metrics by IDs
|
|
130
|
-
curl -X GET "{{url}}/api/scorecard/metrics?metricIds=github.open_prs,
|
|
130
|
+
curl -X GET "{{url}}/api/scorecard/metrics?metricIds=github.open_prs,jira.open_issues" \
|
|
131
131
|
-H "Authorization: Bearer <token>"
|
|
132
132
|
|
|
133
133
|
# Get all metrics from a specific datasource
|
|
@@ -149,9 +149,9 @@ Returns the latest metric values for a specific catalog entity.
|
|
|
149
149
|
|
|
150
150
|
#### Query Parameters
|
|
151
151
|
|
|
152
|
-
| Parameter | Type | Required | Description
|
|
153
|
-
| ----------- | ------ | -------- |
|
|
154
|
-
| `metricIds` | string | No | Comma-separated list of metric IDs to filter by (e.g., `github.open_prs,
|
|
152
|
+
| Parameter | Type | Required | Description |
|
|
153
|
+
| ----------- | ------ | -------- | ------------------------------------------------------------------------------------------ |
|
|
154
|
+
| `metricIds` | string | No | Comma-separated list of metric IDs to filter by (e.g., `github.open_prs,jira.open_issues`) |
|
|
155
155
|
|
|
156
156
|
#### Permissions
|
|
157
157
|
|
|
@@ -9,6 +9,9 @@ class DatabaseMetricValues {
|
|
|
9
9
|
* Insert multiple metric values
|
|
10
10
|
*/
|
|
11
11
|
async createMetricValues(metricValues) {
|
|
12
|
+
if (metricValues.length === 0) {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
12
15
|
await this.dbClient(this.tableName).insert(metricValues);
|
|
13
16
|
}
|
|
14
17
|
/**
|
|
@@ -29,9 +32,9 @@ class DatabaseMetricValues {
|
|
|
29
32
|
/**
|
|
30
33
|
* Get aggregated metrics by status for multiple entities and metrics.
|
|
31
34
|
*/
|
|
32
|
-
async
|
|
33
|
-
const latestIdsSubquery = this.dbClient(this.tableName).max("id").
|
|
34
|
-
const
|
|
35
|
+
async readAggregatedMetricByEntityRefs(catalog_entity_refs, metric_id) {
|
|
36
|
+
const latestIdsSubquery = this.dbClient(this.tableName).max("id").where("metric_id", metric_id).whereIn("catalog_entity_ref", catalog_entity_refs).groupBy("metric_id", "catalog_entity_ref");
|
|
37
|
+
const [row] = await this.dbClient(this.tableName).select("metric_id").count("* as total").max("timestamp as max_timestamp").select(
|
|
35
38
|
this.dbClient.raw(
|
|
36
39
|
"SUM(CASE WHEN status = 'success' AND value IS NOT NULL THEN 1 ELSE 0 END) as success"
|
|
37
40
|
)
|
|
@@ -44,7 +47,7 @@ class DatabaseMetricValues {
|
|
|
44
47
|
"SUM(CASE WHEN status = 'error' AND value IS NOT NULL THEN 1 ELSE 0 END) as error"
|
|
45
48
|
)
|
|
46
49
|
).whereIn("id", latestIdsSubquery).whereNotNull("status").whereNotNull("value").groupBy("metric_id");
|
|
47
|
-
|
|
50
|
+
if (row) {
|
|
48
51
|
let maxTimestamp;
|
|
49
52
|
if (row.max_timestamp instanceof Date) {
|
|
50
53
|
maxTimestamp = row.max_timestamp;
|
|
@@ -61,7 +64,8 @@ class DatabaseMetricValues {
|
|
|
61
64
|
warning: Number(row.warning),
|
|
62
65
|
error: Number(row.error)
|
|
63
66
|
};
|
|
64
|
-
}
|
|
67
|
+
}
|
|
68
|
+
return void 0;
|
|
65
69
|
}
|
|
66
70
|
}
|
|
67
71
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatabaseMetricValues.cjs.js","sources":["../../src/database/DatabaseMetricValues.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 { Knex } from 'knex';\nimport {\n DbMetricValueCreate,\n DbMetricValue,\n DbAggregatedMetric,\n} from './types';\n\nexport class DatabaseMetricValues {\n private readonly tableName = 'metric_values';\n\n constructor(private readonly dbClient: Knex<any, any[]>) {}\n\n /**\n * Insert multiple metric values\n */\n async createMetricValues(metricValues: DbMetricValueCreate[]): Promise<void> {\n await this.dbClient(this.tableName).insert(metricValues);\n }\n\n /**\n * Get the latest metric values for a specific entity and metrics\n */\n async readLatestEntityMetricValues(\n catalog_entity_ref: string,\n metric_ids: string[],\n ): Promise<DbMetricValue[]> {\n return await this.dbClient(this.tableName)\n .select('*')\n .whereIn(\n 'id',\n this.dbClient(this.tableName)\n .max('id')\n .whereIn('metric_id', metric_ids)\n .where('catalog_entity_ref', catalog_entity_ref)\n .groupBy('metric_id'),\n );\n }\n\n /**\n * Delete metric values that are older than the given date\n */\n async cleanupExpiredMetrics(olderThan: Date): Promise<number> {\n return await this.dbClient(this.tableName)\n .where('timestamp', '<', olderThan)\n .del();\n }\n\n /**\n * Get aggregated metrics by status for multiple entities and metrics.\n */\n async
|
|
1
|
+
{"version":3,"file":"DatabaseMetricValues.cjs.js","sources":["../../src/database/DatabaseMetricValues.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 { Knex } from 'knex';\nimport {\n DbMetricValueCreate,\n DbMetricValue,\n DbAggregatedMetric,\n} from './types';\n\nexport class DatabaseMetricValues {\n private readonly tableName = 'metric_values';\n\n constructor(private readonly dbClient: Knex<any, any[]>) {}\n\n /**\n * Insert multiple metric values\n */\n async createMetricValues(metricValues: DbMetricValueCreate[]): Promise<void> {\n if (metricValues.length === 0) {\n return;\n }\n await this.dbClient(this.tableName).insert(metricValues);\n }\n\n /**\n * Get the latest metric values for a specific entity and metrics\n */\n async readLatestEntityMetricValues(\n catalog_entity_ref: string,\n metric_ids: string[],\n ): Promise<DbMetricValue[]> {\n return await this.dbClient(this.tableName)\n .select('*')\n .whereIn(\n 'id',\n this.dbClient(this.tableName)\n .max('id')\n .whereIn('metric_id', metric_ids)\n .where('catalog_entity_ref', catalog_entity_ref)\n .groupBy('metric_id'),\n );\n }\n\n /**\n * Delete metric values that are older than the given date\n */\n async cleanupExpiredMetrics(olderThan: Date): Promise<number> {\n return await this.dbClient(this.tableName)\n .where('timestamp', '<', olderThan)\n .del();\n }\n\n /**\n * Get aggregated metrics by status for multiple entities and metrics.\n */\n async readAggregatedMetricByEntityRefs(\n catalog_entity_refs: string[],\n metric_id: string,\n ): Promise<DbAggregatedMetric | undefined> {\n const latestIdsSubquery = this.dbClient(this.tableName)\n .max('id')\n .where('metric_id', metric_id)\n .whereIn('catalog_entity_ref', catalog_entity_refs)\n .groupBy('metric_id', 'catalog_entity_ref');\n\n const [row] = await this.dbClient(this.tableName)\n .select('metric_id')\n .count('* as total')\n .max('timestamp as max_timestamp')\n .select(\n this.dbClient.raw(\n \"SUM(CASE WHEN status = 'success' AND value IS NOT NULL THEN 1 ELSE 0 END) as success\",\n ),\n )\n .select(\n this.dbClient.raw(\n \"SUM(CASE WHEN status = 'warning' AND value IS NOT NULL THEN 1 ELSE 0 END) as warning\",\n ),\n )\n .select(\n this.dbClient.raw(\n \"SUM(CASE WHEN status = 'error' AND value IS NOT NULL THEN 1 ELSE 0 END) as error\",\n ),\n )\n .whereIn('id', latestIdsSubquery)\n .whereNotNull('status')\n .whereNotNull('value')\n .groupBy('metric_id');\n\n // Normalize types for cross-database compatibility\n // PostgreSQL returns COUNT/SUM as strings, SQLite returns numbers\n // PostgreSQL returns MAX(timestamp) as Date, SQLite returns number (milliseconds)\n if (row) {\n let maxTimestamp: Date;\n if (row.max_timestamp instanceof Date) {\n maxTimestamp = row.max_timestamp;\n } else if (\n typeof row.max_timestamp === 'number' ||\n typeof row.max_timestamp === 'string'\n ) {\n maxTimestamp = new Date(row.max_timestamp as string | number);\n } else {\n maxTimestamp = new Date();\n }\n\n return {\n metric_id: row.metric_id,\n total: Number(row.total),\n max_timestamp: maxTimestamp,\n success: Number(row.success),\n warning: Number(row.warning),\n error: Number(row.error),\n };\n }\n\n return undefined;\n }\n}\n"],"names":[],"mappings":";;AAuBO,MAAM,oBAAqB,CAAA;AAAA,EAGhC,YAA6B,QAA4B,EAAA;AAA5B,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA;AAA6B,EAFzC,SAAY,GAAA,eAAA;AAAA;AAAA;AAAA;AAAA,EAO7B,MAAM,mBAAmB,YAAoD,EAAA;AAC3E,IAAI,IAAA,YAAA,CAAa,WAAW,CAAG,EAAA;AAC7B,MAAA;AAAA;AAEF,IAAA,MAAM,KAAK,QAAS,CAAA,IAAA,CAAK,SAAS,CAAA,CAAE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Z;AAAA;AACF,KAED,CAAA,MAAA;AAAA,MACC,KAAK,QAAS,CAAA,GAAA;AAAA,QACZ;AAAA;AACF,KAED,CAAA,OAAA,CAAQ,IAAM,EAAA,iBAAiB,CAC/B,CAAA,YAAA,CAAa,QAAQ,CAAA,CACrB,YAAa,CAAA,OAAO,CACpB,CAAA,OAAA,CAAQ,WAAW,CAAA;AAKtB,IAAA,IAAI,GAAK,EAAA;AACP,MAAI,IAAA,YAAA;AACJ,MAAI,IAAA,GAAA,CAAI,yBAAyB,IAAM,EAAA;AACrC,QAAA,YAAA,GAAe,GAAI,CAAA,aAAA;AAAA,OACrB,MAAA,IACE,OAAO,GAAI,CAAA,aAAA,KAAkB,YAC7B,OAAO,GAAA,CAAI,kBAAkB,QAC7B,EAAA;AACA,QAAe,YAAA,GAAA,IAAI,IAAK,CAAA,GAAA,CAAI,aAAgC,CAAA;AAAA,OACvD,MAAA;AACL,QAAA,YAAA,uBAAmB,IAAK,EAAA;AAAA;AAG1B,MAAO,OAAA;AAAA,QACL,WAAW,GAAI,CAAA,SAAA;AAAA,QACf,KAAA,EAAO,MAAO,CAAA,GAAA,CAAI,KAAK,CAAA;AAAA,QACvB,aAAe,EAAA,YAAA;AAAA,QACf,OAAA,EAAS,MAAO,CAAA,GAAA,CAAI,OAAO,CAAA;AAAA,QAC3B,OAAA,EAAS,MAAO,CAAA,GAAA,CAAI,OAAO,CAAA;AAAA,QAC3B,KAAA,EAAO,MAAO,CAAA,GAAA,CAAI,KAAK;AAAA,OACzB;AAAA;AAGF,IAAO,OAAA,MAAA;AAAA;AAEX;;;;"}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
var errors = require('@backstage/errors');
|
|
4
4
|
var permissionUtils = require('../permissions/permissionUtils.cjs.js');
|
|
5
5
|
var mergeEntityAndProviderThresholds = require('../utils/mergeEntityAndProviderThresholds.cjs.js');
|
|
6
|
+
var mappers = require('./mappers.cjs.js');
|
|
6
7
|
|
|
7
8
|
class CatalogMetricService {
|
|
8
9
|
catalog;
|
|
@@ -84,52 +85,21 @@ class CatalogMetricService {
|
|
|
84
85
|
);
|
|
85
86
|
}
|
|
86
87
|
/**
|
|
87
|
-
* Get aggregated
|
|
88
|
+
* Get an aggregated metric for multiple entities and a single metric ID.
|
|
88
89
|
*
|
|
89
90
|
* @param entityRefs - Array of entity references in format "kind:namespace/name"
|
|
90
|
-
* @param
|
|
91
|
-
* If not provided, gets all available aggregated metrics.
|
|
91
|
+
* @param metricId - Metric ID to aggregate.
|
|
92
92
|
* @returns Aggregated metric results
|
|
93
93
|
*/
|
|
94
|
-
async
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
);
|
|
104
|
-
return aggregatedMetrics.map((row) => {
|
|
105
|
-
const metricId = row.metric_id;
|
|
106
|
-
const success = row.success || 0;
|
|
107
|
-
const warning = row.warning || 0;
|
|
108
|
-
const error = row.error || 0;
|
|
109
|
-
const total = row.total || 0;
|
|
110
|
-
const timestamp = row.max_timestamp ? new Date(row.max_timestamp).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
|
|
111
|
-
const provider = this.registry.getProvider(metricId);
|
|
112
|
-
const metric = provider.getMetric();
|
|
113
|
-
return {
|
|
114
|
-
id: metricId,
|
|
115
|
-
status: "success",
|
|
116
|
-
metadata: {
|
|
117
|
-
title: metric.title,
|
|
118
|
-
description: metric.description,
|
|
119
|
-
type: metric.type,
|
|
120
|
-
history: metric.history
|
|
121
|
-
},
|
|
122
|
-
result: {
|
|
123
|
-
values: [
|
|
124
|
-
{ count: success, name: "success" },
|
|
125
|
-
{ count: warning, name: "warning" },
|
|
126
|
-
{ count: error, name: "error" }
|
|
127
|
-
],
|
|
128
|
-
total,
|
|
129
|
-
timestamp
|
|
130
|
-
}
|
|
131
|
-
};
|
|
132
|
-
});
|
|
94
|
+
async getAggregatedMetricByEntityRefs(entityRefs, metricId) {
|
|
95
|
+
if (entityRefs.length !== 0) {
|
|
96
|
+
const aggregatedMetric = await this.database.readAggregatedMetricByEntityRefs(
|
|
97
|
+
entityRefs,
|
|
98
|
+
metricId
|
|
99
|
+
);
|
|
100
|
+
return mappers.AggregatedMetricMapper.toAggregatedMetric(aggregatedMetric);
|
|
101
|
+
}
|
|
102
|
+
return mappers.AggregatedMetricMapper.toAggregatedMetric();
|
|
133
103
|
}
|
|
134
104
|
}
|
|
135
105
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CatalogMetricService.cjs.js","sources":["../../src/service/CatalogMetricService.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 AggregatedMetricResult,\n MetricResult,\n ThresholdConfig,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\nimport { MetricProvidersRegistry } from '../providers/MetricProvidersRegistry';\nimport { NotFoundError, stringifyError } from '@backstage/errors';\nimport { AuthService } from '@backstage/backend-plugin-api';\nimport { filterAuthorizedMetrics } from '../permissions/permissionUtils';\nimport {\n PermissionCondition,\n PermissionCriteria,\n PermissionRuleParams,\n} from '@backstage/plugin-permission-common';\nimport { CatalogService } from '@backstage/plugin-catalog-node';\nimport { DatabaseMetricValues } from '../database/DatabaseMetricValues';\nimport { mergeEntityAndProviderThresholds } from '../utils/mergeEntityAndProviderThresholds';\n\ntype CatalogMetricServiceOptions = {\n catalog: CatalogService;\n auth: AuthService;\n registry: MetricProvidersRegistry;\n database: DatabaseMetricValues;\n};\n\nexport type AggregatedMetricsByStatus = Record<\n string,\n { values: { success: number; warning: number; error: number }; total: number }\n>;\n\nexport class CatalogMetricService {\n private readonly catalog: CatalogService;\n private readonly auth: AuthService;\n private readonly registry: MetricProvidersRegistry;\n private readonly database: DatabaseMetricValues;\n\n constructor(options: CatalogMetricServiceOptions) {\n this.catalog = options.catalog;\n this.auth = options.auth;\n this.registry = options.registry;\n this.database = options.database;\n }\n\n /**\n * Get latest metric results for a specific catalog entity and metric providers.\n *\n * @param entityRef - Entity reference in format \"kind:namespace/name\"\n * @param providerIds - Optional array of provider IDs to get latest metrics of.\n * If not provided, gets all available latest metrics.\n * @param filter - Permission filter\n * @returns Metric results with entity-specific thresholds applied\n */\n async getLatestEntityMetrics(\n entityRef: string,\n providerIds?: string[],\n filter?: PermissionCriteria<\n PermissionCondition<string, PermissionRuleParams>\n >,\n ): Promise<MetricResult[]> {\n const entity = await this.catalog.getEntityByRef(entityRef, {\n credentials: await this.auth.getOwnServiceCredentials(),\n });\n if (!entity) {\n throw new NotFoundError(`Entity not found: ${entityRef}`);\n }\n\n const metricsToFetch = this.registry.listMetrics(providerIds);\n\n const authorizedMetricsToFetch = filterAuthorizedMetrics(\n metricsToFetch,\n filter,\n );\n const rawResults = await this.database.readLatestEntityMetricValues(\n entityRef,\n authorizedMetricsToFetch.map(m => m.id),\n );\n\n return rawResults.map(\n ({ metric_id, value, error_message, timestamp, status }) => {\n let thresholds: ThresholdConfig | undefined;\n let thresholdError: string | undefined;\n\n const provider = this.registry.getProvider(metric_id);\n const metric = provider.getMetric();\n\n try {\n thresholds = mergeEntityAndProviderThresholds(entity, provider);\n\n if (value === null) {\n thresholdError =\n 'Unable to evaluate thresholds, metric value is missing';\n } else if (error_message) {\n thresholdError = error_message;\n }\n } catch (error) {\n thresholdError = stringifyError(error);\n }\n\n const isMetricCalcError = error_message !== null && value === null;\n\n return {\n id: metric.id,\n status: isMetricCalcError ? 'error' : 'success',\n metadata: {\n title: metric.title,\n description: metric.description,\n type: metric.type,\n history: metric.history,\n },\n ...(isMetricCalcError && {\n error:\n error_message ??\n stringifyError(new Error(`Metric value is 'undefined'`)),\n }),\n result: {\n value,\n timestamp: new Date(timestamp).toISOString(),\n thresholdResult: {\n definition: thresholds,\n status: thresholdError ? 'error' : 'success',\n evaluation: status,\n ...(thresholdError && { error: thresholdError }),\n },\n },\n };\n },\n );\n }\n\n /**\n * Get aggregated metrics for multiple entities and metrics\n *\n * @param entityRefs - Array of entity references in format \"kind:namespace/name\"\n * @param metricIds - Optional array of metric IDs to get aggregated metrics of.\n * If not provided, gets all available aggregated metrics.\n * @returns Aggregated metric results\n */\n async getAggregatedMetricsByEntityRefs(\n entityRefs: string[],\n metricIds?: string[],\n filter?: PermissionCriteria<\n PermissionCondition<string, PermissionRuleParams>\n >,\n ): Promise<AggregatedMetricResult[]> {\n const metricsToFetch = this.registry.listMetrics(metricIds);\n\n const authorizedMetricsToFetch = filterAuthorizedMetrics(\n metricsToFetch,\n filter,\n );\n\n const aggregatedMetrics =\n await this.database.readAggregatedMetricsByEntityRefs(\n entityRefs,\n authorizedMetricsToFetch.map(m => m.id),\n );\n\n return aggregatedMetrics.map(row => {\n const metricId = row.metric_id;\n const success = row.success || 0;\n const warning = row.warning || 0;\n const error = row.error || 0;\n const total = row.total || 0;\n const timestamp = row.max_timestamp\n ? new Date(row.max_timestamp).toISOString()\n : new Date().toISOString();\n\n const provider = this.registry.getProvider(metricId);\n const metric = provider.getMetric();\n\n return {\n id: metricId,\n status: 'success',\n metadata: {\n title: metric.title,\n description: metric.description,\n type: metric.type,\n history: metric.history,\n },\n result: {\n values: [\n { count: success, name: 'success' },\n { count: warning, name: 'warning' },\n { count: error, name: 'error' },\n ],\n total,\n timestamp,\n },\n };\n });\n }\n}\n"],"names":["NotFoundError","filterAuthorizedMetrics","mergeEntityAndProviderThresholds","stringifyError"],"mappings":";;;;;;AA8CO,MAAM,oBAAqB,CAAA;AAAA,EACf,OAAA;AAAA,EACA,IAAA;AAAA,EACA,QAAA;AAAA,EACA,QAAA;AAAA,EAEjB,YAAY,OAA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,YACN,EAAE,KAAA,EAAO,OAAS,EAAA,IAAA,EAAM,SAAU,EAAA;AAAA,YAClC,EAAE,KAAA,EAAO,OAAS,EAAA,IAAA,EAAM,SAAU,EAAA;AAAA,YAClC,EAAE,KAAA,EAAO,KAAO,EAAA,IAAA,EAAM,OAAQ;AAAA,WAChC;AAAA,UACA,KAAA;AAAA,UACA;AAAA;AACF,OACF;AAAA,KACD,CAAA;AAAA;AAEL;;;;"}
|
|
1
|
+
{"version":3,"file":"CatalogMetricService.cjs.js","sources":["../../src/service/CatalogMetricService.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 MetricResult,\n ThresholdConfig,\n AggregatedMetric,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\nimport { MetricProvidersRegistry } from '../providers/MetricProvidersRegistry';\nimport { NotFoundError, stringifyError } from '@backstage/errors';\nimport { AuthService } from '@backstage/backend-plugin-api';\nimport { filterAuthorizedMetrics } from '../permissions/permissionUtils';\nimport {\n PermissionCondition,\n PermissionCriteria,\n PermissionRuleParams,\n} from '@backstage/plugin-permission-common';\nimport { CatalogService } from '@backstage/plugin-catalog-node';\nimport { DatabaseMetricValues } from '../database/DatabaseMetricValues';\nimport { mergeEntityAndProviderThresholds } from '../utils/mergeEntityAndProviderThresholds';\nimport { AggregatedMetricMapper } from './mappers';\n\ntype CatalogMetricServiceOptions = {\n catalog: CatalogService;\n auth: AuthService;\n registry: MetricProvidersRegistry;\n database: DatabaseMetricValues;\n};\n\nexport type AggregatedMetricsByStatus = Record<\n string,\n { values: { success: number; warning: number; error: number }; total: number }\n>;\n\nexport class CatalogMetricService {\n private readonly catalog: CatalogService;\n private readonly auth: AuthService;\n private readonly registry: MetricProvidersRegistry;\n private readonly database: DatabaseMetricValues;\n\n constructor(options: CatalogMetricServiceOptions) {\n this.catalog = options.catalog;\n this.auth = options.auth;\n this.registry = options.registry;\n this.database = options.database;\n }\n\n /**\n * Get latest metric results for a specific catalog entity and metric providers.\n *\n * @param entityRef - Entity reference in format \"kind:namespace/name\"\n * @param providerIds - Optional array of provider IDs to get latest metrics of.\n * If not provided, gets all available latest metrics.\n * @param filter - Permission filter\n * @returns Metric results with entity-specific thresholds applied\n */\n async getLatestEntityMetrics(\n entityRef: string,\n providerIds?: string[],\n filter?: PermissionCriteria<\n PermissionCondition<string, PermissionRuleParams>\n >,\n ): Promise<MetricResult[]> {\n const entity = await this.catalog.getEntityByRef(entityRef, {\n credentials: await this.auth.getOwnServiceCredentials(),\n });\n if (!entity) {\n throw new NotFoundError(`Entity not found: ${entityRef}`);\n }\n\n const metricsToFetch = this.registry.listMetrics(providerIds);\n\n const authorizedMetricsToFetch = filterAuthorizedMetrics(\n metricsToFetch,\n filter,\n );\n const rawResults = await this.database.readLatestEntityMetricValues(\n entityRef,\n authorizedMetricsToFetch.map(m => m.id),\n );\n\n return rawResults.map(\n ({ metric_id, value, error_message, timestamp, status }) => {\n let thresholds: ThresholdConfig | undefined;\n let thresholdError: string | undefined;\n\n const provider = this.registry.getProvider(metric_id);\n const metric = provider.getMetric();\n\n try {\n thresholds = mergeEntityAndProviderThresholds(entity, provider);\n\n if (value === null) {\n thresholdError =\n 'Unable to evaluate thresholds, metric value is missing';\n } else if (error_message) {\n thresholdError = error_message;\n }\n } catch (error) {\n thresholdError = stringifyError(error);\n }\n\n const isMetricCalcError = error_message !== null && value === null;\n\n return {\n id: metric.id,\n status: isMetricCalcError ? 'error' : 'success',\n metadata: {\n title: metric.title,\n description: metric.description,\n type: metric.type,\n history: metric.history,\n },\n ...(isMetricCalcError && {\n error:\n error_message ??\n stringifyError(new Error(`Metric value is 'undefined'`)),\n }),\n result: {\n value,\n timestamp: new Date(timestamp).toISOString(),\n thresholdResult: {\n definition: thresholds,\n status: thresholdError ? 'error' : 'success',\n evaluation: status,\n ...(thresholdError && { error: thresholdError }),\n },\n },\n };\n },\n );\n }\n\n /**\n * Get an aggregated metric for multiple entities and a single metric ID.\n *\n * @param entityRefs - Array of entity references in format \"kind:namespace/name\"\n * @param metricId - Metric ID to aggregate.\n * @returns Aggregated metric results\n */\n async getAggregatedMetricByEntityRefs(\n entityRefs: string[],\n metricId: string,\n ): Promise<AggregatedMetric> {\n if (entityRefs.length !== 0) {\n const aggregatedMetric =\n await this.database.readAggregatedMetricByEntityRefs(\n entityRefs,\n metricId,\n );\n\n return AggregatedMetricMapper.toAggregatedMetric(aggregatedMetric);\n }\n\n return AggregatedMetricMapper.toAggregatedMetric();\n }\n}\n"],"names":["NotFoundError","filterAuthorizedMetrics","mergeEntityAndProviderThresholds","stringifyError","AggregatedMetricMapper"],"mappings":";;;;;;;AA+CO,MAAM,oBAAqB,CAAA;AAAA,EACf,OAAA;AAAA,EACA,IAAA;AAAA,EACA,QAAA;AAAA,EACA,QAAA;AAAA,EAEjB,YAAY,OAAsC,EAAA;AAChD,IAAA,IAAA,CAAK,UAAU,OAAQ,CAAA,OAAA;AACvB,IAAA,IAAA,CAAK,OAAO,OAAQ,CAAA,IAAA;AACpB,IAAA,IAAA,CAAK,WAAW,OAAQ,CAAA,QAAA;AACxB,IAAA,IAAA,CAAK,WAAW,OAAQ,CAAA,QAAA;AAAA;AAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,sBAAA,CACJ,SACA,EAAA,WAAA,EACA,MAGyB,EAAA;AACzB,IAAA,MAAM,MAAS,GAAA,MAAM,IAAK,CAAA,OAAA,CAAQ,eAAe,SAAW,EAAA;AAAA,MAC1D,WAAa,EAAA,MAAM,IAAK,CAAA,IAAA,CAAK,wBAA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;AAAA,UACtC,QAAU,EAAA;AAAA,YACR,OAAO,MAAO,CAAA,KAAA;AAAA,YACd,aAAa,MAAO,CAAA,WAAA;AAAA,YACpB,MAAM,MAAO,CAAA,IAAA;AAAA,YACb,SAAS,MAAO,CAAA;AAAA,WAClB;AAAA,UACA,GAAI,iBAAqB,IAAA;AAAA,YACvB,OACE,aACA,IAAAA,qBAAA,CAAe,IAAI,KAAA,CAAM,6BAA6B,CAAC;AAAA,WAC3D;AAAA,UACA,MAAQ,EAAA;AAAA,YACN,KAAA;AAAA,YACA,SAAW,EAAA,IAAI,IAAK,CAAA,SAAS,EAAE,WAAY,EAAA;AAAA,YAC3C,eAAiB,EAAA;AAAA,cACf,UAAY,EAAA,UAAA;AAAA,cACZ,MAAA,EAAQ,iBAAiB,OAAU,GAAA,SAAA;AAAA,cACnC,UAAY,EAAA,MAAA;AAAA,cACZ,GAAI,cAAA,IAAkB,EAAE,KAAA,EAAO,cAAe;AAAA;AAChD;AACF,SACF;AAAA;AACF,KACF;AAAA;AACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,+BACJ,CAAA,UAAA,EACA,QAC2B,EAAA;AAC3B,IAAI,IAAA,UAAA,CAAW,WAAW,CAAG,EAAA;AAC3B,MAAM,MAAA,gBAAA,GACJ,MAAM,IAAA,CAAK,QAAS,CAAA,gCAAA;AAAA,QAClB,UAAA;AAAA,QACA;AAAA,OACF;AAEF,MAAO,OAAAC,8BAAA,CAAuB,mBAAmB,gBAAgB,CAAA;AAAA;AAGnE,IAAA,OAAOA,+BAAuB,kBAAmB,EAAA;AAAA;AAErD;;;;"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
class AggregatedMetricMapper {
|
|
4
|
+
static toAggregatedMetric(aggregatedMetric) {
|
|
5
|
+
const success = aggregatedMetric?.success ?? 0;
|
|
6
|
+
const warning = aggregatedMetric?.warning ?? 0;
|
|
7
|
+
const error = aggregatedMetric?.error ?? 0;
|
|
8
|
+
const total = aggregatedMetric?.total ?? 0;
|
|
9
|
+
const timestamp = aggregatedMetric?.max_timestamp ? new Date(aggregatedMetric.max_timestamp).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
|
|
10
|
+
return {
|
|
11
|
+
values: [
|
|
12
|
+
{ count: success, name: "success" },
|
|
13
|
+
{ count: warning, name: "warning" },
|
|
14
|
+
{ count: error, name: "error" }
|
|
15
|
+
],
|
|
16
|
+
total,
|
|
17
|
+
timestamp
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
static toAggregatedMetricResult(metric, aggregatedMetric) {
|
|
21
|
+
return {
|
|
22
|
+
id: metric.id,
|
|
23
|
+
status: "success",
|
|
24
|
+
metadata: {
|
|
25
|
+
title: metric.title,
|
|
26
|
+
description: metric.description,
|
|
27
|
+
type: metric.type,
|
|
28
|
+
history: metric.history
|
|
29
|
+
},
|
|
30
|
+
result: aggregatedMetric
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
exports.AggregatedMetricMapper = AggregatedMetricMapper;
|
|
36
|
+
//# sourceMappingURL=mappers.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mappers.cjs.js","sources":["../../src/service/mappers.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 AggregatedMetric,\n AggregatedMetricResult,\n Metric,\n} from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\nimport { DbAggregatedMetric } from '../database/types';\n\nexport class AggregatedMetricMapper {\n static toAggregatedMetric(\n aggregatedMetric?: DbAggregatedMetric,\n ): AggregatedMetric {\n const success = aggregatedMetric?.success ?? 0;\n const warning = aggregatedMetric?.warning ?? 0;\n const error = aggregatedMetric?.error ?? 0;\n const total = aggregatedMetric?.total ?? 0;\n const timestamp = aggregatedMetric?.max_timestamp\n ? new Date(aggregatedMetric.max_timestamp).toISOString()\n : new Date().toISOString();\n\n return {\n values: [\n { count: success, name: 'success' },\n { count: warning, name: 'warning' },\n { count: error, name: 'error' },\n ],\n total,\n timestamp,\n };\n }\n\n static toAggregatedMetricResult(\n metric: Metric,\n aggregatedMetric: AggregatedMetric,\n ): AggregatedMetricResult {\n return {\n id: metric.id,\n status: 'success',\n metadata: {\n title: metric.title,\n description: metric.description,\n type: metric.type,\n history: metric.history,\n },\n result: aggregatedMetric,\n };\n }\n}\n"],"names":[],"mappings":";;AAuBO,MAAM,sBAAuB,CAAA;AAAA,EAClC,OAAO,mBACL,gBACkB,EAAA;AAClB,IAAM,MAAA,OAAA,GAAU,kBAAkB,OAAW,IAAA,CAAA;AAC7C,IAAM,MAAA,OAAA,GAAU,kBAAkB,OAAW,IAAA,CAAA;AAC7C,IAAM,MAAA,KAAA,GAAQ,kBAAkB,KAAS,IAAA,CAAA;AACzC,IAAM,MAAA,KAAA,GAAQ,kBAAkB,KAAS,IAAA,CAAA;AACzC,IAAA,MAAM,SAAY,GAAA,gBAAA,EAAkB,aAChC,GAAA,IAAI,IAAK,CAAA,gBAAA,CAAiB,aAAa,CAAA,CAAE,WAAY,EAAA,GAAA,iBACjD,IAAA,IAAA,IAAO,WAAY,EAAA;AAE3B,IAAO,OAAA;AAAA,MACL,MAAQ,EAAA;AAAA,QACN,EAAE,KAAA,EAAO,OAAS,EAAA,IAAA,EAAM,SAAU,EAAA;AAAA,QAClC,EAAE,KAAA,EAAO,OAAS,EAAA,IAAA,EAAM,SAAU,EAAA;AAAA,QAClC,EAAE,KAAA,EAAO,KAAO,EAAA,IAAA,EAAM,OAAQ;AAAA,OAChC;AAAA,MACA,KAAA;AAAA,MACA;AAAA,KACF;AAAA;AACF,EAEA,OAAO,wBACL,CAAA,MAAA,EACA,gBACwB,EAAA;AACxB,IAAO,OAAA;AAAA,MACL,IAAI,MAAO,CAAA,EAAA;AAAA,MACX,MAAQ,EAAA,SAAA;AAAA,MACR,QAAU,EAAA;AAAA,QACR,OAAO,MAAO,CAAA,KAAA;AAAA,QACd,aAAa,MAAO,CAAA,WAAA;AAAA,QACpB,MAAM,MAAO,CAAA,IAAA;AAAA,QACb,SAAS,MAAO,CAAA;AAAA,OAClB;AAAA,MACA,MAAQ,EAAA;AAAA,KACV;AAAA;AAEJ;;;;"}
|
|
@@ -11,6 +11,7 @@ var validateCatalogMetricsSchema = require('../validation/validateCatalogMetrics
|
|
|
11
11
|
var getEntitiesOwnedByUser = require('../utils/getEntitiesOwnedByUser.cjs.js');
|
|
12
12
|
var parseCommaSeparatedString = require('../utils/parseCommaSeparatedString.cjs.js');
|
|
13
13
|
var validateMetricsSchema = require('../validation/validateMetricsSchema.cjs.js');
|
|
14
|
+
var mappers = require('./mappers.cjs.js');
|
|
14
15
|
|
|
15
16
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
16
17
|
|
|
@@ -98,25 +99,22 @@ async function createRouter({
|
|
|
98
99
|
const credentials = await httpAuth.credentials(req, { allow: ["user"] });
|
|
99
100
|
const userEntityRef = credentials?.principal?.userEntityRef;
|
|
100
101
|
if (!userEntityRef) {
|
|
101
|
-
throw new errors.
|
|
102
|
+
throw new errors.AuthenticationError("User entity reference not found");
|
|
102
103
|
}
|
|
103
104
|
const entitiesOwnedByAUser = await getEntitiesOwnedByUser.getEntitiesOwnedByUser(userEntityRef, {
|
|
104
105
|
catalog,
|
|
105
106
|
credentials
|
|
106
107
|
});
|
|
107
|
-
if (entitiesOwnedByAUser.length === 0) {
|
|
108
|
-
res.json([]);
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
108
|
for (const entityRef of entitiesOwnedByAUser) {
|
|
112
109
|
await permissionUtils.checkEntityAccess(entityRef, req, permissions, httpAuth);
|
|
113
110
|
}
|
|
114
|
-
const
|
|
111
|
+
const aggregatedMetric = await catalogMetricService.getAggregatedMetricByEntityRefs(
|
|
115
112
|
entitiesOwnedByAUser,
|
|
116
|
-
|
|
117
|
-
|
|
113
|
+
metricId
|
|
114
|
+
);
|
|
115
|
+
res.json(
|
|
116
|
+
mappers.AggregatedMetricMapper.toAggregatedMetricResult(metric, aggregatedMetric)
|
|
118
117
|
);
|
|
119
|
-
res.json(aggregatedMetrics);
|
|
120
118
|
});
|
|
121
119
|
return router;
|
|
122
120
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.cjs.js","sources":["../../src/service/router.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 */\nimport {
|
|
1
|
+
{"version":3,"file":"router.cjs.js","sources":["../../src/service/router.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 */\nimport {\n AuthenticationError,\n InputError,\n NotAllowedError,\n} from '@backstage/errors';\nimport express, { Request } from 'express';\nimport Router from 'express-promise-router';\nimport type { CatalogMetricService } from './CatalogMetricService';\nimport type { MetricProvidersRegistry } from '../providers/MetricProvidersRegistry';\nimport {\n type HttpAuthService,\n type PermissionsService,\n} from '@backstage/backend-plugin-api';\nimport type { CatalogService } from '@backstage/plugin-catalog-node';\nimport {\n AuthorizeResult,\n BasicPermission,\n PolicyDecision,\n ResourcePermission,\n} from '@backstage/plugin-permission-common';\nimport { scorecardMetricReadPermission } from '@red-hat-developer-hub/backstage-plugin-scorecard-common';\nimport {\n filterAuthorizedMetrics,\n checkEntityAccess,\n} from '../permissions/permissionUtils';\nimport { stringifyEntityRef } from '@backstage/catalog-model';\nimport { validateCatalogMetricsSchema } from '../validation/validateCatalogMetricsSchema';\nimport { getEntitiesOwnedByUser } from '../utils/getEntitiesOwnedByUser';\nimport { parseCommaSeparatedString } from '../utils/parseCommaSeparatedString';\nimport { validateMetricsSchema } from '../validation/validateMetricsSchema';\nimport { AggregatedMetricMapper } from './mappers';\n\nexport type ScorecardRouterOptions = {\n metricProvidersRegistry: MetricProvidersRegistry;\n catalogMetricService: CatalogMetricService;\n catalog: CatalogService;\n httpAuth: HttpAuthService;\n permissions: PermissionsService;\n};\n\nexport async function createRouter({\n metricProvidersRegistry,\n catalogMetricService,\n catalog,\n httpAuth,\n permissions,\n}: ScorecardRouterOptions): Promise<express.Router> {\n const router = Router();\n router.use(express.json());\n\n const authorizeConditional = async (\n request: Request,\n permission: ResourcePermission<'scorecard-metric'> | BasicPermission,\n ) => {\n const credentials = await httpAuth.credentials(request);\n let decision: PolicyDecision;\n\n if (permission.type === 'resource') {\n decision = (\n await permissions.authorizeConditional([{ permission }], {\n credentials,\n })\n )[0];\n } else {\n decision = (\n await permissions.authorize([{ permission }], {\n credentials,\n })\n )[0];\n }\n\n if (decision.result === AuthorizeResult.DENY) {\n throw new NotAllowedError(); // 403\n }\n\n return {\n decision,\n conditions:\n decision.result === AuthorizeResult.CONDITIONAL\n ? decision.conditions\n : undefined,\n };\n };\n\n router.get('/metrics', async (req, res) => {\n const { metricIds, datasource } = validateMetricsSchema(req.query);\n\n if (metricIds && datasource) {\n throw new InputError('Cannot filter by both metricIds and datasource');\n }\n\n if (metricIds) {\n return res.json({\n metrics: metricProvidersRegistry.listMetrics(\n parseCommaSeparatedString(metricIds),\n ),\n });\n }\n\n if (datasource) {\n return res.json({\n metrics: metricProvidersRegistry.listMetricsByDatasource(datasource),\n });\n }\n\n return res.json({ metrics: metricProvidersRegistry.listMetrics() });\n });\n\n router.get('/metrics/catalog/:kind/:namespace/:name', async (req, res) => {\n const { conditions } = await authorizeConditional(\n req,\n scorecardMetricReadPermission,\n );\n\n const { kind, namespace, name } = req.params;\n\n const { metricIds } = validateCatalogMetricsSchema(req.query);\n\n const entityRef = stringifyEntityRef({ kind, namespace, name });\n\n // Check if user has permission to read this specific catalog entity\n await checkEntityAccess(entityRef, req, permissions, httpAuth);\n\n const metricIdArray = metricIds\n ? parseCommaSeparatedString(metricIds)\n : undefined;\n\n const results = await catalogMetricService.getLatestEntityMetrics(\n entityRef,\n metricIdArray,\n conditions,\n );\n res.json(results);\n });\n\n router.get('/metrics/:metricId/catalog/aggregations', async (req, res) => {\n const { metricId } = req.params;\n\n const { conditions } = await authorizeConditional(\n req,\n scorecardMetricReadPermission,\n );\n\n const metric = metricProvidersRegistry.getMetric(metricId);\n const authorizedMetrics = filterAuthorizedMetrics([metric], conditions);\n\n if (authorizedMetrics.length === 0) {\n throw new NotAllowedError(\n `To view the scorecard metrics, your administrator must grant you the required permission.`,\n );\n }\n\n const credentials = await httpAuth.credentials(req, { allow: ['user'] });\n const userEntityRef = credentials?.principal?.userEntityRef;\n\n if (!userEntityRef) {\n throw new AuthenticationError('User entity reference not found');\n }\n\n const entitiesOwnedByAUser = await getEntitiesOwnedByUser(userEntityRef, {\n catalog,\n credentials,\n });\n\n for (const entityRef of entitiesOwnedByAUser) {\n await checkEntityAccess(entityRef, req, permissions, httpAuth);\n }\n\n const aggregatedMetric =\n await catalogMetricService.getAggregatedMetricByEntityRefs(\n entitiesOwnedByAUser,\n metricId,\n );\n\n res.json(\n AggregatedMetricMapper.toAggregatedMetricResult(metric, aggregatedMetric),\n );\n });\n\n return router;\n}\n"],"names":["Router","express","AuthorizeResult","NotAllowedError","validateMetricsSchema","InputError","parseCommaSeparatedString","scorecardMetricReadPermission","validateCatalogMetricsSchema","stringifyEntityRef","checkEntityAccess","filterAuthorizedMetrics","AuthenticationError","getEntitiesOwnedByUser","AggregatedMetricMapper"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuDA,eAAsB,YAAa,CAAA;AAAA,EACjC,uBAAA;AAAA,EACA,oBAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EACA;AACF,CAAoD,EAAA;AAClD,EAAA,MAAM,SAASA,uBAAO,EAAA;AACtB,EAAO,MAAA,CAAA,GAAA,CAAIC,wBAAQ,CAAA,IAAA,EAAM,CAAA;AAEzB,EAAM,MAAA,oBAAA,GAAuB,OAC3B,OAAA,EACA,UACG,KAAA;AACH,IAAA,MAAM,WAAc,GAAA,MAAM,QAAS,CAAA,WAAA,CAAY,OAAO,CAAA;AACtD,IAAI,IAAA,QAAA;AAEJ,IAAI,IAAA,UAAA,CAAW,SAAS,UAAY,EAAA;AAClC,MAAA,QAAA,GAAA,CACE,MAAM,WAAY,CAAA,oBAAA,CAAqB,CAAC,EAAE,UAAA,EAAY,CAAG,EAAA;AAAA,QACvD;AAAA,OACD,GACD,CAAC,CAAA;AAAA,KACE,MAAA;AACL,MAAA,QAAA,GAAA,CACE,MAAM,WAAY,CAAA,SAAA,CAAU,CAAC,EAAE,UAAA,EAAY,CAAG,EAAA;AAAA,QAC5C;AAAA,OACD,GACD,CAAC,CAAA;AAAA;AAGL,IAAI,IAAA,QAAA,CAAS,MAAW,KAAAC,sCAAA,CAAgB,IAAM,EAAA;AAC5C,MAAA,MAAM,IAAIC,sBAAgB,EAAA;AAAA;AAG5B,IAAO,OAAA;AAAA,MACL,QAAA;AAAA,MACA,YACE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A,MAAMH,iCAAkB,CAAA,SAAA,EAAW,GAAK,EAAA,WAAA,EAAa,QAAQ,CAAA;AAAA;AAG/D,IAAM,MAAA,gBAAA,GACJ,MAAM,oBAAqB,CAAA,+BAAA;AAAA,MACzB,oBAAA;AAAA,MACA;AAAA,KACF;AAEF,IAAI,GAAA,CAAA,IAAA;AAAA,MACFI,8BAAA,CAAuB,wBAAyB,CAAA,MAAA,EAAQ,gBAAgB;AAAA,KAC1E;AAAA,GACD,CAAA;AAED,EAAO,OAAA,MAAA;AACT;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@red-hat-developer-hub/backstage-plugin-scorecard-backend",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.4",
|
|
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": "^1.20.0",
|
|
48
48
|
"@backstage/plugin-permission-common": "^0.9.3",
|
|
49
49
|
"@backstage/plugin-permission-node": "^0.10.6",
|
|
50
|
-
"@red-hat-developer-hub/backstage-plugin-scorecard-common": "^2.3.
|
|
51
|
-
"@red-hat-developer-hub/backstage-plugin-scorecard-node": "^2.3.
|
|
50
|
+
"@red-hat-developer-hub/backstage-plugin-scorecard-common": "^2.3.4",
|
|
51
|
+
"@red-hat-developer-hub/backstage-plugin-scorecard-node": "^2.3.4",
|
|
52
52
|
"express": "^4.17.1",
|
|
53
53
|
"express-promise-router": "^4.1.0",
|
|
54
54
|
"knex": "^3.1.0",
|