From f39517304b436d68713c8639efa3fcb88ff6fd97 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 29 Jan 2025 14:53:26 +0000 Subject: [PATCH 01/18] Update dependency @tanstack/react-virtual to v3.11.3 (#99746) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- yarn.lock | 293 ++++-------------------------------------------------- 1 file changed, 18 insertions(+), 275 deletions(-) diff --git a/yarn.lock b/yarn.lock index f3824f36967..1bc54e8d8a4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -254,14 +254,7 @@ __metadata: languageName: node linkType: hard -"@babel/helper-plugin-utils@npm:^7.0.0, @babel/helper-plugin-utils@npm:^7.10.4, @babel/helper-plugin-utils@npm:^7.12.13, @babel/helper-plugin-utils@npm:^7.14.5, @babel/helper-plugin-utils@npm:^7.18.6, @babel/helper-plugin-utils@npm:^7.18.9, @babel/helper-plugin-utils@npm:^7.22.5, @babel/helper-plugin-utils@npm:^7.24.7, @babel/helper-plugin-utils@npm:^7.25.9, @babel/helper-plugin-utils@npm:^7.8.0, @babel/helper-plugin-utils@npm:^7.8.3": - version: 7.25.9 - resolution: "@babel/helper-plugin-utils@npm:7.25.9" - checksum: 10/e347d87728b1ab10b6976d46403941c8f9008c045ea6d99997a7ffca7b852dc34b6171380f7b17edf94410e0857ff26f3a53d8618f11d73744db86e8ca9b8c64 - languageName: node - linkType: hard - -"@babel/helper-plugin-utils@npm:^7.26.5": +"@babel/helper-plugin-utils@npm:^7.0.0, @babel/helper-plugin-utils@npm:^7.10.4, @babel/helper-plugin-utils@npm:^7.12.13, @babel/helper-plugin-utils@npm:^7.14.5, @babel/helper-plugin-utils@npm:^7.18.6, @babel/helper-plugin-utils@npm:^7.18.9, @babel/helper-plugin-utils@npm:^7.22.5, @babel/helper-plugin-utils@npm:^7.24.7, @babel/helper-plugin-utils@npm:^7.25.9, @babel/helper-plugin-utils@npm:^7.26.5, @babel/helper-plugin-utils@npm:^7.8.0, @babel/helper-plugin-utils@npm:^7.8.3": version: 7.26.5 resolution: "@babel/helper-plugin-utils@npm:7.26.5" checksum: 10/1cc0fd8514da3bb249bed6c27227696ab5e84289749d7258098701cffc0c599b7f61ec40dd332f8613030564b79899d9826813c96f966330bcfc7145a8377857 @@ -7984,7 +7977,7 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-ast@npm:^1.0.0-beta.11": +"@swagger-api/apidom-ast@npm:^1.0.0-beta.11, @swagger-api/apidom-ast@npm:^1.0.0-beta.5": version: 1.0.0-beta.11 resolution: "@swagger-api/apidom-ast@npm:1.0.0-beta.11" dependencies: @@ -7998,21 +7991,7 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-ast@npm:^1.0.0-beta.5": - version: 1.0.0-beta.5 - resolution: "@swagger-api/apidom-ast@npm:1.0.0-beta.5" - dependencies: - "@babel/runtime-corejs3": "npm:^7.20.7" - "@swagger-api/apidom-error": "npm:^1.0.0-beta.5" - "@types/ramda": "npm:~0.30.0" - ramda: "npm:~0.30.0" - ramda-adjunct: "npm:^5.0.0" - unraw: "npm:^3.0.0" - checksum: 10/b2ea32b8ed589a3aff122e9209d5f0c873364bb34b234d13796422d4fce6b9f52fab599ef47956f655316256cf6af821c233117c0ca96a677b867e075b70cb5d - languageName: node - linkType: hard - -"@swagger-api/apidom-core@npm:>=1.0.0-beta.11 <1.0.0-rc.0, @swagger-api/apidom-core@npm:^1.0.0-beta.11": +"@swagger-api/apidom-core@npm:>=1.0.0-beta.11 <1.0.0-rc.0, @swagger-api/apidom-core@npm:^1.0.0-beta.11, @swagger-api/apidom-core@npm:^1.0.0-beta.5": version: 1.0.0-beta.11 resolution: "@swagger-api/apidom-core@npm:1.0.0-beta.11" dependencies: @@ -8029,24 +8008,7 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-core@npm:^1.0.0-beta.5": - version: 1.0.0-beta.5 - resolution: "@swagger-api/apidom-core@npm:1.0.0-beta.5" - dependencies: - "@babel/runtime-corejs3": "npm:^7.20.7" - "@swagger-api/apidom-ast": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-error": "npm:^1.0.0-beta.5" - "@types/ramda": "npm:~0.30.0" - minim: "npm:~0.23.8" - ramda: "npm:~0.30.0" - ramda-adjunct: "npm:^5.0.0" - short-unique-id: "npm:^5.0.2" - ts-mixer: "npm:^6.0.3" - checksum: 10/c034ef286738b2b5aab525b068fd22e1b54145e3024477abcafde926f3783c280c69e4de23cc28d9cc568a62fb02719a0a89e6fd2011136cf447f42ed66fca55 - languageName: node - linkType: hard - -"@swagger-api/apidom-error@npm:>=1.0.0-beta.11 <1.0.0-rc.0, @swagger-api/apidom-error@npm:^1.0.0-beta.11": +"@swagger-api/apidom-error@npm:>=1.0.0-beta.11 <1.0.0-rc.0, @swagger-api/apidom-error@npm:^1.0.0-beta.11, @swagger-api/apidom-error@npm:^1.0.0-beta.3 <1.0.0-rc.0, @swagger-api/apidom-error@npm:^1.0.0-beta.5": version: 1.0.0-beta.11 resolution: "@swagger-api/apidom-error@npm:1.0.0-beta.11" dependencies: @@ -8055,16 +8017,7 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-error@npm:^1.0.0-beta.3 <1.0.0-rc.0, @swagger-api/apidom-error@npm:^1.0.0-beta.5": - version: 1.0.0-beta.5 - resolution: "@swagger-api/apidom-error@npm:1.0.0-beta.5" - dependencies: - "@babel/runtime-corejs3": "npm:^7.20.7" - checksum: 10/defb3ba3775be8a511ff01be4ed7d2eca66faf5ab478f65a39845c8981510a0286e622268240de56613fd3ee37de906a7c6947a82aceb214fdd89d0988b972bb - languageName: node - linkType: hard - -"@swagger-api/apidom-json-pointer@npm:>=1.0.0-beta.11 <1.0.0-rc.0, @swagger-api/apidom-json-pointer@npm:^1.0.0-beta.11": +"@swagger-api/apidom-json-pointer@npm:>=1.0.0-beta.11 <1.0.0-rc.0, @swagger-api/apidom-json-pointer@npm:^1.0.0-beta.11, @swagger-api/apidom-json-pointer@npm:^1.0.0-beta.3 <1.0.0-rc.0": version: 1.0.0-beta.11 resolution: "@swagger-api/apidom-json-pointer@npm:1.0.0-beta.11" dependencies: @@ -8078,20 +8031,6 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-json-pointer@npm:^1.0.0-beta.3 <1.0.0-rc.0, @swagger-api/apidom-json-pointer@npm:^1.0.0-beta.5": - version: 1.0.0-beta.5 - resolution: "@swagger-api/apidom-json-pointer@npm:1.0.0-beta.5" - dependencies: - "@babel/runtime-corejs3": "npm:^7.20.7" - "@swagger-api/apidom-core": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-error": "npm:^1.0.0-beta.5" - "@types/ramda": "npm:~0.30.0" - ramda: "npm:~0.30.0" - ramda-adjunct: "npm:^5.0.0" - checksum: 10/68b3b196de1d2cb86663350ba70f885599a12c21804cd9bc1be1777ee5e99e9f570623599d476d241bda298e0890c34d2c9a516f7a47cf060992107c31e9d9f5 - languageName: node - linkType: hard - "@swagger-api/apidom-ns-api-design-systems@npm:^1.0.0-beta.5": version: 1.0.0-beta.5 resolution: "@swagger-api/apidom-ns-api-design-systems@npm:1.0.0-beta.5" @@ -8155,7 +8094,7 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-ns-json-schema-draft-4@npm:^1.0.0-beta.11": +"@swagger-api/apidom-ns-json-schema-draft-4@npm:^1.0.0-beta.11, @swagger-api/apidom-ns-json-schema-draft-4@npm:^1.0.0-beta.5": version: 1.0.0-beta.11 resolution: "@swagger-api/apidom-ns-json-schema-draft-4@npm:1.0.0-beta.11" dependencies: @@ -8170,21 +8109,6 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-ns-json-schema-draft-4@npm:^1.0.0-beta.5": - version: 1.0.0-beta.5 - resolution: "@swagger-api/apidom-ns-json-schema-draft-4@npm:1.0.0-beta.5" - dependencies: - "@babel/runtime-corejs3": "npm:^7.20.7" - "@swagger-api/apidom-ast": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-core": "npm:^1.0.0-beta.5" - "@types/ramda": "npm:~0.30.0" - ramda: "npm:~0.30.0" - ramda-adjunct: "npm:^5.0.0" - ts-mixer: "npm:^6.0.4" - checksum: 10/2518b3aa9b7387a90553565132101616dc24c6d1f8aee581f3562bac87403f87887217fdb3cf17b113f685e051980fc66ec25d9cab7e4a0bf4922b4bcd3bc502 - languageName: node - linkType: hard - "@swagger-api/apidom-ns-json-schema-draft-6@npm:^1.0.0-beta.11": version: 1.0.0-beta.11 resolution: "@swagger-api/apidom-ns-json-schema-draft-6@npm:1.0.0-beta.11" @@ -8201,23 +8125,7 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-ns-json-schema-draft-6@npm:^1.0.0-beta.5": - version: 1.0.0-beta.5 - resolution: "@swagger-api/apidom-ns-json-schema-draft-6@npm:1.0.0-beta.5" - dependencies: - "@babel/runtime-corejs3": "npm:^7.20.7" - "@swagger-api/apidom-core": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-error": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-ns-json-schema-draft-4": "npm:^1.0.0-beta.5" - "@types/ramda": "npm:~0.30.0" - ramda: "npm:~0.30.0" - ramda-adjunct: "npm:^5.0.0" - ts-mixer: "npm:^6.0.4" - checksum: 10/c439c3679dc6ea1807affa0a2913deea52ff8d63b48722c741458da147e849be9acc0c13955757a7b6904a4e7148cdb7845291da758a085083c61610a96fc36f - languageName: node - linkType: hard - -"@swagger-api/apidom-ns-json-schema-draft-7@npm:^1.0.0-beta.11": +"@swagger-api/apidom-ns-json-schema-draft-7@npm:^1.0.0-beta.11, @swagger-api/apidom-ns-json-schema-draft-7@npm:^1.0.0-beta.5": version: 1.0.0-beta.11 resolution: "@swagger-api/apidom-ns-json-schema-draft-7@npm:1.0.0-beta.11" dependencies: @@ -8233,22 +8141,6 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-ns-json-schema-draft-7@npm:^1.0.0-beta.5": - version: 1.0.0-beta.5 - resolution: "@swagger-api/apidom-ns-json-schema-draft-7@npm:1.0.0-beta.5" - dependencies: - "@babel/runtime-corejs3": "npm:^7.20.7" - "@swagger-api/apidom-core": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-error": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-ns-json-schema-draft-6": "npm:^1.0.0-beta.5" - "@types/ramda": "npm:~0.30.0" - ramda: "npm:~0.30.0" - ramda-adjunct: "npm:^5.0.0" - ts-mixer: "npm:^6.0.4" - checksum: 10/28c8f989e26a453f2ca6c655d6822d63f7bc57137375c460c707caa964a5097566969031f322d772b49de0ce2924aeb69e2c5a6ff66191b457844e68a40f013e - languageName: node - linkType: hard - "@swagger-api/apidom-ns-openapi-2@npm:^1.0.0-beta.3 <1.0.0-rc.0, @swagger-api/apidom-ns-openapi-2@npm:^1.0.0-beta.5": version: 1.0.0-beta.5 resolution: "@swagger-api/apidom-ns-openapi-2@npm:1.0.0-beta.5" @@ -8265,7 +8157,7 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-ns-openapi-3-0@npm:^1.0.0-beta.11": +"@swagger-api/apidom-ns-openapi-3-0@npm:^1.0.0-beta.11, @swagger-api/apidom-ns-openapi-3-0@npm:^1.0.0-beta.3 <1.0.0-rc.0, @swagger-api/apidom-ns-openapi-3-0@npm:^1.0.0-beta.5": version: 1.0.0-beta.11 resolution: "@swagger-api/apidom-ns-openapi-3-0@npm:1.0.0-beta.11" dependencies: @@ -8281,23 +8173,7 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-ns-openapi-3-0@npm:^1.0.0-beta.3 <1.0.0-rc.0, @swagger-api/apidom-ns-openapi-3-0@npm:^1.0.0-beta.5": - version: 1.0.0-beta.5 - resolution: "@swagger-api/apidom-ns-openapi-3-0@npm:1.0.0-beta.5" - dependencies: - "@babel/runtime-corejs3": "npm:^7.20.7" - "@swagger-api/apidom-core": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-error": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-ns-json-schema-draft-4": "npm:^1.0.0-beta.5" - "@types/ramda": "npm:~0.30.0" - ramda: "npm:~0.30.0" - ramda-adjunct: "npm:^5.0.0" - ts-mixer: "npm:^6.0.3" - checksum: 10/5bb9c191a3d79d9a69aa04deb5dd6ce2eaa09700210f5a89fdeb0668ec76eb3f2d4a26950405f001459e59ad199ddd4632251992b9fc1b9fa03955e1ad600810 - languageName: node - linkType: hard - -"@swagger-api/apidom-ns-openapi-3-1@npm:>=1.0.0-beta.11 <1.0.0-rc.0": +"@swagger-api/apidom-ns-openapi-3-1@npm:>=1.0.0-beta.11 <1.0.0-rc.0, @swagger-api/apidom-ns-openapi-3-1@npm:^1.0.0-beta.3 <1.0.0-rc.0, @swagger-api/apidom-ns-openapi-3-1@npm:^1.0.0-beta.5": version: 1.0.0-beta.11 resolution: "@swagger-api/apidom-ns-openapi-3-1@npm:1.0.0-beta.11" dependencies: @@ -8315,23 +8191,6 @@ __metadata: languageName: node linkType: hard -"@swagger-api/apidom-ns-openapi-3-1@npm:^1.0.0-beta.3 <1.0.0-rc.0, @swagger-api/apidom-ns-openapi-3-1@npm:^1.0.0-beta.5": - version: 1.0.0-beta.5 - resolution: "@swagger-api/apidom-ns-openapi-3-1@npm:1.0.0-beta.5" - dependencies: - "@babel/runtime-corejs3": "npm:^7.20.7" - "@swagger-api/apidom-ast": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-core": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-json-pointer": "npm:^1.0.0-beta.5" - "@swagger-api/apidom-ns-openapi-3-0": "npm:^1.0.0-beta.5" - "@types/ramda": "npm:~0.30.0" - ramda: "npm:~0.30.0" - ramda-adjunct: "npm:^5.0.0" - ts-mixer: "npm:^6.0.3" - checksum: 10/69018147465c78a25efc5e7bc4439561c2d620c65c9cf86bdc503dbad9b40e52db77bb0cb11800a4c34bdc88d462126e3dc355bad290cdfe7c9fbeda391405c8 - languageName: node - linkType: hard - "@swagger-api/apidom-ns-workflows-1@npm:^1.0.0-beta.3 <1.0.0-rc.0, @swagger-api/apidom-ns-workflows-1@npm:^1.0.0-beta.5": version: 1.0.0-beta.5 resolution: "@swagger-api/apidom-ns-workflows-1@npm:1.0.0-beta.5" @@ -8661,13 +8520,6 @@ __metadata: languageName: node linkType: hard -"@swc/core-darwin-arm64@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-darwin-arm64@npm:1.10.9" - conditions: os=darwin & cpu=arm64 - languageName: node - linkType: hard - "@swc/core-darwin-x64@npm:1.10.11": version: 1.10.11 resolution: "@swc/core-darwin-x64@npm:1.10.11" @@ -8675,13 +8527,6 @@ __metadata: languageName: node linkType: hard -"@swc/core-darwin-x64@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-darwin-x64@npm:1.10.9" - conditions: os=darwin & cpu=x64 - languageName: node - linkType: hard - "@swc/core-linux-arm-gnueabihf@npm:1.10.11": version: 1.10.11 resolution: "@swc/core-linux-arm-gnueabihf@npm:1.10.11" @@ -8689,13 +8534,6 @@ __metadata: languageName: node linkType: hard -"@swc/core-linux-arm-gnueabihf@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-linux-arm-gnueabihf@npm:1.10.9" - conditions: os=linux & cpu=arm - languageName: node - linkType: hard - "@swc/core-linux-arm64-gnu@npm:1.10.11": version: 1.10.11 resolution: "@swc/core-linux-arm64-gnu@npm:1.10.11" @@ -8703,13 +8541,6 @@ __metadata: languageName: node linkType: hard -"@swc/core-linux-arm64-gnu@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-linux-arm64-gnu@npm:1.10.9" - conditions: os=linux & cpu=arm64 & libc=glibc - languageName: node - linkType: hard - "@swc/core-linux-arm64-musl@npm:1.10.11": version: 1.10.11 resolution: "@swc/core-linux-arm64-musl@npm:1.10.11" @@ -8717,13 +8548,6 @@ __metadata: languageName: node linkType: hard -"@swc/core-linux-arm64-musl@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-linux-arm64-musl@npm:1.10.9" - conditions: os=linux & cpu=arm64 & libc=musl - languageName: node - linkType: hard - "@swc/core-linux-x64-gnu@npm:1.10.11": version: 1.10.11 resolution: "@swc/core-linux-x64-gnu@npm:1.10.11" @@ -8731,13 +8555,6 @@ __metadata: languageName: node linkType: hard -"@swc/core-linux-x64-gnu@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-linux-x64-gnu@npm:1.10.9" - conditions: os=linux & cpu=x64 & libc=glibc - languageName: node - linkType: hard - "@swc/core-linux-x64-musl@npm:1.10.11": version: 1.10.11 resolution: "@swc/core-linux-x64-musl@npm:1.10.11" @@ -8745,13 +8562,6 @@ __metadata: languageName: node linkType: hard -"@swc/core-linux-x64-musl@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-linux-x64-musl@npm:1.10.9" - conditions: os=linux & cpu=x64 & libc=musl - languageName: node - linkType: hard - "@swc/core-win32-arm64-msvc@npm:1.10.11": version: 1.10.11 resolution: "@swc/core-win32-arm64-msvc@npm:1.10.11" @@ -8759,13 +8569,6 @@ __metadata: languageName: node linkType: hard -"@swc/core-win32-arm64-msvc@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-win32-arm64-msvc@npm:1.10.9" - conditions: os=win32 & cpu=arm64 - languageName: node - linkType: hard - "@swc/core-win32-ia32-msvc@npm:1.10.11": version: 1.10.11 resolution: "@swc/core-win32-ia32-msvc@npm:1.10.11" @@ -8773,13 +8576,6 @@ __metadata: languageName: node linkType: hard -"@swc/core-win32-ia32-msvc@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-win32-ia32-msvc@npm:1.10.9" - conditions: os=win32 & cpu=ia32 - languageName: node - linkType: hard - "@swc/core-win32-x64-msvc@npm:1.10.11": version: 1.10.11 resolution: "@swc/core-win32-x64-msvc@npm:1.10.11" @@ -8787,14 +8583,7 @@ __metadata: languageName: node linkType: hard -"@swc/core-win32-x64-msvc@npm:1.10.9": - version: 1.10.9 - resolution: "@swc/core-win32-x64-msvc@npm:1.10.9" - conditions: os=win32 & cpu=x64 - languageName: node - linkType: hard - -"@swc/core@npm:1.10.11": +"@swc/core@npm:1.10.11, @swc/core@npm:^1.7.3": version: 1.10.11 resolution: "@swc/core@npm:1.10.11" dependencies: @@ -8840,52 +8629,6 @@ __metadata: languageName: node linkType: hard -"@swc/core@npm:^1.7.3": - version: 1.10.9 - resolution: "@swc/core@npm:1.10.9" - dependencies: - "@swc/core-darwin-arm64": "npm:1.10.9" - "@swc/core-darwin-x64": "npm:1.10.9" - "@swc/core-linux-arm-gnueabihf": "npm:1.10.9" - "@swc/core-linux-arm64-gnu": "npm:1.10.9" - "@swc/core-linux-arm64-musl": "npm:1.10.9" - "@swc/core-linux-x64-gnu": "npm:1.10.9" - "@swc/core-linux-x64-musl": "npm:1.10.9" - "@swc/core-win32-arm64-msvc": "npm:1.10.9" - "@swc/core-win32-ia32-msvc": "npm:1.10.9" - "@swc/core-win32-x64-msvc": "npm:1.10.9" - "@swc/counter": "npm:^0.1.3" - "@swc/types": "npm:^0.1.17" - peerDependencies: - "@swc/helpers": "*" - dependenciesMeta: - "@swc/core-darwin-arm64": - optional: true - "@swc/core-darwin-x64": - optional: true - "@swc/core-linux-arm-gnueabihf": - optional: true - "@swc/core-linux-arm64-gnu": - optional: true - "@swc/core-linux-arm64-musl": - optional: true - "@swc/core-linux-x64-gnu": - optional: true - "@swc/core-linux-x64-musl": - optional: true - "@swc/core-win32-arm64-msvc": - optional: true - "@swc/core-win32-ia32-msvc": - optional: true - "@swc/core-win32-x64-msvc": - optional: true - peerDependenciesMeta: - "@swc/helpers": - optional: true - checksum: 10/543e79c249f6052883d656035321d449cf6c0f2ea54f786d5e3b96394d4cf201b293d6c3f897cc604eb145b21cce82f904306931fe9efbc6a50c714a5d5d97f0 - languageName: node - linkType: hard - "@swc/counter@npm:^0.1.3": version: 0.1.3 resolution: "@swc/counter@npm:0.1.3" @@ -8912,21 +8655,21 @@ __metadata: linkType: hard "@tanstack/react-virtual@npm:^3.5.1, @tanstack/react-virtual@npm:^3.9.0": - version: 3.11.2 - resolution: "@tanstack/react-virtual@npm:3.11.2" + version: 3.11.3 + resolution: "@tanstack/react-virtual@npm:3.11.3" dependencies: - "@tanstack/virtual-core": "npm:3.11.2" + "@tanstack/virtual-core": "npm:3.11.3" peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - checksum: 10/a1136da0ec4c2ecbd4f996d8b84f228f0b8d851b15806e01049a160ad1d9b2eef0e0a491035fe017c6f84a0e125334f69ea23b32c180df23614ea4a8eeb7490c + checksum: 10/eb39f8a015f4dc98070f0c18bbb1f9c094b7182133554ef3ee31d2678cd3a66edd28ce854d533e830f88f1f0ad1d5b065de184438a08fe774a9acc1dc62da436 languageName: node linkType: hard -"@tanstack/virtual-core@npm:3.11.2": - version: 3.11.2 - resolution: "@tanstack/virtual-core@npm:3.11.2" - checksum: 10/8433044a5c801052ba2e4cdda098cdc8e32adfd3a76ba31af7064bbdda60062fe221a3558096987baa66cd94f528855e887c282cb0f9eb99d3751457c2a62872 +"@tanstack/virtual-core@npm:3.11.3": + version: 3.11.3 + resolution: "@tanstack/virtual-core@npm:3.11.3" + checksum: 10/24a3369dd0290d4f19aa1af7d0a6fb1b843741d722c6a5cf786416657bbf978f4f82a0b257eaee867d0798d8334374f5e940868a7b71dc065939fb7eeee19ad1 languageName: node linkType: hard From c0600969e0857037d37bbbea15088eb4274582b1 Mon Sep 17 00:00:00 2001 From: Kevin Minehart <5140827+kminehart@users.noreply.github.com> Date: Wed, 29 Jan 2025 09:04:12 -0600 Subject: [PATCH 02/18] CI: update changelog generator to use compare API (#99688) update changelog generator to use compare API --- .github/workflows/actions/changelog/index.js | 46 +++++++++++--------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/.github/workflows/actions/changelog/index.js b/.github/workflows/actions/changelog/index.js index 48da9dcf33a..b658caf349c 100644 --- a/.github/workflows/actions/changelog/index.js +++ b/.github/workflows/actions/changelog/index.js @@ -69,8 +69,17 @@ const graphql = async (ghtoken, query, variables) => { }, body: JSON.stringify({ query, variables }), }); - const { data } = await results.json(); - return data; + + const res = await results.json(); + + LOG( + JSON.stringify({ + status: results.status, + text: results.statusText, + }) + ); + + return res.data; }; // Using Github GraphQL API find the timestamp for the given tag/commit hash. @@ -99,20 +108,20 @@ const getCommitishDate = async (name, owner, target) => { // Using Github GraphQL API get a list of PRs between the two "commitish" items. // This resoves the "since" item's timestamp first and iterates over all PRs // till "target" using naïve pagination. -const getHistory = async (name, owner, target, sinceDate) => { - LOG(`Fetching ${owner}/${name} PRs since ${sinceDate} till ${target}`); +const getHistory = async (name, owner, from, to) => { + LOG(`Fetching ${owner}/${name} PRs between ${from} and ${to}`); const query = ` query findCommitsWithAssociatedPullRequests( $name: String! $owner: String! - $target: String! - $sinceDate: GitTimestamp + $from: String! + $to: String! $cursor: String ) { repository(name: $name, owner: $owner) { - object(expression: $target) { - ... on Commit { - history(first: 50, since: $sinceDate, after: $cursor) { + ref(qualifiedName: $from) { + compare(headRef: $to) { + commits(first: 25, after: $cursor) { totalCount pageInfo { hasNextPage @@ -155,13 +164,13 @@ const getHistory = async (name, owner, target, sinceDate) => { const result = await graphql(ghtoken, query, { name, owner, - target, - sinceDate, + from, + to, cursor, }); LOG(`GraphQL: ${JSON.stringify(result)}`); - nodes = [...nodes, ...result.repository.object.history.nodes]; - const { hasNextPage, endCursor } = result.repository.object.history.pageInfo; + nodes = [...nodes, ...result.repository.ref.compare.commits.nodes]; + const { hasNextPage, endCursor } = result.repository.ref.compare.commits.pageInfo; if (!hasNextPage) { break; } @@ -175,11 +184,11 @@ const getHistory = async (name, owner, target, sinceDate) => { // feature, deprecation, breaking change and plugin fixes/enhancements). // // PR grouping relies on Github labels only, not on the PR contents. -const getChangeLogItems = async (name, owner, sinceDate, to) => { +const getChangeLogItems = async (name, owner, from, to) => { // check if a node contains a certain label const hasLabel = ({ labels }, label) => labels.nodes.some(({ name }) => name === label); // get all the PRs between the two "commitish" items - const history = await getHistory(name, owner, to, sinceDate); + const history = await getHistory(name, owner, from, to); const items = history.flatMap((node) => { // discard PRs without a "changelog" label @@ -231,13 +240,10 @@ const previous = process.argv[3] || process.env.INPUT_PREVIOUS || (await getPrev LOG(`Previous tag/commit: ${previous}`); -const sinceDate = await getCommitishDate('grafana', 'grafana', previous); -LOG(`Previous tag/commit timestamp: ${sinceDate}`); - // Get all changelog items from Grafana OSS -const oss = await getChangeLogItems('grafana', 'grafana', sinceDate, target); +const oss = await getChangeLogItems('grafana', 'grafana', previous, target); // Get all changelog items from Grafana Enterprise -const entr = await getChangeLogItems('grafana-enterprise', 'grafana', sinceDate, target); +const entr = await getChangeLogItems('grafana-enterprise', 'grafana', previous, target); LOG(`Found OSS PRs: ${oss.length}`); LOG(`Found Enterprise PRs: ${entr.length}`); From 9b37337f7b1061c9ff6549f1ca7db88ff79900e0 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 29 Jan 2025 17:14:41 +0200 Subject: [PATCH 03/18] Update dependency @types/webpack-env to v1.18.8 (#99759) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index 1bc54e8d8a4..d4270687974 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10322,9 +10322,9 @@ __metadata: linkType: hard "@types/webpack-env@npm:^1.18.4": - version: 1.18.5 - resolution: "@types/webpack-env@npm:1.18.5" - checksum: 10/3c8dd0b23d45e2d33abdfbae7f1d8f75ce23d54588b08943e833f4dba81eb683ac68672a75eccbdba8e008bc1647638803c1bcadc8cdfd1dd7142fa2c3f612de + version: 1.18.8 + resolution: "@types/webpack-env@npm:1.18.8" + checksum: 10/f3932f3d6c2530f644cfc898eda1ab8182d6ae57f555c2f0179d813549b639078671b71e4041831fc306c5ebe61f5cdac794fe4ceae281fce8bf67e23661a488 languageName: node linkType: hard From 90c18099a54cab1356796dca63b9033ec61fffd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jean-Philippe=20Qu=C3=A9m=C3=A9ner?= Date: Wed, 29 Jan 2025 16:38:25 +0100 Subject: [PATCH 04/18] fix(unified-storage): return folder title in legacy search (#99762) --- .../dashboards/service/dashboard_service.go | 32 +++++++++--- .../service/dashboard_service_test.go | 50 +++++++++++-------- 2 files changed, 54 insertions(+), 28 deletions(-) diff --git a/pkg/services/dashboards/service/dashboard_service.go b/pkg/services/dashboards/service/dashboard_service.go index 8f4953d2723..d56118429d2 100644 --- a/pkg/services/dashboards/service/dashboard_service.go +++ b/pkg/services/dashboards/service/dashboard_service.go @@ -23,6 +23,7 @@ import ( claims "github.com/grafana/authlib/types" "github.com/grafana/grafana-plugin-sdk-go/backend/gtime" + "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/apis/dashboard/v0alpha1" @@ -1248,16 +1249,31 @@ func (dr *DashboardServiceImpl) FindDashboards(ctx context.Context, query *dashb } finalResults := make([]dashboards.DashboardSearchProjection, len(response.Hits)) + // Create a small runtime cache for folders to avoid extra calls to the folder service + foldersMap := make(map[string]*folder.Folder) for i, hit := range response.Hits { + f, ok := foldersMap[hit.Folder] + if !ok { + f, err = dr.folderService.Get(ctx, &folder.GetFolderQuery{ + UID: &hit.Folder, + OrgID: query.OrgId, + SignedInUser: query.SignedInUser, + }) + if err != nil { + return nil, err + } + foldersMap[hit.Folder] = f + } finalResults[i] = dashboards.DashboardSearchProjection{ - ID: hit.Field.GetNestedInt64(search.DASHBOARD_LEGACY_ID), - UID: hit.Name, - OrgID: query.OrgId, - Title: hit.Title, - Slug: slugify.Slugify(hit.Title), - IsFolder: false, - FolderUID: hit.Folder, - Tags: hit.Tags, + ID: hit.Field.GetNestedInt64(search.DASHBOARD_LEGACY_ID), + UID: hit.Name, + OrgID: query.OrgId, + Title: hit.Title, + Slug: slugify.Slugify(hit.Title), + IsFolder: false, + FolderUID: hit.Folder, + FolderTitle: f.Title, + Tags: hit.Tags, } } diff --git a/pkg/services/dashboards/service/dashboard_service_test.go b/pkg/services/dashboards/service/dashboard_service_test.go index d7adcd9ad9a..1ae6c4f5b90 100644 --- a/pkg/services/dashboards/service/dashboard_service_test.go +++ b/pkg/services/dashboards/service/dashboard_service_test.go @@ -10,6 +10,9 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/components/simplejson" @@ -28,8 +31,6 @@ import ( "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/storage/unified/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) func TestDashboardService(t *testing.T) { @@ -71,10 +72,10 @@ func TestDashboardService(t *testing.T) { t.Run("Should return validation error if message is too long", func(t *testing.T) { dto.Dashboard = dashboards.NewDashboard("Dash") dto.Message = `Here we go, 500+ characters for testing. I'm sorry that you're - having to read this. I spent too long trying to come up with something clever + having to read this. I spent too long trying to come up with something clever to say or a funny joke. Unforuntately, nothing came to mind. So instead, I'm will share this with you, as a form of payment for having to read this: - https://youtu.be/dQw4w9WgXcQ?si=KeoTIpn9tUtQnOBk! Enjoy :) Now lets see if + https://youtu.be/dQw4w9WgXcQ?si=KeoTIpn9tUtQnOBk! Enjoy :) Now lets see if this test passes or if the result is more exciting than these 500 characters I wrote. Best of luck to the both of us!` _, err := service.SaveDashboard(context.Background(), dto, false) @@ -1327,10 +1328,15 @@ func TestDeleteAllDashboards(t *testing.T) { func TestSearchDashboards(t *testing.T) { fakeStore := dashboards.FakeDashboardStore{} + fakeFolders := foldertest.NewFakeService() + fakeFolders.ExpectedFolder = &folder.Folder{ + Title: "testing-folder-1", + } defer fakeStore.AssertExpectations(t) service := &DashboardServiceImpl{ cfg: setting.NewCfg(), dashboardStore: &fakeStore, + folderService: fakeFolders, } expectedResult := model.HitList{ @@ -1345,15 +1351,17 @@ func TestSearchDashboards(t *testing.T) { "tag1", "tag2", }, + FolderTitle: "testing-folder-1", }, { - UID: "uid2", - OrgID: 1, - Title: "Dashboard 2", - Type: "dash-db", - URI: "db/dashboard-2", - URL: "/d/uid2/dashboard-2", - Tags: []string{}, + UID: "uid2", + OrgID: 1, + Title: "Dashboard 2", + Type: "dash-db", + URI: "db/dashboard-2", + URL: "/d/uid2/dashboard-2", + Tags: []string{}, + FolderTitle: "testing-folder-1", }, } query := dashboards.FindPersistedDashboardsQuery{ @@ -1363,17 +1371,19 @@ func TestSearchDashboards(t *testing.T) { service.features = featuremgmt.WithFeatures() fakeStore.On("FindDashboards", mock.Anything, mock.Anything).Return([]dashboards.DashboardSearchProjection{ { - UID: "uid1", - Slug: "dashboard-1", - OrgID: 1, - Title: "Dashboard 1", - Tags: []string{"tag1", "tag2"}, + UID: "uid1", + Slug: "dashboard-1", + OrgID: 1, + Title: "Dashboard 1", + Tags: []string{"tag1", "tag2"}, + FolderTitle: "testing-folder-1", }, { - UID: "uid2", - Slug: "dashboard-2", - OrgID: 1, - Title: "Dashboard 2", + UID: "uid2", + Slug: "dashboard-2", + OrgID: 1, + Title: "Dashboard 2", + FolderTitle: "testing-folder-1", }, }, nil).Once() result, err := service.SearchDashboards(context.Background(), &query) From 7883215c680a5bc9c7782918e77b81d2095c5236 Mon Sep 17 00:00:00 2001 From: Joey <90795735+joey-grafana@users.noreply.github.com> Date: Wed, 29 Jan 2025 15:40:06 +0000 Subject: [PATCH 05/18] Tempo: Support TraceQL instant metrics queries (#99732) Support TraceQL instant metrics --- .../dataquery/x/TempoDataQuery_types.gen.ts | 9 ++++ .../kinds/dataquery/types_dataquery_gen.go | 13 ++++- pkg/tsdb/tempo/traceql/metrics.go | 40 +++++++++++++++ pkg/tsdb/tempo/traceql/metrics_test.go | 44 ++++++++++++++++ pkg/tsdb/tempo/traceql_query.go | 50 +++++++++++++++---- .../plugins/datasource/tempo/dataquery.cue | 4 ++ .../plugins/datasource/tempo/dataquery.gen.ts | 9 ++++ .../traceql/TempoQueryBuilderOptions.tsx | 20 +++++++- 8 files changed, 177 insertions(+), 12 deletions(-) diff --git a/packages/grafana-schema/src/raw/composable/tempo/dataquery/x/TempoDataQuery_types.gen.ts b/packages/grafana-schema/src/raw/composable/tempo/dataquery/x/TempoDataQuery_types.gen.ts index b93945b296d..9a279f1653b 100644 --- a/packages/grafana-schema/src/raw/composable/tempo/dataquery/x/TempoDataQuery_types.gen.ts +++ b/packages/grafana-schema/src/raw/composable/tempo/dataquery/x/TempoDataQuery_types.gen.ts @@ -30,6 +30,10 @@ export interface TempoQuery extends common.DataQuery { * @deprecated Define the maximum duration to select traces. Use duration format, for example: 1.2s, 100ms */ maxDuration?: string; + /** + * For metric queries, whether to run instant or range queries + */ + metricsQueryType?: MetricsQueryType; /** * @deprecated Define the minimum duration to select traces. Use duration format, for example: 1.2s, 100ms */ @@ -79,6 +83,11 @@ export const defaultTempoQuery: Partial = { export type TempoQueryType = ('traceql' | 'traceqlSearch' | 'serviceMap' | 'upload' | 'nativeSearch' | 'traceId' | 'clear'); +export enum MetricsQueryType { + Instant = 'instant', + Range = 'range', +} + /** * The state of the TraceQL streaming search query */ diff --git a/pkg/tsdb/tempo/kinds/dataquery/types_dataquery_gen.go b/pkg/tsdb/tempo/kinds/dataquery/types_dataquery_gen.go index a709b74c0e6..079185206f1 100644 --- a/pkg/tsdb/tempo/kinds/dataquery/types_dataquery_gen.go +++ b/pkg/tsdb/tempo/kinds/dataquery/types_dataquery_gen.go @@ -54,13 +54,15 @@ type TempoQuery struct { TableType *SearchTableType `json:"tableType,omitempty"` // For metric queries, the step size to use Step *string `json:"step,omitempty"` + // For metric queries, how many exemplars to request, 0 means no exemplars + Exemplars *int64 `json:"exemplars,omitempty"` // For mixed data sources the selected datasource is on the query level. // For non mixed scenarios this is undefined. // TODO find a better way to do this ^ that's friendly to schema // TODO this shouldn't be unknown but DataSourceRef | null Datasource any `json:"datasource,omitempty"` - // For metric queries, how many exemplars to request, 0 means no exemplars - Exemplars *int64 `json:"exemplars,omitempty"` + // For metric queries, whether to run instant or range queries + MetricsQueryType *MetricsQueryType `json:"metricsQueryType,omitempty"` } // NewTempoQuery creates a new TempoQuery object. @@ -80,6 +82,13 @@ const ( TempoQueryTypeClear TempoQueryType = "clear" ) +type MetricsQueryType string + +const ( + MetricsQueryTypeRange MetricsQueryType = "range" + MetricsQueryTypeInstant MetricsQueryType = "instant" +) + // The state of the TraceQL streaming search query type SearchStreamingState string diff --git a/pkg/tsdb/tempo/traceql/metrics.go b/pkg/tsdb/tempo/traceql/metrics.go index 06fd22b1fb0..54e5e34c7e6 100644 --- a/pkg/tsdb/tempo/traceql/metrics.go +++ b/pkg/tsdb/tempo/traceql/metrics.go @@ -59,6 +59,46 @@ func TransformMetricsResponse(query *dataquery.TempoQuery, resp tempopb.QueryRan return append(frames, exemplarFrames...) } +func TransformInstantMetricsResponse(query *dataquery.TempoQuery, resp tempopb.QueryInstantResponse) []*data.Frame { + frames := make([]*data.Frame, len(resp.Series)) + + for i, series := range resp.Series { + name, labels := transformLabelsAndGetName(series.Labels) + + labelKeys := make([]string, 0, len(labels)) + labelFields := make([]*data.Field, 0, len(labels)) + for key := range labels { + labelKeys = append(labelKeys, key) + labelFields = append(labelFields, data.NewField(key, nil, []string{})) + } + + timeField := data.NewField("time", nil, []time.Time{}) + valueField := data.NewField("value", labels, []float64{}) + valueField.Config = &data.FieldConfig{ + DisplayName: name, + } + + frame := &data.Frame{ + RefID: name, + Name: name, + Fields: append([]*data.Field{timeField}, append(labelFields, valueField)...), + Meta: &data.FrameMeta{ + PreferredVisualization: data.VisTypeTable, + }, + } + + labelValues := make([]interface{}, len(labels)) + for idx, key := range labelKeys { + labelValues[idx] = strings.Trim(labels[key], "\"") + } + row := append([]interface{}{time.Now()}, append(labelValues, series.GetValue())...) + frame.AppendRow(row...) + + frames[i] = frame + } + return frames +} + func metricsValueToString(value *v1.AnyValue) (string, string) { switch value.GetValue().(type) { case *v1.AnyValue_DoubleValue: diff --git a/pkg/tsdb/tempo/traceql/metrics_test.go b/pkg/tsdb/tempo/traceql/metrics_test.go index f5ac27c3f12..8254af5f8b5 100644 --- a/pkg/tsdb/tempo/traceql/metrics_test.go +++ b/pkg/tsdb/tempo/traceql/metrics_test.go @@ -122,3 +122,47 @@ func TestTransformMetricsResponse_MultipleSeries(t *testing.T) { assert.Equal(t, time.UnixMilli(1638316800000), frames[1].Fields[0].At(0)) assert.Equal(t, 4.56, frames[1].Fields[1].At(0)) } + +func TestTransformInstantMetricsResponse(t *testing.T) { + query := &dataquery.TempoQuery{} + resp := tempopb.QueryInstantResponse{ + Series: []*tempopb.InstantSeries{ + { + Labels: []v1.KeyValue{ + { + Key: "label", + Value: &v1.AnyValue{Value: &v1.AnyValue_StringValue{StringValue: "value"}}, + }, + }, + Value: 123.45, + PromLabels: "label=\"value\"", + }, + }, + } + + frames := TransformInstantMetricsResponse(query, resp) + + assert.Len(t, frames, 1) + frame := frames[0] + + assert.Equal(t, "value", frame.RefID) + assert.Equal(t, "value", frame.Name) + assert.Len(t, frame.Fields, 3) + + timeField := frame.Fields[0] + assert.Equal(t, "time", timeField.Name) + assert.Equal(t, 1, timeField.Len()) + assert.IsType(t, time.Time{}, timeField.At(0)) + + labelField := frame.Fields[1] + assert.Equal(t, "label", labelField.Name) + assert.Equal(t, 1, labelField.Len()) + assert.IsType(t, "", labelField.At(0)) + assert.Equal(t, "value", labelField.At(0)) + + valueField := frame.Fields[2] + assert.Equal(t, "value", valueField.Name) + assert.Equal(t, 1, valueField.Len()) + assert.IsType(t, 0.0, valueField.At(0)) + assert.Equal(t, 123.45, valueField.At(0).(float64)) +} diff --git a/pkg/tsdb/tempo/traceql_query.go b/pkg/tsdb/tempo/traceql_query.go index 35d45b0beee..5265097ad41 100644 --- a/pkg/tsdb/tempo/traceql_query.go +++ b/pkg/tsdb/tempo/traceql_query.go @@ -14,6 +14,7 @@ import ( //nolint:all "github.com/golang/protobuf/jsonpb" "github.com/grafana/grafana-plugin-sdk-go/backend" + "github.com/grafana/grafana-plugin-sdk-go/backend/log" "github.com/grafana/grafana-plugin-sdk-go/backend/tracing" "github.com/grafana/grafana/pkg/tsdb/tempo/kinds/dataquery" "github.com/grafana/grafana/pkg/tsdb/tempo/traceql" @@ -86,21 +87,40 @@ func (s *Service) runTraceQlQueryMetrics(ctx context.Context, pCtx backend.Plugi return result, nil } - var queryResponse tempopb.QueryRangeResponse - err = jsonpb.Unmarshal(bytes.NewReader(responseBody), &queryResponse) + if isInstantQuery(tempoQuery.MetricsQueryType) { + var queryResponse tempopb.QueryInstantResponse + err = jsonpb.Unmarshal(bytes.NewReader(responseBody), &queryResponse) + if res, err := handleConversionError(ctxLogger, span, err); err != nil { + return res, err + } + + frames := traceql.TransformInstantMetricsResponse(tempoQuery, queryResponse) + result.Frames = frames + } else { + var queryResponse tempopb.QueryRangeResponse + err = jsonpb.Unmarshal(bytes.NewReader(responseBody), &queryResponse) + + if res, err := handleConversionError(ctxLogger, span, err); err != nil { + return res, err + } + + frames := traceql.TransformMetricsResponse(tempoQuery, queryResponse) + result.Frames = frames + } + + ctxLogger.Debug("Successfully performed TraceQL query", "function", logEntrypoint()) + return result, nil +} + +func handleConversionError(ctxLogger log.Logger, span trace.Span, err error) (*backend.DataResponse, error) { if err != nil { ctxLogger.Error("Failed to convert response to type", "error", err, "function", logEntrypoint()) span.RecordError(err) span.SetStatus(codes.Error, err.Error()) return &backend.DataResponse{}, fmt.Errorf("failed to convert response to type: %w", err) } - - frames := traceql.TransformMetricsResponse(tempoQuery, queryResponse) - - result.Frames = frames - ctxLogger.Debug("Successfully performed TraceQL query", "function", logEntrypoint()) - return result, nil + return nil, nil } func (s *Service) performMetricsQuery(ctx context.Context, dsInfo *Datasource, model *dataquery.TempoQuery, query backend.DataQuery, span trace.Span) (*http.Response, []byte, error) { @@ -133,7 +153,12 @@ func (s *Service) performMetricsQuery(ctx context.Context, dsInfo *Datasource, m func (s *Service) createMetricsQuery(ctx context.Context, dsInfo *Datasource, query *dataquery.TempoQuery, start int64, end int64) (*http.Request, error) { ctxLogger := s.logger.FromContext(ctx) - rawUrl := fmt.Sprintf("%s/api/metrics/query_range", dsInfo.URL) + queryType := "query_range" + if isInstantQuery(query.MetricsQueryType) { + queryType = "query" + } + + rawUrl := fmt.Sprintf("%s/api/metrics/%s", dsInfo.URL, queryType) searchUrl, err := url.Parse(rawUrl) if err != nil { ctxLogger.Error("Failed to parse URL", "url", rawUrl, "error", err, "function", logEntrypoint()) @@ -167,6 +192,13 @@ func (s *Service) createMetricsQuery(ctx context.Context, dsInfo *Datasource, qu return req, nil } +func isInstantQuery(metricQueryType *dataquery.MetricsQueryType) bool { + if metricQueryType == nil { + return false + } + return *metricQueryType == dataquery.MetricsQueryTypeInstant +} + func isMetricsQuery(query string) bool { match, _ := regexp.MatchString("\\|\\s*(rate|count_over_time|avg_over_time|max_over_time|min_over_time|quantile_over_time|histogram_over_time|compare)\\s*\\(", query) return match diff --git a/public/app/plugins/datasource/tempo/dataquery.cue b/public/app/plugins/datasource/tempo/dataquery.cue index 345a5d11409..ef5a4526dbb 100644 --- a/public/app/plugins/datasource/tempo/dataquery.cue +++ b/public/app/plugins/datasource/tempo/dataquery.cue @@ -55,10 +55,14 @@ composableKinds: DataQuery: { step?: string // For metric queries, how many exemplars to request, 0 means no exemplars exemplars?: int64 + // For metric queries, whether to run instant or range queries + metricsQueryType?: #MetricsQueryType } @cuetsy(kind="interface") @grafana(TSVeneer="type") #TempoQueryType: "traceql" | "traceqlSearch" | "serviceMap" | "upload" | "nativeSearch" | "traceId" | "clear" @cuetsy(kind="type") + #MetricsQueryType: "range" | "instant" @cuetsy(kind="enum") + // The state of the TraceQL streaming search query #SearchStreamingState: "pending" | "streaming" | "done" | "error" @cuetsy(kind="enum") diff --git a/public/app/plugins/datasource/tempo/dataquery.gen.ts b/public/app/plugins/datasource/tempo/dataquery.gen.ts index 31a2a9f3fbe..757960330c8 100644 --- a/public/app/plugins/datasource/tempo/dataquery.gen.ts +++ b/public/app/plugins/datasource/tempo/dataquery.gen.ts @@ -28,6 +28,10 @@ export interface TempoQuery extends common.DataQuery { * @deprecated Define the maximum duration to select traces. Use duration format, for example: 1.2s, 100ms */ maxDuration?: string; + /** + * For metric queries, whether to run instant or range queries + */ + metricsQueryType?: MetricsQueryType; /** * @deprecated Define the minimum duration to select traces. Use duration format, for example: 1.2s, 100ms */ @@ -77,6 +81,11 @@ export const defaultTempoQuery: Partial = { export type TempoQueryType = ('traceql' | 'traceqlSearch' | 'serviceMap' | 'upload' | 'nativeSearch' | 'traceId' | 'clear'); +export enum MetricsQueryType { + Instant = 'instant', + Range = 'range', +} + /** * The state of the TraceQL streaming search query */ diff --git a/public/app/plugins/datasource/tempo/traceql/TempoQueryBuilderOptions.tsx b/public/app/plugins/datasource/tempo/traceql/TempoQueryBuilderOptions.tsx index f273bc788ca..5834a153594 100644 --- a/public/app/plugins/datasource/tempo/traceql/TempoQueryBuilderOptions.tsx +++ b/public/app/plugins/datasource/tempo/traceql/TempoQueryBuilderOptions.tsx @@ -6,7 +6,7 @@ import { EditorField, EditorRow } from '@grafana/experimental'; import { AutoSizeInput, RadioButtonGroup, useStyles2 } from '@grafana/ui'; import { QueryOptionGroup } from '../_importedDependencies/datasources/prometheus/QueryOptionGroup'; -import { SearchTableType } from '../dataquery.gen'; +import { SearchTableType, MetricsQueryType } from '../dataquery.gen'; import { DEFAULT_LIMIT, DEFAULT_SPSS } from '../datasource'; import { TempoQuery } from '../types'; @@ -40,6 +40,10 @@ export const TempoQueryBuilderOptions = React.memo(({ onChange, query, is query.tableType = SearchTableType.Traces; } + if (!query.hasOwnProperty('metricsQueryType')) { + query.metricsQueryType = MetricsQueryType.Range; + } + const onLimitChange = (e: React.FormEvent) => { onChange({ ...query, limit: parseIntWithFallback(e.currentTarget.value, DEFAULT_LIMIT) }); }; @@ -49,6 +53,9 @@ export const TempoQueryBuilderOptions = React.memo(({ onChange, query, is const onTableTypeChange = (val: SearchTableType) => { onChange({ ...query, tableType: val }); }; + const onMetricsQueryTypeChange = (val: MetricsQueryType) => { + onChange({ ...query, metricsQueryType: val }); + }; const onStepChange = (e: React.FormEvent) => { onChange({ ...query, step: e.currentTarget.value }); }; @@ -74,6 +81,7 @@ export const TempoQueryBuilderOptions = React.memo(({ onChange, query, is const collapsedMetricsOptions = [ `Step: ${query.step || 'auto'}`, + `Type: ${query.metricsQueryType === MetricsQueryType.Range ? 'Range' : 'Instant'}`, // `Exemplars: ${query.exemplars !== undefined ? query.exemplars : 'auto'}`, ]; @@ -132,6 +140,16 @@ export const TempoQueryBuilderOptions = React.memo(({ onChange, query, is value={query.step} /> + + + {/* Date: Wed, 29 Jan 2025 15:46:13 +0000 Subject: [PATCH 06/18] Chore: add lint rule prevent `t` import from `i18next` (#99761) * also handle i18next import * fix violations --- eslint.config.js | 5 +++++ .../features/explore/RichHistory/RichHistoryAddToLibrary.tsx | 2 +- public/app/features/manage-dashboards/utils/validation.ts | 3 +-- .../features/migrate-to-cloud/onprem/useNotifyOnSuccess.tsx | 2 +- public/app/features/profile/UserSessions.tsx | 3 +-- 5 files changed, 9 insertions(+), 6 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index cf427ade626..8c4910b7310 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -117,6 +117,11 @@ module.exports = [ importNames: ['Trans', 't'], message: 'Please import from app/core/internationalization instead', }, + { + name: 'i18next', + importNames: ['t'], + message: 'Please import from app/core/internationalization instead', + }, ], }, ], diff --git a/public/app/features/explore/RichHistory/RichHistoryAddToLibrary.tsx b/public/app/features/explore/RichHistory/RichHistoryAddToLibrary.tsx index 260d6f945b6..f735180c11a 100644 --- a/public/app/features/explore/RichHistory/RichHistoryAddToLibrary.tsx +++ b/public/app/features/explore/RichHistory/RichHistoryAddToLibrary.tsx @@ -1,8 +1,8 @@ -import { t } from 'i18next'; import { useState } from 'react'; import { DataQuery } from '@grafana/schema'; import { Button, Modal } from '@grafana/ui'; +import { t } from 'app/core/internationalization'; import { isQueryLibraryEnabled, useListQueryTemplateQuery } from 'app/features/query-library'; import { getK8sNamespace } from '../../query-library/api/query'; diff --git a/public/app/features/manage-dashboards/utils/validation.ts b/public/app/features/manage-dashboards/utils/validation.ts index b6d78b9b952..7e4b1d9089e 100644 --- a/public/app/features/manage-dashboards/utils/validation.ts +++ b/public/app/features/manage-dashboards/utils/validation.ts @@ -1,5 +1,4 @@ -import { t } from 'i18next'; - +import { t } from 'app/core/internationalization'; import { getDashboardAPI } from 'app/features/dashboard/api/dashboard_api'; import { validationSrv } from '../services/ValidationSrv'; diff --git a/public/app/features/migrate-to-cloud/onprem/useNotifyOnSuccess.tsx b/public/app/features/migrate-to-cloud/onprem/useNotifyOnSuccess.tsx index a5baf03f93e..e21fd83e815 100644 --- a/public/app/features/migrate-to-cloud/onprem/useNotifyOnSuccess.tsx +++ b/public/app/features/migrate-to-cloud/onprem/useNotifyOnSuccess.tsx @@ -1,7 +1,7 @@ -import { t } from 'i18next'; import { useRef, useEffect } from 'react'; import { useAppNotification } from 'app/core/copy/appNotification'; +import { t } from 'app/core/internationalization'; import { GetSnapshotResponseDto, SnapshotDto } from '../api'; diff --git a/public/app/features/profile/UserSessions.tsx b/public/app/features/profile/UserSessions.tsx index a6ed2d98543..f6cc0538c64 100644 --- a/public/app/features/profile/UserSessions.tsx +++ b/public/app/features/profile/UserSessions.tsx @@ -1,11 +1,10 @@ import { css } from '@emotion/css'; -import { t } from 'i18next'; import { PureComponent } from 'react'; import { selectors } from '@grafana/e2e-selectors'; import { Button, Icon, LoadingPlaceholder } from '@grafana/ui'; import { TagBadge } from 'app/core/components/TagFilter/TagBadge'; -import { Trans } from 'app/core/internationalization'; +import { t, Trans } from 'app/core/internationalization'; import { formatDate } from 'app/core/internationalization/dates'; import { UserSession } from 'app/types'; From 0613ed1f1147d78521af2cf0cfe4deb08a8f4888 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 29 Jan 2025 15:47:25 +0000 Subject: [PATCH 07/18] Update dependency i18next to v24.2.2 (#99763) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index d4270687974..1a4a877ad45 100644 --- a/yarn.lock +++ b/yarn.lock @@ -18850,8 +18850,8 @@ __metadata: linkType: hard "i18next@npm:^23.5.1 || ^24.2.0, i18next@npm:^24.0.0": - version: 24.2.1 - resolution: "i18next@npm:24.2.1" + version: 24.2.2 + resolution: "i18next@npm:24.2.2" dependencies: "@babel/runtime": "npm:^7.23.2" peerDependencies: @@ -18859,7 +18859,7 @@ __metadata: peerDependenciesMeta: typescript: optional: true - checksum: 10/74836c3ca3365155906f95162bf75461f8f82a86034b03fc8efc670e10f610299dc5b51923acc1ab9d52ec7e7e717e44fb95b91ff1560ff45c6bad0c383517af + checksum: 10/f66ed9e56d9412e59502f5df39163631daf9f1264774732fb21edbd66a528ca7a6b67dc2e2aec95683c6c7956e42c651587a54bd8ee082bd12008880ce6cd326 languageName: node linkType: hard From 9f4e8ee206c3715680a562eb6fe88613fcb59cff Mon Sep 17 00:00:00 2001 From: Alex Khomenko Date: Wed, 29 Jan 2025 18:05:40 +0200 Subject: [PATCH 08/18] Query Library: Update API client (#99382) * Add process script * Working version * Use new types * Use new types * Update client * Tweaks * Process multiple specs * Remove 'any' types * Use BASE_URL * Update CODEOWNERS * Fix filename * add openapi * update CODEOWNDER * use JSONeq * Use existing specs * Filter ForAllNamespaces * Add instructions * Switch to tsx * Use openapi-types * Update src path * Expand docs * Update docs * Rename script * codeowners * More docs * Move openapi-types to dev deps * Update error message * Update doc * Fix typo --------- Co-authored-by: Ryan McKinley --- .github/CODEOWNERS | 1 + package.json | 4 +- pkg/tests/apis/openapi_snapshots/README.md | 33 +++- pkg/tests/apis/openapi_test.go | 5 +- .../QueryLibrary/QueryTemplateForm.tsx | 8 +- .../QueryLibrary/QueryTemplatesList.tsx | 9 +- .../QueryTemplatesTable/ActionsCell.tsx | 4 +- .../explore/RichHistory/RichHistory.tsx | 5 +- .../RichHistory/RichHistoryAddToLibrary.tsx | 5 +- .../query-library/api/endpoints.gen.ts | 127 +++++++--------- .../app/features/query-library/api/mappers.ts | 9 +- .../app/features/query-library/api/query.ts | 4 +- .../api/scripts/generate-rtk-apis.ts | 6 +- scripts/process-specs.ts | 143 ++++++++++++++++++ yarn.lock | 8 + 15 files changed, 260 insertions(+), 111 deletions(-) create mode 100644 scripts/process-specs.ts diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 499078f1e7f..82604409275 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -617,6 +617,7 @@ playwright.config.ts @grafana/plugins-platform-frontend /scripts/cleanup-husky.sh @grafana/frontend-ops /scripts/verify-repo-update/ @grafana/grafana-developer-enablement-squad /scripts/generate-rtk-apis.ts @grafana/grafana-frontend-platform +/scripts/process-specs.ts @grafana/grafana-frontend-platform /scripts/generate-alerting-rtk-apis.ts @grafana/alerting-frontend /scripts/levitate-parse-json-report.js @grafana/plugins-platform-frontend /scripts/levitate-show-affected-plugins.js @grafana/plugins-platform-frontend diff --git a/package.json b/package.json index 0ebd64c648a..0456907f286 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,8 @@ "plugin:build:commit": "nx run-many -t build:commit --projects='tag:scope:plugin'", "plugin:build:dev": "nx run-many -t dev --projects='tag:scope:plugin' --maxParallel=100", "generate-icons": "nx run grafana-icons:generate", - "generate-apis": "rtk-query-codegen-openapi ./scripts/generate-rtk-apis.ts" + "process-specs": "npx tsx scripts/process-specs.ts", + "generate-apis": "yarn process-specs && rtk-query-codegen-openapi ./scripts/generate-rtk-apis.ts" }, "grafana": { "whatsNewUrl": "https://grafana.com/docs/grafana/next/whatsnew/whats-new-in-v11-4/", @@ -215,6 +216,7 @@ "ngtemplate-loader": "2.1.0", "node-notifier": "10.0.1", "nx": "19.8.2", + "openapi-types": "^12.1.3", "postcss": "8.5.1", "postcss-loader": "8.1.1", "postcss-reporter": "7.1.0", diff --git a/pkg/tests/apis/openapi_snapshots/README.md b/pkg/tests/apis/openapi_snapshots/README.md index 93fdfdbeba9..7ca313c4be3 100644 --- a/pkg/tests/apis/openapi_snapshots/README.md +++ b/pkg/tests/apis/openapi_snapshots/README.md @@ -1,3 +1,32 @@ -This folder contains a rendered OpenAPI for each group/version +This folder contains a rendered OpenAPI file for each group/version. The “real” OpenAPI is generated by the running server, but the files here are used to build static frontend clients. -The "real" openapi is generated by the running server, but this is used to build static frontend clients +## Generating RTK API Clients + +The RTK API clients are generated from processed OpenAPI files using the `scripts/process-specs.ts` script. The source files are in `pkg/tests/apis/openapi_snapshots`, and the processed files are stored in the `data/openapi` directory. Spec processing happens as part of `yarn generate-apis` task, but can also be triggered separately (see below). + +To generate or update the RTK API clients: + +1. _If generating or updating an RTK client for the first time_, update `scripts/generate-rtk-apis.js` so `schemaFile` points to the processed spec files, for example: + ```typescript + '../public/app/features/dashboards/api/endpoints.gen.ts': { + schemaFile: '../data/openapi/dashboard.grafana.app-v0alpha1.json', + }, + ``` + +2. Generate or update the OpenAPI spec files by running: + ```bash + go test pkg/tests/apis/openapi_test.go + ``` + _If generating an RTK client for a new API_, also add a new group/version of the API to the `groups` slice. If the API is behind a feature toggle, add the toggle to `EnableFeatureToggles` in `pkg/tests/apis/openapi_test.go`. + + +3. Run: + ```bash + yarn generate-apis + ``` + This command generates (or updates) the spec files in the `data/openapi` directory and generates the RTK API clients. + +If you want to process the OpenAPI files without generating the RTK API clients (for example, if you have a separate `generate-rtk-apis` file), run: +```bash +yarn process-specs +``` diff --git a/pkg/tests/apis/openapi_test.go b/pkg/tests/apis/openapi_test.go index ec9cda563ca..a4a7164fa0d 100644 --- a/pkg/tests/apis/openapi_test.go +++ b/pkg/tests/apis/openapi_test.go @@ -63,7 +63,7 @@ func TestIntegrationOpenAPIs(t *testing.T) { dir := "openapi_snapshots" - for _, gv := range []schema.GroupVersion{{ + var groups = []schema.GroupVersion{{ Group: "dashboard.grafana.app", Version: "v0alpha1", }, { @@ -72,7 +72,8 @@ func TestIntegrationOpenAPIs(t *testing.T) { }, { Group: "peakq.grafana.app", Version: "v0alpha1", - }} { + }} + for _, gv := range groups { VerifyOpenAPISnapshots(t, dir, gv, h) } } diff --git a/public/app/features/explore/QueryLibrary/QueryTemplateForm.tsx b/public/app/features/explore/QueryLibrary/QueryTemplateForm.tsx index dfa248707d7..801b9899802 100644 --- a/public/app/features/explore/QueryLibrary/QueryTemplateForm.tsx +++ b/public/app/features/explore/QueryLibrary/QueryTemplateForm.tsx @@ -13,7 +13,6 @@ import { useCreateQueryTemplateMutation, useUpdateQueryTemplateMutation } from ' import { AddQueryTemplateCommand, EditQueryTemplateCommand } from 'app/features/query-library/types'; import { convertAddQueryTemplateCommandToDataQuerySpec } from '../../query-library/api/mappers'; -import { getK8sNamespace } from '../../query-library/api/query'; import { useDatasource } from '../QueryLibrary/utils/useDatasource'; import { QueryTemplateRow } from './QueryTemplatesTable/types'; @@ -64,9 +63,7 @@ export const QueryTemplateForm = ({ onCancel, onSave, queryToAdd, templateData } const handleAddQueryTemplate = async (addQueryTemplateCommand: AddQueryTemplateCommand) => { return addQueryTemplate({ - namespace: getK8sNamespace(), - comGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate: - convertAddQueryTemplateCommandToDataQuerySpec(addQueryTemplateCommand), + queryTemplate: convertAddQueryTemplateCommandToDataQuerySpec(addQueryTemplateCommand), }) .unwrap() .then(() => { @@ -89,9 +86,8 @@ export const QueryTemplateForm = ({ onCancel, onSave, queryToAdd, templateData } const handleEditQueryTemplate = async (editQueryTemplateCommand: EditQueryTemplateCommand) => { return editQueryTemplate({ - namespace: getK8sNamespace(), name: editQueryTemplateCommand.uid, - ioK8SApimachineryPkgApisMetaV1Patch: { + patch: { spec: editQueryTemplateCommand.partialSpec, }, }) diff --git a/public/app/features/explore/QueryLibrary/QueryTemplatesList.tsx b/public/app/features/explore/QueryLibrary/QueryTemplatesList.tsx index a0860add66e..7f238354704 100644 --- a/public/app/features/explore/QueryLibrary/QueryTemplatesList.tsx +++ b/public/app/features/explore/QueryLibrary/QueryTemplatesList.tsx @@ -13,7 +13,6 @@ import { QueryTemplate } from 'app/features/query-library/types'; import { getDatasourceSrv } from '../../plugins/datasource_srv'; import { convertDataQueryResponseToQueryTemplates } from '../../query-library/api/mappers'; -import { getK8sNamespace } from '../../query-library/api/query'; import { QueryLibraryProps } from './QueryLibrary'; import { queryLibraryTrackFilterDatasource } from './QueryLibraryAnalyticsEvents'; @@ -25,13 +24,7 @@ import { searchQueryLibrary } from './utils/search'; interface QueryTemplatesListProps extends QueryLibraryProps {} export function QueryTemplatesList(props: QueryTemplatesListProps) { - const { - data: rawData, - isLoading, - error, - } = useListQueryTemplateQuery({ - namespace: getK8sNamespace(), - }); + const { data: rawData, isLoading, error } = useListQueryTemplateQuery({}); const data = useMemo(() => (rawData ? convertDataQueryResponseToQueryTemplates(rawData) : undefined), [rawData]); const [isModalOpen, setIsModalOpen] = useState(false); const [searchQuery, setSearchQuery] = useState(''); diff --git a/public/app/features/explore/QueryLibrary/QueryTemplatesTable/ActionsCell.tsx b/public/app/features/explore/QueryLibrary/QueryTemplatesTable/ActionsCell.tsx index 7390f030338..88174485be1 100644 --- a/public/app/features/explore/QueryLibrary/QueryTemplatesTable/ActionsCell.tsx +++ b/public/app/features/explore/QueryLibrary/QueryTemplatesTable/ActionsCell.tsx @@ -9,7 +9,6 @@ import { useDeleteQueryTemplateMutation } from 'app/features/query-library'; import { dispatch } from 'app/store/store'; import { ShowConfirmModalEvent } from 'app/types/events'; -import { getK8sNamespace } from '../../../query-library/api/query'; import ExploreRunQueryButton from '../../ExploreRunQueryButton'; import { useQueriesDrawerContext } from '../../QueriesDrawer/QueriesDrawerContext'; import { @@ -38,8 +37,7 @@ function ActionsCell({ queryTemplate, rootDatasourceUid, queryUid }: ActionsCell const performDelete = (queryUid: string) => { deleteQueryTemplate({ name: queryUid, - namespace: getK8sNamespace(), - ioK8SApimachineryPkgApisMetaV1DeleteOptions: {}, + deleteOptions: {}, }); dispatch(notifyApp(createSuccessNotification(t('explore.query-library.query-deleted', 'Query deleted')))); queryLibaryTrackDeleteQuery(); diff --git a/public/app/features/explore/RichHistory/RichHistory.tsx b/public/app/features/explore/RichHistory/RichHistory.tsx index 38a7cb66dcb..b614401cde6 100644 --- a/public/app/features/explore/RichHistory/RichHistory.tsx +++ b/public/app/features/explore/RichHistory/RichHistory.tsx @@ -17,7 +17,6 @@ import { RichHistoryQuery } from 'app/types/explore'; import { supportedFeatures } from '../../../core/history/richHistoryStorageProvider'; import { useListQueryTemplateQuery } from '../../query-library'; -import { getK8sNamespace } from '../../query-library/api/query'; import { Tabs, useQueriesDrawerContext } from '../QueriesDrawer/QueriesDrawerContext'; import { i18n } from '../QueriesDrawer/utils'; import { QueryLibrary } from '../QueryLibrary/QueryLibrary'; @@ -99,9 +98,7 @@ export function RichHistory(props: RichHistoryProps) { .map((eDs) => listOfDatasources.find((ds) => ds.uid === eDs.datasource?.uid)?.name) .filter((name): name is string => !!name); - const { data } = useListQueryTemplateQuery({ - namespace: getK8sNamespace(), - }); + const { data } = useListQueryTemplateQuery({}); const queryTemplatesCount = data?.items?.length ?? 0; const QueryLibraryTab: TabConfig = { diff --git a/public/app/features/explore/RichHistory/RichHistoryAddToLibrary.tsx b/public/app/features/explore/RichHistory/RichHistoryAddToLibrary.tsx index f735180c11a..e6aa0e25143 100644 --- a/public/app/features/explore/RichHistory/RichHistoryAddToLibrary.tsx +++ b/public/app/features/explore/RichHistory/RichHistoryAddToLibrary.tsx @@ -5,7 +5,6 @@ import { Button, Modal } from '@grafana/ui'; import { t } from 'app/core/internationalization'; import { isQueryLibraryEnabled, useListQueryTemplateQuery } from 'app/features/query-library'; -import { getK8sNamespace } from '../../query-library/api/query'; import { queryLibraryTrackAddFromQueryHistory, queryLibraryTrackAddFromQueryHistoryAddModalShown, @@ -17,9 +16,7 @@ type Props = { }; export const RichHistoryAddToLibrary = ({ query }: Props) => { - const { refetch } = useListQueryTemplateQuery({ - namespace: getK8sNamespace(), - }); + const { refetch } = useListQueryTemplateQuery({}); const [isOpen, setIsOpen] = useState(false); const [hasBeenSaved, setHasBeenSaved] = useState(false); diff --git a/public/app/features/query-library/api/endpoints.gen.ts b/public/app/features/query-library/api/endpoints.gen.ts index 9d7a680ed24..133cad6a83e 100644 --- a/public/app/features/query-library/api/endpoints.gen.ts +++ b/public/app/features/query-library/api/endpoints.gen.ts @@ -8,7 +8,7 @@ const injectedRtkApi = api endpoints: (build) => ({ listQueryTemplate: build.query({ query: (queryArg) => ({ - url: `/apis/peakq.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/querytemplates`, + url: `/querytemplates`, params: { pretty: queryArg.pretty, allowWatchBookmarks: queryArg.allowWatchBookmarks, @@ -27,9 +27,9 @@ const injectedRtkApi = api }), createQueryTemplate: build.mutation({ query: (queryArg) => ({ - url: `/apis/peakq.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/querytemplates`, + url: `/querytemplates`, method: 'POST', - body: queryArg.comGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate, + body: queryArg.queryTemplate, params: { pretty: queryArg.pretty, dryRun: queryArg.dryRun, @@ -41,9 +41,9 @@ const injectedRtkApi = api }), deleteQueryTemplate: build.mutation({ query: (queryArg) => ({ - url: `/apis/peakq.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/querytemplates/${queryArg.name}`, + url: `/querytemplates/${queryArg.name}`, method: 'DELETE', - body: queryArg.ioK8SApimachineryPkgApisMetaV1DeleteOptions, + body: queryArg.deleteOptions, params: { pretty: queryArg.pretty, dryRun: queryArg.dryRun, @@ -57,9 +57,9 @@ const injectedRtkApi = api }), updateQueryTemplate: build.mutation({ query: (queryArg) => ({ - url: `/apis/peakq.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/querytemplates/${queryArg.name}`, + url: `/querytemplates/${queryArg.name}`, method: 'PATCH', - body: queryArg.ioK8SApimachineryPkgApisMetaV1Patch, + body: queryArg.patch, params: { pretty: queryArg.pretty, dryRun: queryArg.dryRun, @@ -74,11 +74,8 @@ const injectedRtkApi = api overrideExisting: false, }); export { injectedRtkApi as generatedQueryLibraryApi }; -export type ListQueryTemplateApiResponse = - /** status 200 OK */ ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplateList; +export type ListQueryTemplateApiResponse = /** status 200 OK */ QueryTemplateList; export type ListQueryTemplateApiArg = { - /** object name and auth scope, such as for teams and projects */ - namespace: string; /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ pretty?: string; /** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */ @@ -123,12 +120,10 @@ export type ListQueryTemplateApiArg = { watch?: boolean; }; export type CreateQueryTemplateApiResponse = /** status 200 OK */ - | ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate - | /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate - | /** status 202 Accepted */ ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate; + | QueryTemplate + | /** status 201 Created */ QueryTemplate + | /** status 202 Accepted */ QueryTemplate; export type CreateQueryTemplateApiArg = { - /** object name and auth scope, such as for teams and projects */ - namespace: string; /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ pretty?: string; /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ @@ -137,16 +132,12 @@ export type CreateQueryTemplateApiArg = { fieldManager?: string; /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ fieldValidation?: string; - comGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate: ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate; + queryTemplate: QueryTemplate; }; -export type DeleteQueryTemplateApiResponse = /** status 200 OK */ - | IoK8SApimachineryPkgApisMetaV1Status - | /** status 202 Accepted */ IoK8SApimachineryPkgApisMetaV1Status; +export type DeleteQueryTemplateApiResponse = /** status 200 OK */ Status | /** status 202 Accepted */ Status; export type DeleteQueryTemplateApiArg = { /** name of the QueryTemplate */ name: string; - /** object name and auth scope, such as for teams and projects */ - namespace: string; /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ pretty?: string; /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ @@ -159,16 +150,14 @@ export type DeleteQueryTemplateApiArg = { orphanDependents?: boolean; /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ propagationPolicy?: string; - ioK8SApimachineryPkgApisMetaV1DeleteOptions: IoK8SApimachineryPkgApisMetaV1DeleteOptions; + deleteOptions: DeleteOptions; }; export type UpdateQueryTemplateApiResponse = /** status 200 OK */ - | ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate - | /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate; + | QueryTemplate + | /** status 201 Created */ QueryTemplate; export type UpdateQueryTemplateApiArg = { /** name of the QueryTemplate */ name: string; - /** object name and auth scope, such as for teams and projects */ - namespace: string; /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ pretty?: string; /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ @@ -179,17 +168,17 @@ export type UpdateQueryTemplateApiArg = { fieldValidation?: string; /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ force?: boolean; - ioK8SApimachineryPkgApisMetaV1Patch: IoK8SApimachineryPkgApisMetaV1Patch; + patch: Patch; }; -export type IoK8SApimachineryPkgApisMetaV1Time = string; -export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object; -export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = { +export type Time = string; +export type FieldsV1 = object; +export type ManagedFieldsEntry = { /** APIVersion defines the version of this resource that this field set applies to. The format is "group/version" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted. */ apiVersion?: string; /** FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: "FieldsV1" */ fieldsType?: string; /** FieldsV1 holds the first JSON version format as described in the "FieldsV1" type. */ - fieldsV1?: IoK8SApimachineryPkgApisMetaV1FieldsV1; + fieldsV1?: FieldsV1; /** Manager is an identifier of the workflow managing these fields. */ manager?: string; /** Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'. */ @@ -197,9 +186,9 @@ export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = { /** Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource. */ subresource?: string; /** Time is the timestamp of when the ManagedFields entry was added. The timestamp will also be updated if a field is added, the manager changes any of the owned fields value or removes a field. The timestamp does not update when a field is removed from the entry because another manager took it over. */ - time?: IoK8SApimachineryPkgApisMetaV1Time; + time?: Time; }; -export type IoK8SApimachineryPkgApisMetaV1OwnerReference = { +export type OwnerReference = { /** API version of the referent. */ apiVersion: string; /** If true, AND if the owner has the "foregroundDeletion" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. See https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion for how the garbage collector interacts with this field and enforces the foreground deletion. Defaults to false. To set this field, a user needs "delete" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. */ @@ -213,7 +202,7 @@ export type IoK8SApimachineryPkgApisMetaV1OwnerReference = { /** UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ uid: string; }; -export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = { +export type ObjectMeta = { /** Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations */ annotations?: { [key: string]: string; @@ -221,13 +210,13 @@ export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = { /** CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC. Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */ - creationTimestamp?: IoK8SApimachineryPkgApisMetaV1Time; + creationTimestamp?: Time; /** Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only. */ deletionGracePeriodSeconds?: number; /** DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested. Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */ - deletionTimestamp?: IoK8SApimachineryPkgApisMetaV1Time; + deletionTimestamp?: Time; /** Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list. */ finalizers?: string[]; /** GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server. @@ -243,7 +232,7 @@ export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = { [key: string]: string; }; /** ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like "ci-cd". The set of fields is always in the version that the workflow used when modifying the object. */ - managedFields?: IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry[]; + managedFields?: ManagedFieldsEntry[]; /** Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */ name?: string; /** Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty. @@ -251,7 +240,7 @@ export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = { Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces */ namespace?: string; /** List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. */ - ownerReferences?: IoK8SApimachineryPkgApisMetaV1OwnerReference[]; + ownerReferences?: OwnerReference[]; /** An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources. Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */ @@ -263,7 +252,7 @@ export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = { Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ uid?: string; }; -export type ComGithubGrafanaGrafanaPluginSdkGoExperimentalApisDataV0Alpha1DataQuery = { +export type DataQuery = { /** The datasource */ datasource?: { /** The apiserver version */ @@ -336,13 +325,13 @@ export type ComGithubGrafanaGrafanaPluginSdkGoExperimentalApisDataV0Alpha1DataQu }; [key: string]: any; }; -export type ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplatePosition = { +export type TemplatePosition = { /** End is the byte offset of the end of the variable. */ end: number; /** Start is the byte offset within TargetKey's property of the variable. It is the start location for replacements). */ start: number; }; -export type ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplateVariableReplacement = { +export type TemplateVariableReplacement = { /** How values should be interpolated Possible enum values: @@ -356,48 +345,48 @@ export type ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplateVariableReplaceme /** Path is the location of the property within a target. The format for this is not figured out yet (Maybe JSONPath?). Idea: ["string", int, "string"] where int indicates array offset */ path: string; /** Positions is a list of where to perform the interpolation within targets during render. The first string is the Idx of the target as a string, since openAPI does not support ints as map keys */ - position?: ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplatePosition; + position?: TemplatePosition; }; -export type ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplateTarget = { +export type TemplateTarget = { /** DataType is the returned Dataplane type from the query. */ dataType?: string; /** Query target */ - properties: ComGithubGrafanaGrafanaPluginSdkGoExperimentalApisDataV0Alpha1DataQuery; + properties: DataQuery; /** Variables that will be replaced in the query */ variables: { - [key: string]: ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplateVariableReplacement[]; + [key: string]: TemplateVariableReplacement[]; }; }; -export type ComGithubGrafanaGrafanaPkgApimachineryApisCommonV0Alpha1Unstructured = { +export type Unstructured = { [key: string]: any; }; -export type ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplateTemplateVariable = { +export type TemplateTemplateVariable = { /** DefaultValue is the value to be used when there is no selected value during render. */ defaultValues?: string[]; /** Key is the name of the variable. */ key: string; /** ValueListDefinition is the object definition used by the FE to get a list of possible values to select for render. */ - valueListDefinition?: ComGithubGrafanaGrafanaPkgApimachineryApisCommonV0Alpha1Unstructured; + valueListDefinition?: Unstructured; }; -export type ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplateQueryTemplate = { +export type TemplateQueryTemplate = { /** Longer description for why it is interesting */ description?: string; /** Output variables */ - targets: ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplateTarget[]; + targets: TemplateTarget[]; /** A display name */ title?: string; /** The variables that can be used to render */ - vars?: ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplateTemplateVariable[]; + vars?: TemplateTemplateVariable[]; }; -export type ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate = { +export type QueryTemplate = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ apiVersion?: string; /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ kind?: string; - metadata?: IoK8SApimachineryPkgApisMetaV1ObjectMeta; - spec?: ComGithubGrafanaGrafanaPkgApisQueryV0Alpha1TemplateQueryTemplate; + metadata?: ObjectMeta; + spec?: TemplateQueryTemplate; }; -export type IoK8SApimachineryPkgApisMetaV1ListMeta = { +export type ListMeta = { /** continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. */ continue?: string; /** remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. */ @@ -407,15 +396,15 @@ export type IoK8SApimachineryPkgApisMetaV1ListMeta = { /** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */ selfLink?: string; }; -export type ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplateList = { +export type QueryTemplateList = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ apiVersion?: string; - items?: ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate[]; + items?: QueryTemplate[]; /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ kind?: string; - metadata?: IoK8SApimachineryPkgApisMetaV1ListMeta; + metadata?: ListMeta; }; -export type IoK8SApimachineryPkgApisMetaV1StatusCause = { +export type StatusCause = { /** The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional. Examples: @@ -427,9 +416,9 @@ export type IoK8SApimachineryPkgApisMetaV1StatusCause = { /** A machine-readable description of the cause of the error. If this value is empty there is no information available. */ reason?: string; }; -export type IoK8SApimachineryPkgApisMetaV1StatusDetails = { +export type StatusDetails = { /** The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. */ - causes?: IoK8SApimachineryPkgApisMetaV1StatusCause[]; + causes?: StatusCause[]; /** The group attribute of the resource associated with the status StatusReason. */ group?: string; /** The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ @@ -441,31 +430,31 @@ export type IoK8SApimachineryPkgApisMetaV1StatusDetails = { /** UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ uid?: string; }; -export type IoK8SApimachineryPkgApisMetaV1Status = { +export type Status = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ apiVersion?: string; /** Suggested HTTP return code for this status, 0 if not set. */ code?: number; /** Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type. */ - details?: IoK8SApimachineryPkgApisMetaV1StatusDetails; + details?: StatusDetails; /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ kind?: string; /** A human-readable description of the status of this operation. */ message?: string; /** Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ - metadata?: IoK8SApimachineryPkgApisMetaV1ListMeta; + metadata?: ListMeta; /** A machine-readable description of why this operation is in the "Failure" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it. */ reason?: string; /** Status of the operation. One of: "Success" or "Failure". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status */ status?: string; }; -export type IoK8SApimachineryPkgApisMetaV1Preconditions = { +export type Preconditions = { /** Specifies the target ResourceVersion */ resourceVersion?: string; /** Specifies the target UID. */ uid?: string; }; -export type IoK8SApimachineryPkgApisMetaV1DeleteOptions = { +export type DeleteOptions = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ apiVersion?: string; /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ @@ -479,8 +468,8 @@ export type IoK8SApimachineryPkgApisMetaV1DeleteOptions = { /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ orphanDependents?: boolean; /** Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */ - preconditions?: IoK8SApimachineryPkgApisMetaV1Preconditions; + preconditions?: Preconditions; /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ propagationPolicy?: string; }; -export type IoK8SApimachineryPkgApisMetaV1Patch = object; +export type Patch = object; diff --git a/public/app/features/query-library/api/mappers.ts b/public/app/features/query-library/api/mappers.ts index 01b3f870e2e..2d95b48465f 100644 --- a/public/app/features/query-library/api/mappers.ts +++ b/public/app/features/query-library/api/mappers.ts @@ -2,10 +2,7 @@ import { v4 as uuidv4 } from 'uuid'; import { AddQueryTemplateCommand, QueryTemplate } from '../types'; -import { - ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate, - ListQueryTemplateApiResponse, -} from './endpoints.gen'; +import { ListQueryTemplateApiResponse, QueryTemplate as QT } from './endpoints.gen'; import { API_VERSION, QueryTemplateKinds } from './query'; import { CREATED_BY_KEY } from './types'; @@ -30,9 +27,7 @@ export const convertDataQueryResponseToQueryTemplates = (result: ListQueryTempla }); }; -export const convertAddQueryTemplateCommandToDataQuerySpec = ( - addQueryTemplateCommand: AddQueryTemplateCommand -): ComGithubGrafanaGrafanaPkgApisPeakqV0Alpha1QueryTemplate => { +export const convertAddQueryTemplateCommandToDataQuerySpec = (addQueryTemplateCommand: AddQueryTemplateCommand): QT => { const { title, targets } = addQueryTemplateCommand; return { apiVersion: API_VERSION, diff --git a/public/app/features/query-library/api/query.ts b/public/app/features/query-library/api/query.ts index 1de6d303408..c2ce2bea47c 100644 --- a/public/app/features/query-library/api/query.ts +++ b/public/app/features/query-library/api/query.ts @@ -23,7 +23,7 @@ export const getK8sNamespace = () => config.namespace; * * @alpha */ -export const BASE_URL = `/apis/${API_VERSION}/namespaces/${getK8sNamespace()}/querytemplates`; +export const BASE_URL = `/apis/${API_VERSION}/namespaces/${getK8sNamespace()}`; interface QueryLibraryBackendRequest extends BackendSrvRequest { body?: BackendSrvRequest['data']; @@ -32,7 +32,7 @@ interface QueryLibraryBackendRequest extends BackendSrvRequest { export const baseQuery: BaseQueryFn = async (requestOptions) => { try { const responseObservable = getBackendSrv().fetch({ - url: `${requestOptions.url ?? ''}`, + url: `${BASE_URL}/${requestOptions.url ?? ''}`, showErrorAlert: true, method: requestOptions.method || 'GET', data: requestOptions.body, diff --git a/public/app/features/query-library/api/scripts/generate-rtk-apis.ts b/public/app/features/query-library/api/scripts/generate-rtk-apis.ts index 8b1c90b60c6..1db96f698ea 100644 --- a/public/app/features/query-library/api/scripts/generate-rtk-apis.ts +++ b/public/app/features/query-library/api/scripts/generate-rtk-apis.ts @@ -1,12 +1,12 @@ /** * To generate query library k8s APIs, run: - * `npx rtk-query-codegen-openapi ./public/app/features/query-library/api/scripts/generate-rtk-apis.ts` from the root of the repo + * `yarn process-specs && npx rtk-query-codegen-openapi ./public/app/features/query-library/api/scripts/generate-rtk-apis.ts` from the root of the repo */ import { ConfigFile } from '@rtk-query/codegen-openapi'; import { accessSync } from 'fs'; -const schemaFile = '../../../../../../data/query-library/openapi.json'; +const schemaFile = '../../../../../../data/openapi/peakq.grafana.app-v0alpha1.json'; try { // Check we have the OpenAPI before generating query library RTK APIs, @@ -15,7 +15,7 @@ try { } catch (e) { console.error('\nCould not find OpenAPI definition.\n'); console.error( - 'Please visit /openapi/v3/apis/peakq.grafana.app/v0alpha1 and save the OpenAPI definition to data/query-library/openapi.json\n' + 'Please run go test pkg/tests/apis/openapi_test.go to generate the OpenAPI definition, then try running this script again.\n' ); throw e; } diff --git a/scripts/process-specs.ts b/scripts/process-specs.ts new file mode 100644 index 00000000000..b101f80b74e --- /dev/null +++ b/scripts/process-specs.ts @@ -0,0 +1,143 @@ +import fs from 'fs'; +import { OpenAPIV3 } from 'openapi-types'; +import path from 'path'; + +/** + * Process an OpenAPI spec to remove k8s metadata from names and paths: + * - Remove paths containing "/watch/" as they're deprecated. + * - Remove 'ForAllNamespaces' endpoints + * - Remove the prefix: "/apis///namespaces/{namespace}" from paths. + * - Filter out `namespace` from path parameters. + * - Update all $ref fields to remove k8s metadata from schema names. + * - Simplify schema names in "components.schemas". + */ +function processOpenAPISpec(spec: OpenAPIV3.Document) { + // Create a deep copy of the spec to avoid mutating the original + const newSpec = JSON.parse(JSON.stringify(spec)); + + // Process 'paths' property + const newPaths: Record = {}; + for (const [path, pathItem] of Object.entries(newSpec.paths)) { + // Remove 'watch' paths as they're deprecated / remove empty path items + if (path.includes('/watch/') || !pathItem) { + continue; + } + // Remove the specified part from the path key + const newPathKey = path.replace(/^\/apis\/[^\/]+\/[^\/]+\/namespaces\/\{namespace}/, ''); + + // Process each method in the path (e.g., get, post) + const newPathItem: Record = {}; + for (const method of Object.keys(pathItem)) { + // Filter out the 'namespace' param + if (method === 'parameters' && Array.isArray(pathItem.parameters)) { + pathItem.parameters = pathItem.parameters?.filter((param) => 'name' in param && param.name !== 'namespace'); + } + + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + const operation = pathItem[method as keyof OpenAPIV3.PathItemObject]; + + if ( + typeof operation === 'object' && + operation !== null && + 'operationId' in operation && + operation.operationId?.includes('ForAllNamespaces') + ) { + continue; + } + + updateRefs(operation); + + newPathItem[method] = operation; + } + + newPaths[newPathKey] = newPathItem; + } + newSpec.paths = newPaths; + + // Process 'components.schemas', i.e., type definitions + const newSchemas: Record = {}; + for (const schemaKey of Object.keys(newSpec.components.schemas)) { + const newKey = simplifySchemaName(schemaKey); + + const schemaObject = newSpec.components.schemas[schemaKey]; + updateRefs(schemaObject); + + newSchemas[newKey] = schemaObject; + } + newSpec.components.schemas = newSchemas; + + return newSpec; +} + +/** + * Recursively update all $ref fields to remove k8s metadata from names + */ +function updateRefs(obj: unknown) { + if (Array.isArray(obj)) { + for (const item of obj) { + updateRefs(item); + } + } else if (typeof obj === 'object' && obj !== null) { + if ('$ref' in obj && typeof obj.$ref === 'string') { + const refParts = obj.$ref.split('/'); + const lastRefPart = refParts[refParts.length - 1]; + const newRefName = simplifySchemaName(lastRefPart); + obj.$ref = `#/components/schemas/${newRefName}`; + } + for (const key in obj) { + if (key !== '$ref') { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + updateRefs(obj[key as keyof typeof obj]); + } + } + } +} + +/** + * Simplify a schema name by removing the version prefix if present. + * For example, 'io.k8s.apimachinery.pkg.apis.meta.v1.Time' becomes 'Time'. + */ +function simplifySchemaName(schemaName: string) { + const parts = schemaName.split('.'); + + // Regex to match version segments like 'v1', 'v1beta1', 'v0alpha1', etc. + const versionRegex = /^v\d+[a-zA-Z0-9]*$/; + const versionIndex = parts.findIndex((part) => versionRegex.test(part)); + + if (versionIndex !== -1 && versionIndex + 1 < parts.length) { + return parts.slice(versionIndex + 1).join('.'); + } else { + return schemaName; + } +} + +const sourceDir = path.resolve(__dirname, '../pkg/tests/apis/openapi_snapshots'); +const outputDir = path.resolve(__dirname, '../data/openapi'); + +// Create the output directory if it doesn't exist +if (!fs.existsSync(outputDir)) { + fs.mkdirSync(outputDir, { recursive: true }); +} + +const files = fs.readdirSync(sourceDir).filter((file: string) => file.endsWith('.json')); + +for (const file of files) { + const inputPath = path.join(sourceDir, file); + const outputPath = path.join(outputDir, file); + + console.log(`Processing file "${file}"...`); + + const fileContent = fs.readFileSync(inputPath, 'utf-8'); + + let inputSpec; + try { + inputSpec = JSON.parse(fileContent); + } catch (err) { + console.error(`Invalid JSON file "${file}". Skipping this file.`); + continue; + } + + const outputSpec = processOpenAPISpec(inputSpec); + fs.writeFileSync(outputPath, JSON.stringify(outputSpec, null, 2), 'utf-8'); + console.log(`Processing completed for file "${file}".`); +} diff --git a/yarn.lock b/yarn.lock index 1a4a877ad45..28181b0a8fa 100644 --- a/yarn.lock +++ b/yarn.lock @@ -18013,6 +18013,7 @@ __metadata: nx: "npm:19.8.2" ol: "npm:7.4.0" ol-ext: "npm:4.0.26" + openapi-types: "npm:^12.1.3" pluralize: "npm:^8.0.0" postcss: "npm:8.5.1" postcss-loader: "npm:8.1.1" @@ -23503,6 +23504,13 @@ __metadata: languageName: node linkType: hard +"openapi-types@npm:^12.1.3": + version: 12.1.3 + resolution: "openapi-types@npm:12.1.3" + checksum: 10/9d1d7ed848622b63d0a4c3f881689161b99427133054e46b8e3241e137f1c78bb0031c5d80b420ee79ac2e91d2e727ffd6fc13c553d1b0488ddc8ad389dcbef8 + languageName: node + linkType: hard + "opener@npm:^1.5.1, opener@npm:^1.5.2": version: 1.5.2 resolution: "opener@npm:1.5.2" From be9a7ce9089e94e4f8a8fe1a6e6416ab3288d324 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 29 Jan 2025 16:12:47 +0000 Subject: [PATCH 09/18] Update dependency knip to v5.43.6 (#99766) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index 28181b0a8fa..b315ac4d2b0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -20983,8 +20983,8 @@ __metadata: linkType: hard "knip@npm:^5.10.0": - version: 5.43.1 - resolution: "knip@npm:5.43.1" + version: 5.43.6 + resolution: "knip@npm:5.43.6" dependencies: "@nodelib/fs.walk": "npm:3.0.1" "@snyk/github-codeowners": "npm:1.1.0" @@ -21008,7 +21008,7 @@ __metadata: bin: knip: bin/knip.js knip-bun: bin/knip-bun.js - checksum: 10/068e4145371cf3a4434d07a206eddf8f1d509541482d76252440484562f0b989c11c3efb9c4083d8b5854a90758d3bbcc4a228fe935f6e90ecc9ef2c9f9da8a7 + checksum: 10/d843ed0f5b56baf5c29257308b0cf1956348cfa9d2b9b627420db023a6ccdaf54450f047fe900b263dc10291f395bc3eceef221dc6050e7fd55fb1fbe4fce3a2 languageName: node linkType: hard From 07601bee6f0a8bcb536880361a1a18559639feb0 Mon Sep 17 00:00:00 2001 From: Scott Lepper Date: Wed, 29 Jan 2025 11:48:19 -0500 Subject: [PATCH 10/18] [search] title search wildcard (#99769) --- pkg/services/dashboards/service/dashboard_service.go | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/pkg/services/dashboards/service/dashboard_service.go b/pkg/services/dashboards/service/dashboard_service.go index d56118429d2..bc193b82b18 100644 --- a/pkg/services/dashboards/service/dashboard_service.go +++ b/pkg/services/dashboards/service/dashboard_service.go @@ -1699,17 +1699,9 @@ func (dr *DashboardServiceImpl) searchDashboardsThroughK8sRaw(ctx context.Contex request.Options.Fields = append(request.Options.Fields, req...) } - // note: this does not allow for partial matching - // - // partial matching will be allowed through the api layer for the frontend, - // but is currently not needed by other services in the backend if query.Title != "" { - req := []*resource.Requirement{{ - Key: resource.SEARCH_FIELD_TITLE_SORT, // use title sort to prevent issues with `-` in the title & how bleve searches - Operator: string(selection.In), - Values: []string{strings.ToLower(query.Title)}, - }} - request.Options.Fields = append(request.Options.Fields, req...) + // allow wildcard search + request.Query = "*" + strings.ToLower(query.Title) + "*" } if len(query.Tags) > 0 { From 8f60308e7383a005fca341eb30c059920a5fc3dc Mon Sep 17 00:00:00 2001 From: Ashley Harrison Date: Wed, 29 Jan 2025 17:29:16 +0000 Subject: [PATCH 11/18] Chore: centralise `getK8sNamespace` (#99767) * create new public/app/api folder, expose getK8sNamespace * rename to getAPINamespace --- .github/CODEOWNERS | 1 + public/app/api/utils.ts | 3 +++ .../contact-points/useContactPoints.ts | 17 +++++++---------- .../contact-points/useNotificationTemplates.ts | 13 +++++++------ .../components/mute-timings/useMuteTimings.tsx | 17 +++++++---------- .../useNotificationPolicyRoute.ts | 11 ++++++----- .../features/alerting/unified/home/Insights.tsx | 4 ++-- .../alerting/unified/utils/k8s/utils.ts | 5 ----- public/app/features/apiserver/client.ts | 4 +++- .../features/dashboard/services/SnapshotSrv.ts | 4 +++- public/app/features/query-library/api/query.ts | 7 +++---- public/app/features/query-library/api/user.ts | 5 +++-- public/app/features/scopes/internal/api.ts | 6 ++++-- public/app/features/search/service/unified.ts | 4 +++- 14 files changed, 52 insertions(+), 49 deletions(-) create mode 100644 public/app/api/utils.ts diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 82604409275..1f5d5f25b5e 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -455,6 +455,7 @@ playwright.config.ts @grafana/plugins-platform-frontend # public folder +/public/app/api/ @grafana/grafana-frontend-platform /public/app/core/ @grafana/grafana-frontend-platform /public/app/core/components/TimePicker/ @grafana/grafana-frontend-platform /public/app/core/components/Layers/ @grafana/dataviz-squad diff --git a/public/app/api/utils.ts b/public/app/api/utils.ts new file mode 100644 index 00000000000..51ba395ad43 --- /dev/null +++ b/public/app/api/utils.ts @@ -0,0 +1,3 @@ +import { config } from '@grafana/runtime'; + +export const getAPINamespace = () => config.namespace; diff --git a/public/app/features/alerting/unified/components/contact-points/useContactPoints.ts b/public/app/features/alerting/unified/components/contact-points/useContactPoints.ts index a052f34013e..314a64aa852 100644 --- a/public/app/features/alerting/unified/components/contact-points/useContactPoints.ts +++ b/public/app/features/alerting/unified/components/contact-points/useContactPoints.ts @@ -12,17 +12,14 @@ import { ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Receiver } f import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks'; import { cloudNotifierTypes } from 'app/features/alerting/unified/utils/cloud-alertmanager-notifier-types'; import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource'; -import { - getK8sNamespace, - isK8sEntityProvisioned, - shouldUseK8sApi, -} from 'app/features/alerting/unified/utils/k8s/utils'; +import { isK8sEntityProvisioned, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils'; import { GrafanaManagedContactPoint, GrafanaManagedReceiverConfig, Receiver, } from 'app/plugins/datasource/alertmanager/types'; +import { getAPINamespace } from '../../../../../api/utils'; import { alertmanagerApi } from '../../api/alertmanagerApi'; import { onCallApi } from '../../api/onCallApi'; import { useAsync } from '../../hooks/useAsync'; @@ -117,7 +114,7 @@ const useK8sContactPoints = (...[hookParams, queryOptions]: Parameters { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); const useK8sApi = shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME); const grafanaResponse = useGetContactPointsListQuery(undefined, { @@ -239,7 +236,7 @@ const useGetGrafanaContactPoint = ( { name }: { name: string }, queryOptions?: Parameters[1] ) => { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); const useK8sApi = shouldUseK8sApi(GRAFANA_RULES_SOURCE_NAME); const k8sResponse = useReadNamespacedReceiverQuery( @@ -314,7 +311,7 @@ export function useDeleteContactPoint({ alertmanager }: BaseAlertmanagerArgs) { const [deleteReceiver] = useDeleteNamespacedReceiverMutation(); const deleteFromK8sAPI = useAsync(async ({ name, resourceVersion }: DeleteContactPointArgs) => { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); await deleteReceiver({ name, namespace, @@ -407,7 +404,7 @@ export const useCreateContactPoint = ({ alertmanager }: BaseAlertmanagerArgs) => ? await createOnCallIntegrations(contactPoint) : contactPoint; - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); const contactPointToUse = grafanaContactPointToK8sReceiver(contactPointWithMaybeOnCall); return createGrafanaContactPoint({ @@ -455,7 +452,7 @@ export const useUpdateContactPoint = ({ alertmanager }: BaseAlertmanagerArgs) => ? await createOnCallIntegrations(contactPoint) : contactPoint; - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); const contactPointToUse = grafanaContactPointToK8sReceiver(receiverWithPotentialOnCall, id, resourceVersion); return replaceGrafanaContactPoint({ diff --git a/public/app/features/alerting/unified/components/contact-points/useNotificationTemplates.ts b/public/app/features/alerting/unified/components/contact-points/useNotificationTemplates.ts index 160a28001a6..91739aeca61 100644 --- a/public/app/features/alerting/unified/components/contact-points/useNotificationTemplates.ts +++ b/public/app/features/alerting/unified/components/contact-points/useNotificationTemplates.ts @@ -1,6 +1,7 @@ import { useEffect } from 'react'; import { Validate } from 'react-hook-form'; +import { getAPINamespace } from '../../../../../api/utils'; import { AlertManagerCortexConfig } from '../../../../../plugins/datasource/alertmanager/types'; import { alertmanagerApi } from '../../api/alertmanagerApi'; import { templatesApi } from '../../api/templateApi'; @@ -16,7 +17,7 @@ import { updateNotificationTemplateAction, } from '../../reducers/alertmanager/notificationTemplates'; import { K8sAnnotations, PROVENANCE_NONE } from '../../utils/k8s/constants'; -import { getAnnotation, getK8sNamespace, shouldUseK8sApi } from '../../utils/k8s/utils'; +import { getAnnotation, shouldUseK8sApi } from '../../utils/k8s/utils'; import { ensureDefine } from '../../utils/templates'; import { TemplateFormValues } from '../receivers/TemplateForm'; @@ -46,7 +47,7 @@ export function useNotificationTemplates({ alertmanager }: BaseAlertmanagerArgs) const k8sApiSupported = shouldUseK8sApi(alertmanager); const k8sApiTemplatesRequestState = useListNamespacedTemplateGroupQuery( - { namespace: getK8sNamespace() }, + { namespace: getAPINamespace() }, { skip: !k8sApiSupported, selectFromResult: (state) => ({ @@ -131,7 +132,7 @@ export function useGetNotificationTemplate({ alertmanager, uid }: GetTemplatePar // What are pros and cons of each? useEffect(() => { if (k8sApiSupported) { - fetchTemplate({ namespace: getK8sNamespace(), name: uid }); + fetchTemplate({ namespace: getAPINamespace(), name: uid }); } else { fetchAmConfig(alertmanager); } @@ -164,7 +165,7 @@ export function useCreateNotificationTemplate({ alertmanager }: BaseAlertmanager const content = ensureDefine(templateValues.title, templateValues.content); return createNamespacedTemplateGroup({ - namespace: getK8sNamespace(), + namespace: getAPINamespace(), comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1TemplateGroup: { spec: { title: templateValues.title, content }, metadata: {}, @@ -195,7 +196,7 @@ export function useUpdateNotificationTemplate({ alertmanager }: BaseAlertmanager const content = ensureDefine(patch.title, patch.content); return replaceNamespacedTemplateGroup({ - namespace: getK8sNamespace(), + namespace: getAPINamespace(), name: template.uid, comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1TemplateGroup: { spec: { title: patch.title, content }, @@ -218,7 +219,7 @@ export function useDeleteNotificationTemplate({ alertmanager }: BaseAlertmanager const deleteUsingK8sApi = useAsync(({ uid }: { uid: string }) => { return deleteNamespacedTemplateGroup({ - namespace: getK8sNamespace(), + namespace: getAPINamespace(), name: uid, ioK8SApimachineryPkgApisMetaV1DeleteOptions: {}, }).unwrap(); diff --git a/public/app/features/alerting/unified/components/mute-timings/useMuteTimings.tsx b/public/app/features/alerting/unified/components/mute-timings/useMuteTimings.tsx index dd365218c47..fb873f967b3 100644 --- a/public/app/features/alerting/unified/components/mute-timings/useMuteTimings.tsx +++ b/public/app/features/alerting/unified/components/mute-timings/useMuteTimings.tsx @@ -10,13 +10,10 @@ import { import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks'; import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource'; import { PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants'; -import { - getK8sNamespace, - isK8sEntityProvisioned, - shouldUseK8sApi, -} from 'app/features/alerting/unified/utils/k8s/utils'; +import { isK8sEntityProvisioned, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils'; import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types'; +import { getAPINamespace } from '../../../../../api/utils'; import { useAsync } from '../../hooks/useAsync'; import { useProduceNewAlertmanagerConfiguration } from '../../hooks/useProduceNewAlertmanagerConfig'; import { @@ -114,7 +111,7 @@ export const useMuteTimings = ({ alertmanager, skip }: BaseAlertmanagerArgs & Sk return; } if (useK8sApi) { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); getGrafanaTimeIntervals({ namespace }); } else { getAlertmanagerTimeIntervals(alertmanager); @@ -140,7 +137,7 @@ export const useCreateMuteTiming = ({ alertmanager }: BaseAlertmanagerArgs) => { const [updateConfiguration] = useProduceNewAlertmanagerConfiguration(); const addToK8sAPI = useAsync(({ interval }: CreateUpdateMuteTimingArgs) => { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); return createGrafanaTimeInterval({ namespace, @@ -202,7 +199,7 @@ export const useGetMuteTiming = ({ alertmanager, name: nameToFind }: BaseAlertma useEffect(() => { if (useK8sApi) { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); getGrafanaTimeInterval({ namespace, fieldSelector: `spec.name=${nameToFind}` }, true); } else { getAlertmanagerTimeInterval(alertmanager, true); @@ -228,7 +225,7 @@ export const useUpdateMuteTiming = ({ alertmanager }: BaseAlertmanagerArgs) => { const updateToK8sAPI = useAsync( async ({ interval, originalName }: CreateUpdateMuteTimingArgs & { originalName: string }) => { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); return replaceGrafanaTimeInterval({ name: originalName, @@ -267,7 +264,7 @@ export const useDeleteMuteTiming = ({ alertmanager }: BaseAlertmanagerArgs) => { }); const deleteFromK8sAPI = useAsync(async ({ name }: DeleteMuteTimingArgs) => { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); await deleteGrafanaTimeInterval({ name, namespace, diff --git a/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.ts b/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.ts index 4b1e2243c8e..f927fc49d70 100644 --- a/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.ts +++ b/public/app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute.ts @@ -4,6 +4,7 @@ import memoize from 'micro-memoize'; import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks'; import { MatcherOperator, ROUTES_META_SYMBOL, Route } from 'app/plugins/datasource/alertmanager/types'; +import { getAPINamespace } from '../../../../../api/utils'; import { alertmanagerApi } from '../../api/alertmanagerApi'; import { useAsync } from '../../hooks/useAsync'; import { useProduceNewAlertmanagerConfiguration } from '../../hooks/useProduceNewAlertmanagerConfig'; @@ -21,7 +22,7 @@ import { import { FormAmRoute } from '../../types/amroutes'; import { addUniqueIdentifierToRoute } from '../../utils/amroutes'; import { PROVENANCE_NONE, ROOT_ROUTE_NAME } from '../../utils/k8s/constants'; -import { getK8sNamespace, isK8sEntityProvisioned, shouldUseK8sApi } from '../../utils/k8s/utils'; +import { isK8sEntityProvisioned, shouldUseK8sApi } from '../../utils/k8s/utils'; import { INHERITABLE_KEYS, InheritableProperties } from '../../utils/notification-policies'; import { InsertPosition, @@ -45,7 +46,7 @@ export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArg const k8sApiSupported = shouldUseK8sApi(alertmanager); const k8sRouteQuery = useListNamespacedRoutingTreeQuery( - { namespace: getK8sNamespace() }, + { namespace: getAPINamespace() }, { skip: skip || !k8sApiSupported, selectFromResult: (result) => { @@ -92,7 +93,7 @@ export function useUpdateExistingNotificationPolicy({ alertmanager }: BaseAlertm const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery(); const updateUsingK8sApi = useAsync(async (update: Partial) => { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); const result = await listNamespacedRoutingTree({ namespace }); const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : []; @@ -128,7 +129,7 @@ export function useDeleteNotificationPolicy({ alertmanager }: BaseAlertmanagerAr const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation(); const deleteFromK8sApi = useAsync(async (id: string) => { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); const result = await listNamespacedRoutingTree({ namespace }); const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : []; @@ -173,7 +174,7 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs) referenceRouteIdentifier: string; insertPosition: InsertPosition; }) => { - const namespace = getK8sNamespace(); + const namespace = getAPINamespace(); const result = await listNamespacedRoutingTree({ namespace }); const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : []; diff --git a/public/app/features/alerting/unified/home/Insights.tsx b/public/app/features/alerting/unified/home/Insights.tsx index f98cd51622e..9d85797751b 100644 --- a/public/app/features/alerting/unified/home/Insights.tsx +++ b/public/app/features/alerting/unified/home/Insights.tsx @@ -16,7 +16,7 @@ import { } from '@grafana/scenes'; import { Icon, Text, Tooltip } from '@grafana/ui'; -import { config } from '../../../../core/config'; +import { getAPINamespace } from '../../../../api/utils'; import { SectionFooter } from '../insights/SectionFooter'; import { SectionSubheader } from '../insights/SectionSubheader'; import { getActiveGrafanaAlertsScene } from '../insights/grafana/Active'; @@ -95,7 +95,7 @@ export const PANEL_STYLES = { minHeight: 300 }; const THIS_WEEK_TIME_RANGE = new SceneTimeRange({ from: 'now-1w', to: 'now' }); -const namespace = config.namespace; +const namespace = getAPINamespace(); export const INSTANCE_ID = namespace.includes('stacks-') ? namespace.replace('stacks-', '') : undefined; diff --git a/public/app/features/alerting/unified/utils/k8s/utils.ts b/public/app/features/alerting/unified/utils/k8s/utils.ts index 2857552ecc5..0aec7c1dd52 100644 --- a/public/app/features/alerting/unified/utils/k8s/utils.ts +++ b/public/app/features/alerting/unified/utils/k8s/utils.ts @@ -3,11 +3,6 @@ import { IoK8SApimachineryPkgApisMetaV1ObjectMeta } from 'app/features/alerting/ import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource'; import { K8sAnnotations, PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants'; -/** - * Get the correct namespace to use when using the K8S API. - */ -export const getK8sNamespace = () => config.namespace; - /** * Should we call the kubernetes-style API for managing alertmanager entities? * diff --git a/public/app/features/apiserver/client.ts b/public/app/features/apiserver/client.ts index ba647d4cf6c..90a5004b8b0 100644 --- a/public/app/features/apiserver/client.ts +++ b/public/app/features/apiserver/client.ts @@ -3,6 +3,8 @@ import { Observable, from, retry, catchError, filter, map, mergeMap } from 'rxjs import { config, getBackendSrv } from '@grafana/runtime'; import { contextSrv } from 'app/core/core'; +import { getAPINamespace } from '../../api/utils'; + import { ListOptions, ListOptionsFieldSelector, @@ -29,7 +31,7 @@ export class ScopedResourceClient implements readonly url: string; constructor(gvr: GroupVersionResource, namespaced = true) { - const ns = namespaced ? `namespaces/${config.namespace}/` : ''; + const ns = namespaced ? `namespaces/${getAPINamespace()}/` : ''; this.url = `/apis/${gvr.group}/${gvr.version}/${ns}${gvr.resource}`; } diff --git a/public/app/features/dashboard/services/SnapshotSrv.ts b/public/app/features/dashboard/services/SnapshotSrv.ts index 5467542ab2b..1ca4894de22 100644 --- a/public/app/features/dashboard/services/SnapshotSrv.ts +++ b/public/app/features/dashboard/services/SnapshotSrv.ts @@ -4,6 +4,8 @@ import { config, getBackendSrv, FetchResponse } from '@grafana/runtime'; import { contextSrv } from 'app/core/core'; import { DashboardDataDTO, DashboardDTO } from 'app/types'; +import { getAPINamespace } from '../../../api/utils'; + // Used in the snapshot list export interface Snapshot { key: string; @@ -91,7 +93,7 @@ class K8sAPI implements DashboardSnapshotSrv { readonly url: string; constructor() { - this.url = `/apis/${this.apiVersion}/namespaces/${config.namespace}/dashboardsnapshots`; + this.url = `/apis/${this.apiVersion}/namespaces/${getAPINamespace()}/dashboardsnapshots`; } async create(cmd: SnapshotCreateCommand) { diff --git a/public/app/features/query-library/api/query.ts b/public/app/features/query-library/api/query.ts index c2ce2bea47c..610c1556387 100644 --- a/public/app/features/query-library/api/query.ts +++ b/public/app/features/query-library/api/query.ts @@ -1,9 +1,10 @@ import { BaseQueryFn } from '@reduxjs/toolkit/query/react'; import { lastValueFrom } from 'rxjs'; -import { config } from '@grafana/runtime'; import { BackendSrvRequest, getBackendSrv, isFetchError } from '@grafana/runtime/src/services/backendSrv'; +import { getAPINamespace } from '../../../api/utils'; + /** * @alpha */ @@ -16,14 +17,12 @@ export enum QueryTemplateKinds { QueryTemplate = 'QueryTemplate', } -export const getK8sNamespace = () => config.namespace; - /** * Query Library is an experimental feature. API (including the URL path) will likely change. * * @alpha */ -export const BASE_URL = `/apis/${API_VERSION}/namespaces/${getK8sNamespace()}`; +export const BASE_URL = `/apis/${API_VERSION}/namespaces/${getAPINamespace()}`; interface QueryLibraryBackendRequest extends BackendSrvRequest { body?: BackendSrvRequest['data']; diff --git a/public/app/features/query-library/api/user.ts b/public/app/features/query-library/api/user.ts index 640b04aa1dd..6b8ba4c9437 100644 --- a/public/app/features/query-library/api/user.ts +++ b/public/app/features/query-library/api/user.ts @@ -1,6 +1,7 @@ import { getBackendSrv } from '@grafana/runtime'; -import { getK8sNamespace } from './query'; +import { getAPINamespace } from '../../../api/utils'; + import { UserDataQueryResponse } from './types'; /** @@ -11,7 +12,7 @@ export const API_VERSION = 'iam.grafana.app/v0alpha1'; /** * @alpha */ -const BASE_URL = `apis/${API_VERSION}/namespaces/${getK8sNamespace()}/display`; +const BASE_URL = `apis/${API_VERSION}/namespaces/${getAPINamespace()}/display`; export async function getUserInfo(url?: string): Promise { const userInfo = await getBackendSrv().get(`${BASE_URL}${url}`); diff --git a/public/app/features/scopes/internal/api.ts b/public/app/features/scopes/internal/api.ts index b1f1ceaf869..1b0dae4cce9 100644 --- a/public/app/features/scopes/internal/api.ts +++ b/public/app/features/scopes/internal/api.ts @@ -1,13 +1,15 @@ import { Scope, ScopeDashboardBinding, ScopeNode, ScopeSpec } from '@grafana/data'; -import { config, getBackendSrv } from '@grafana/runtime'; +import { getBackendSrv } from '@grafana/runtime'; import { ScopedResourceClient } from 'app/features/apiserver/client'; +import { getAPINamespace } from '../../../api/utils'; + import { NodeReason, NodesMap, SelectedScope, TreeScope } from './types'; import { getBasicScope, mergeScopes } from './utils'; const group = 'scope.grafana.app'; const version = 'v0alpha1'; -const namespace = config.namespace ?? 'default'; +const namespace = getAPINamespace(); const nodesEndpoint = `/apis/${group}/${version}/namespaces/${namespace}/find/scope_node_children`; const dashboardsEndpoint = `/apis/${group}/${version}/namespaces/${namespace}/find/scope_dashboard_bindings`; diff --git a/public/app/features/search/service/unified.ts b/public/app/features/search/service/unified.ts index 3ed44146c35..700cf566314 100644 --- a/public/app/features/search/service/unified.ts +++ b/public/app/features/search/service/unified.ts @@ -4,6 +4,8 @@ import { DataFrame, DataFrameView, getDisplayProcessor, SelectableValue, toDataF import { config, getBackendSrv } from '@grafana/runtime'; import { TermCount } from 'app/core/components/TagFilter/TagFilter'; +import { getAPINamespace } from '../../../api/utils'; + import { DashboardQueryResult, GrafanaSearcher, @@ -18,7 +20,7 @@ import { replaceCurrentFolderQuery } from './utils'; // and that it can not serve any search requests. We are temporarily using the old SQL Search API as a fallback when that happens. const loadingFrameName = 'Loading'; -const searchURI = `apis/dashboard.grafana.app/v0alpha1/namespaces/${config.namespace}/search`; +const searchURI = `apis/dashboard.grafana.app/v0alpha1/namespaces/${getAPINamespace()}/search`; export type SearchHit = { resource: string; // dashboards | folders From 243ce03b93792c464f59a0949427f034a20bd71a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 29 Jan 2025 17:29:43 +0000 Subject: [PATCH 12/18] Update dependency @types/babel__preset-env to v7.10.0 (#99768) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index b315ac4d2b0..9550b4ecfe0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8934,9 +8934,9 @@ __metadata: linkType: hard "@types/babel__preset-env@npm:^7": - version: 7.9.7 - resolution: "@types/babel__preset-env@npm:7.9.7" - checksum: 10/624425a84d9149aec04795fed6b1ac2f27dfd5d7976fde479bb1a4d754de34c92cdc28a1a373a5826382a68127b536420a0e090aa5fae522cb62724b7a571cb5 + version: 7.10.0 + resolution: "@types/babel__preset-env@npm:7.10.0" + checksum: 10/7d4d12758d89708afe327079d7d7580e8af3292295f087b8a9a48e12ac1d90aadc18ac3bc00f9b0cbc8778f3ce9fe778801d4d49b7691a75e3f13a901b69fd07 languageName: node linkType: hard From 7d4895c3c9601049943be9a888cd2931abe6abbe Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 29 Jan 2025 18:53:30 +0100 Subject: [PATCH 13/18] Alerting: Use exponential backoff in the remote Alertmanager readiness check (#99756) * Alerting: Use exponential backoff in the remote Alertmanager readiness check * fix capitalized error * remove unnecessary 'for' * refactor, use time.After() instead of channel --- pkg/services/ngalert/remote/alertmanager.go | 14 +-- .../ngalert/remote/client/alertmanager.go | 106 +++++++++--------- 2 files changed, 56 insertions(+), 64 deletions(-) diff --git a/pkg/services/ngalert/remote/alertmanager.go b/pkg/services/ngalert/remote/alertmanager.go index 82b222713ef..5928c8f6dcb 100644 --- a/pkg/services/ngalert/remote/alertmanager.go +++ b/pkg/services/ngalert/remote/alertmanager.go @@ -232,19 +232,15 @@ func (am *Alertmanager) ApplyConfig(ctx context.Context, config *models.AlertCon } func (am *Alertmanager) checkReadiness(ctx context.Context) error { - ready, err := am.amClient.IsReadyWithBackoff(ctx) + err := am.amClient.IsReadyWithBackoff(ctx) if err != nil { return err } - if ready { - am.log.Debug("Alertmanager readiness check successful") - am.metrics.LastReadinessCheck.SetToCurrentTime() - am.ready = true - return nil - } - - return notifier.ErrAlertmanagerNotReady + am.log.Debug("Alertmanager readiness check successful") + am.metrics.LastReadinessCheck.SetToCurrentTime() + am.ready = true + return nil } // CompareAndSendConfiguration checks whether a given configuration is being used by the remote Alertmanager. diff --git a/pkg/services/ngalert/remote/client/alertmanager.go b/pkg/services/ngalert/remote/client/alertmanager.go index bc228884460..d7cf67ec41a 100644 --- a/pkg/services/ngalert/remote/client/alertmanager.go +++ b/pkg/services/ngalert/remote/client/alertmanager.go @@ -66,69 +66,65 @@ func (am *Alertmanager) GetAuthedClient() client.Requester { } // IsReadyWithBackoff executes a readiness check against the `/-/ready` Alertmanager endpoint. -// If it takes more than 10s to get a response back - we abort the check. -func (am *Alertmanager) IsReadyWithBackoff(ctx context.Context) (bool, error) { - ctx, cancel := context.WithCancel(ctx) +// It uses exponential backoff (100ms * 2^attempts) with a 10s timeout. +func (am *Alertmanager) IsReadyWithBackoff(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() - readyURL := am.url.JoinPath(alertmanagerAPIMountPath, alertmanagerReadyPath) - - attempt := func() (int, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, readyURL.String(), nil) - if err != nil { - return 0, fmt.Errorf("error creating the readiness request: %w", err) - } - - res, err := am.httpClient.Do(req) - if err != nil { - return 0, fmt.Errorf("error performing the readiness check: %w", err) - } - - defer func() { - if err := res.Body.Close(); err != nil { - am.logger.Warn("Error closing response body", "err", err) - } - }() - - return res.StatusCode, nil - } - - var attempts int - ticker := time.NewTicker(100 * time.Millisecond) - deadlineCh := time.After(10 * time.Second) - defer ticker.Stop() - - for { + var wait time.Duration + for attempt := 1; ; attempt++ { select { - case <-ticker.C: - attempts++ - status, err := attempt() + case <-ctx.Done(): + return fmt.Errorf("readiness check timed out") + case <-time.After(wait): + wait = time.Duration(100<= 400 && status < 500 { - if status == http.StatusNotAcceptable { - // Mimir returns a 406 when the Alertmanager for the tenant is not running. - // This is expected if the Grafana Alertmanager configuration is default or not promoted. - // We can still use the endpoints to store and retrieve configuration/state. - am.logger.Debug("Remote Alertmanager not initialized for tenant", "attempt", attempts, "status", status) - return true, nil - } - - am.logger.Debug("Ready check failed with non-retriable status code", "attempt", attempts, "status", status) - return false, fmt.Errorf("ready check failed with non-retriable status code %d", status) - } - am.logger.Debug("Ready check failed, status code is not 200", "attempt", attempts, "status", status, "err", err) - continue + if status == http.StatusOK { + return nil } - return true, nil - case <-deadlineCh: - cancel() - return false, fmt.Errorf("ready check timed out after %d attempts", attempts) + if status == http.StatusNotAcceptable { + // Mimir returns a 406 when the Alertmanager for the tenant is not running. + // This is expected if the Grafana Alertmanager configuration is default or not promoted. + // We can still use the endpoints to store and retrieve configuration/state. + am.logger.Debug("Remote Alertmanager not initialized for tenant") + return nil + } + + if status >= 400 && status < 500 { + return fmt.Errorf("readiness check failed on attempt %d with non-retriable status code %d", attempt, status) + } + am.logger.Debug("Readiness check failed, status code is not 200", "attempt", attempt, "status", status, "err", err) } } } + +func (am *Alertmanager) checkReadiness(ctx context.Context) (int, error) { + req, err := http.NewRequestWithContext( + ctx, + http.MethodGet, + am.url.JoinPath(alertmanagerAPIMountPath, alertmanagerReadyPath).String(), + nil, + ) + if err != nil { + return 0, fmt.Errorf("error creating the readiness request: %w", err) + } + + res, err := am.httpClient.Do(req) + if err != nil { + return 0, fmt.Errorf("error performing the readiness check: %w", err) + } + + defer func() { + if err := res.Body.Close(); err != nil { + am.logger.Warn("Error closing response body", "err", err) + } + }() + + return res.StatusCode, nil +} From 49bd8a608ec941f38bad58c7e3a1b368ca5ab3e1 Mon Sep 17 00:00:00 2001 From: Gilles De Mey Date: Wed, 29 Jan 2025 18:54:41 +0100 Subject: [PATCH 14/18] Alerting: Fix fieldSelector encoding (#99751) Co-authored-by: Sonia Aguilar --- .../mute-timings/useMuteTimings.tsx | 9 +++++-- .../alerting/unified/utils/k8s/utils.test.ts | 27 +++++++++++++++++++ .../alerting/unified/utils/k8s/utils.ts | 8 ++++++ 3 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 public/app/features/alerting/unified/utils/k8s/utils.test.ts diff --git a/public/app/features/alerting/unified/components/mute-timings/useMuteTimings.tsx b/public/app/features/alerting/unified/components/mute-timings/useMuteTimings.tsx index fb873f967b3..edf6fd8fd05 100644 --- a/public/app/features/alerting/unified/components/mute-timings/useMuteTimings.tsx +++ b/public/app/features/alerting/unified/components/mute-timings/useMuteTimings.tsx @@ -10,7 +10,11 @@ import { import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks'; import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource'; import { PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants'; -import { isK8sEntityProvisioned, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils'; +import { + encodeFieldSelector, + isK8sEntityProvisioned, + shouldUseK8sApi, +} from 'app/features/alerting/unified/utils/k8s/utils'; import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types'; import { getAPINamespace } from '../../../../../api/utils'; @@ -200,7 +204,8 @@ export const useGetMuteTiming = ({ alertmanager, name: nameToFind }: BaseAlertma useEffect(() => { if (useK8sApi) { const namespace = getAPINamespace(); - getGrafanaTimeInterval({ namespace, fieldSelector: `spec.name=${nameToFind}` }, true); + const entityName = encodeFieldSelector(nameToFind); + getGrafanaTimeInterval({ namespace, fieldSelector: `spec.name=${entityName}` }, true); } else { getAlertmanagerTimeInterval(alertmanager, true); } diff --git a/public/app/features/alerting/unified/utils/k8s/utils.test.ts b/public/app/features/alerting/unified/utils/k8s/utils.test.ts new file mode 100644 index 00000000000..a04a1ea16ec --- /dev/null +++ b/public/app/features/alerting/unified/utils/k8s/utils.test.ts @@ -0,0 +1,27 @@ +import { encodeFieldSelector } from './utils'; + +describe('encodeFieldSelector', () => { + it('should escape backslashes', () => { + expect(encodeFieldSelector('some\\value')).toBe('some\\\\value'); + }); + + it('should escape equal signs', () => { + expect(encodeFieldSelector('key=value')).toBe('key\\=value'); + }); + + it('should handle strings with no backslashes or equal signs', () => { + expect(encodeFieldSelector('simplevalue')).toBe('simplevalue'); + }); + + it('should handle strings with multiple equal signs', () => { + expect(encodeFieldSelector('key=value=another=value')).toBe('key\\=value\\=another\\=value'); + }); + + it('should escape commas', () => { + expect(encodeFieldSelector('value,another')).toBe('value\\,another'); + }); + + it('should escape mixed special characters', () => { + expect(encodeFieldSelector('foo=bar,bar=baz,qux\\foo')).toBe('foo\\=bar\\,bar\\=baz\\,qux\\\\foo'); + }); +}); diff --git a/public/app/features/alerting/unified/utils/k8s/utils.ts b/public/app/features/alerting/unified/utils/k8s/utils.ts index 0aec7c1dd52..69444f02b2c 100644 --- a/public/app/features/alerting/unified/utils/k8s/utils.ts +++ b/public/app/features/alerting/unified/utils/k8s/utils.ts @@ -43,3 +43,11 @@ export const canAdminEntity = (k8sEntity: EntityToCheck) => export const canDeleteEntity = (k8sEntity: EntityToCheck) => getAnnotation(k8sEntity, K8sAnnotations.AccessDelete) === 'true'; + +/** + * Escape \ and = characters for field selectors. + * The Kubernetes API Machinery will decode those automatically. + */ +export const encodeFieldSelector = (value: string): string => { + return value.replaceAll(/\\/g, '\\\\').replaceAll(/\=/g, '\\=').replaceAll(/,/g, '\\,'); +}; From 1048e23872e3d5df42afe184b4bb0cf4025da0f6 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 29 Jan 2025 17:57:54 +0000 Subject: [PATCH 15/18] Update dependency react-i18next to v15.4.0 (#99772) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index 9550b4ecfe0..02276433807 100644 --- a/yarn.lock +++ b/yarn.lock @@ -26013,8 +26013,8 @@ __metadata: linkType: hard "react-i18next@npm:^15.0.0": - version: 15.2.0 - resolution: "react-i18next@npm:15.2.0" + version: 15.4.0 + resolution: "react-i18next@npm:15.4.0" dependencies: "@babel/runtime": "npm:^7.25.0" html-parse-stringify: "npm:^3.0.1" @@ -26026,7 +26026,7 @@ __metadata: optional: true react-native: optional: true - checksum: 10/9b2937f7beab763c494d55a801f21bfdbfe98e9509994c350d24fa404ded573f41e8607eeba290c686d5877d34f0ddefe48e9d6876720d5ed0e1243bcdd5dda6 + checksum: 10/4b3666d819f01cf96a256af4419b26938d314e33c6388eafccc29f67ad02994e5d53e7bf82eac656cade7f7bcd04f4a237f0b293165d7eda91d62e3fde605a38 languageName: node linkType: hard From 1795a2b4e3a88d0fcdf562d6fdfffbd47ef8bdab Mon Sep 17 00:00:00 2001 From: Kristina Date: Wed, 29 Jan 2025 13:02:56 -0600 Subject: [PATCH 16/18] Bar Gauge: Add extra padding for scrollbar (#99722) * Add extra padding in bar gauge if scroll exists * Add thin scroll bars, and fix test * add comment about height calculation --- .../src/components/BarGauge/BarGauge.test.tsx | 1 + .../src/components/BarGauge/BarGauge.tsx | 29 ++++++++++++++++--- .../components/VizRepeater/VizRepeater.tsx | 1 + .../plugins/panel/bargauge/BarGaugePanel.tsx | 6 +++- 4 files changed, 32 insertions(+), 5 deletions(-) diff --git a/packages/grafana-ui/src/components/BarGauge/BarGauge.test.tsx b/packages/grafana-ui/src/components/BarGauge/BarGauge.test.tsx index c8b76542ba5..df45a86942a 100644 --- a/packages/grafana-ui/src/components/BarGauge/BarGauge.test.tsx +++ b/packages/grafana-ui/src/components/BarGauge/BarGauge.test.tsx @@ -56,6 +56,7 @@ function getProps(propOverrides?: Partial): Props { theme, orientation: VizOrientation.Horizontal, namePlacement: BarGaugeNamePlacement.Auto, + isOverflow: false, }; Object.assign(props, propOverrides); diff --git a/packages/grafana-ui/src/components/BarGauge/BarGauge.tsx b/packages/grafana-ui/src/components/BarGauge/BarGauge.tsx index 1048d86253a..043578ff10a 100644 --- a/packages/grafana-ui/src/components/BarGauge/BarGauge.tsx +++ b/packages/grafana-ui/src/components/BarGauge/BarGauge.tsx @@ -34,6 +34,7 @@ const MAX_VALUE_WIDTH = 150; const TITLE_LINE_HEIGHT = 1.5; const VALUE_LINE_HEIGHT = 1; const VALUE_LEFT_PADDING = 10; +const VALUE_RIGHT_OVERFLOW_PADDING = 15; export interface Props extends Themeable2 { height: number; @@ -52,6 +53,7 @@ export interface Props extends Themeable2 { alignmentFactors?: DisplayValueAlignmentFactors; valueDisplayMode?: BarGaugeValueMode; namePlacement?: BarGaugeNamePlacement; + isOverflow: boolean; } export class BarGauge extends PureComponent { @@ -73,6 +75,7 @@ export class BarGauge extends PureComponent { }, itemSpacing: 8, showUnfilled: true, + isOverflow: false, }; render() { @@ -145,6 +148,7 @@ export class BarGauge extends PureComponent { text, valueDisplayMode, theme, + isOverflow, } = this.props; const { valueHeight, valueWidth, maxBarHeight, maxBarWidth, wrapperWidth, wrapperHeight } = calculateBarAndValueDimensions(this.props); @@ -160,7 +164,15 @@ export class BarGauge extends PureComponent { const valueColor = getTextValueColor(this.props); const valueToBaseSizeOn = alignmentFactors ? alignmentFactors : value; - const valueStyles = getValueStyles(valueToBaseSizeOn, valueColor, valueWidth, valueHeight, orientation, text); + const valueStyles = getValueStyles( + valueToBaseSizeOn, + valueColor, + valueWidth, + valueHeight, + orientation, + isOverflow, + text + ); const containerStyles: CSSProperties = { width: `${wrapperWidth}px`, @@ -486,7 +498,7 @@ export function getValuePercent(value: number, minValue: number, maxValue: numbe * Only exported to for unit test */ export function getBasicAndGradientStyles(props: Props): BasicAndGradientStyles { - const { displayMode, field, value, alignmentFactors, orientation, theme, text } = props; + const { displayMode, field, value, alignmentFactors, orientation, theme, text, isOverflow } = props; const { valueWidth, valueHeight, maxBarHeight, maxBarWidth } = calculateBarAndValueDimensions(props); const minValue = field.min ?? GAUGE_DEFAULT_MINIMUM; @@ -496,7 +508,15 @@ export function getBasicAndGradientStyles(props: Props): BasicAndGradientStyles const barColor = value.color ?? FALLBACK_COLOR; const valueToBaseSizeOn = alignmentFactors ? alignmentFactors : value; - const valueStyles = getValueStyles(valueToBaseSizeOn, textColor, valueWidth, valueHeight, orientation, text); + const valueStyles = getValueStyles( + valueToBaseSizeOn, + textColor, + valueWidth, + valueHeight, + orientation, + isOverflow, + text + ); const isBasic = displayMode === 'basic'; const wrapperStyles: CSSProperties = { @@ -663,6 +683,7 @@ function getValueStyles( width: number, height: number, orientation: VizOrientation, + isOverflow: boolean, text?: VizTextDisplayOptions ): CSSProperties { const styles: CSSProperties = { @@ -688,7 +709,7 @@ function getValueStyles( calculateFontSize(formattedValueString, textWidth - VALUE_LEFT_PADDING * 2, height, VALUE_LINE_HEIGHT); styles.justifyContent = `flex-end`; styles.paddingLeft = `${VALUE_LEFT_PADDING}px`; - styles.paddingRight = `${VALUE_LEFT_PADDING}px`; + styles.paddingRight = `${VALUE_LEFT_PADDING + (isOverflow ? VALUE_RIGHT_OVERFLOW_PADDING : 0)}px`; // Need to remove the left padding from the text width constraints textWidth -= VALUE_LEFT_PADDING; } diff --git a/packages/grafana-ui/src/components/VizRepeater/VizRepeater.tsx b/packages/grafana-ui/src/components/VizRepeater/VizRepeater.tsx index fab514bde4b..7fe09d92777 100644 --- a/packages/grafana-ui/src/components/VizRepeater/VizRepeater.tsx +++ b/packages/grafana-ui/src/components/VizRepeater/VizRepeater.tsx @@ -181,6 +181,7 @@ export class VizRepeater extends PureComponent { const { value, alignmentFactors, orientation, width, height, count } = valueProps; const { field, display, view, colIndex } = value; const { openMenu, targetClassName } = menuProps; + const spacing = this.getItemSpacing(); + // check if the total height is bigger than the visualization height, if so, there will be scrollbars for overflow + const isOverflow = (height + spacing) * count - spacing > this.props.height; let processor: DisplayProcessor | undefined = undefined; if (view && isNumber(colIndex)) { @@ -45,7 +48,7 @@ export class BarGaugePanel extends PureComponent { text={options.text} display={processor} theme={config.theme2} - itemSpacing={this.getItemSpacing()} + itemSpacing={spacing} displayMode={options.displayMode} onClick={openMenu} className={targetClassName} @@ -53,6 +56,7 @@ export class BarGaugePanel extends PureComponent { showUnfilled={options.showUnfilled} valueDisplayMode={options.valueMode} namePlacement={options.namePlacement} + isOverflow={isOverflow} /> ); }; From 3954a1948c21236e6b0ca91e95e6189e2e6e2b15 Mon Sep 17 00:00:00 2001 From: Leon Sorokin Date: Wed, 29 Jan 2025 13:44:09 -0600 Subject: [PATCH 17/18] Data links: Remove messaging around deprecating compact Explore URLs (#99780) --- .../components/DataLinks/DataLinkEditor.tsx | 7 +---- .../DataLinksListItem.test.tsx | 11 ------- .../DataLinksListItem.tsx | 21 +++---------- .../grafana-ui/src/utils/dataLinks.test.ts | 31 ------------------- packages/grafana-ui/src/utils/dataLinks.ts | 5 --- 5 files changed, 5 insertions(+), 70 deletions(-) delete mode 100644 packages/grafana-ui/src/utils/dataLinks.test.ts diff --git a/packages/grafana-ui/src/components/DataLinks/DataLinkEditor.tsx b/packages/grafana-ui/src/components/DataLinks/DataLinkEditor.tsx index cdd5e64eddf..e87d01fbea2 100644 --- a/packages/grafana-ui/src/components/DataLinks/DataLinkEditor.tsx +++ b/packages/grafana-ui/src/components/DataLinks/DataLinkEditor.tsx @@ -4,7 +4,6 @@ import { memo, ChangeEvent } from 'react'; import { VariableSuggestion, GrafanaTheme2, DataLink } from '@grafana/data'; import { useStyles2 } from '../../themes/index'; -import { isCompactUrl } from '../../utils/dataLinks'; import { t, Trans } from '../../utils/i18n'; import { Field } from '../Forms/Field'; import { Input } from '../Input/Input'; @@ -55,11 +54,7 @@ export const DataLinkEditor = memo(({ index, value, onChange, suggestions, isLas - + diff --git a/packages/grafana-ui/src/components/DataLinks/DataLinksInlineEditor/DataLinksListItem.test.tsx b/packages/grafana-ui/src/components/DataLinks/DataLinksInlineEditor/DataLinksListItem.test.tsx index 1ab1c27d4cd..b44576d53f7 100644 --- a/packages/grafana-ui/src/components/DataLinks/DataLinksInlineEditor/DataLinksListItem.test.tsx +++ b/packages/grafana-ui/src/components/DataLinks/DataLinksInlineEditor/DataLinksListItem.test.tsx @@ -63,17 +63,6 @@ describe('DataLinksListItem', () => { expect(screen.getByText(/http:\/\/localhost\:3000/i)).toBeInTheDocument(); expect(screen.getByTitle(/http:\/\/localhost\:3000/i)).toBeInTheDocument(); }); - - it('that is a explore compact url, then the title should be a warning', () => { - const link = { - ...baseLink, - url: 'http://localhost:3000/explore?orgId=1&left=[%22now-1h%22,%22now%22,%22gdev-loki%22,{%22expr%22:%22{place=%22luna%22}%22,%22refId%22:%22A%22}]', - }; - setupTestContext({ link }); - - expect(screen.getByText(/http:\/\/localhost\:3000/i)).toBeInTheDocument(); - expect(screen.getByText(/Explore data link may not work in the future. Please edit./i)).toBeInTheDocument(); - }); }); describe('when link is missing title', () => { diff --git a/packages/grafana-ui/src/components/DataLinks/DataLinksInlineEditor/DataLinksListItem.tsx b/packages/grafana-ui/src/components/DataLinks/DataLinksInlineEditor/DataLinksListItem.tsx index 1c12a41dd2a..9bddc35da71 100644 --- a/packages/grafana-ui/src/components/DataLinks/DataLinksInlineEditor/DataLinksListItem.tsx +++ b/packages/grafana-ui/src/components/DataLinks/DataLinksInlineEditor/DataLinksListItem.tsx @@ -4,12 +4,10 @@ import { Draggable } from '@hello-pangea/dnd'; import { DataFrame, DataLink, GrafanaTheme2 } from '@grafana/data'; import { useStyles2 } from '../../../themes'; -import { isCompactUrl } from '../../../utils'; import { t } from '../../../utils/i18n'; import { Badge } from '../../Badge/Badge'; import { Icon } from '../../Icon/Icon'; import { IconButton } from '../../IconButton/IconButton'; -import { Tooltip } from '../../Tooltip/Tooltip'; export interface DataLinksListItemProps { index: number; @@ -29,8 +27,6 @@ export const DataLinksListItem = ({ link, onEdit, onRemove, index, itemKey }: Da const hasTitle = title.trim() !== ''; const hasUrl = url.trim() !== ''; - const isCompactExploreUrl = isCompactUrl(url); - return ( {(provided) => ( @@ -41,17 +37,12 @@ export const DataLinksListItem = ({ link, onEdit, onRemove, index, itemKey }: Da key={index} >
-
+
{hasTitle ? title : 'Data link title not provided'}
- -
- {hasUrl ? url : 'Data link url not provided'} -
-
+
+ {hasUrl ? url : 'Data link url not provided'} +
{oneClick && ( @@ -91,10 +82,6 @@ const getDataLinkListItemStyles = (theme: GrafanaTheme2) => { flexGrow: 1, maxWidth: `calc(100% - 100px)`, }), - errored: css({ - color: theme.colors.error.text, - fontStyle: 'italic', - }), notConfigured: css({ fontStyle: 'italic', }), diff --git a/packages/grafana-ui/src/utils/dataLinks.test.ts b/packages/grafana-ui/src/utils/dataLinks.test.ts deleted file mode 100644 index a4f5ae1a61b..00000000000 --- a/packages/grafana-ui/src/utils/dataLinks.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { isCompactUrl } from './dataLinks'; - -describe('Datalinks', () => { - it('isCompactUrl matches compact URL with segments', () => { - expect( - isCompactUrl( - 'http://localhost:3000/explore?orgId=1&left=[%22now-1h%22,%22now%22,%22gdev-loki%22,{%22expr%22:%22{place=%22luna%22}%22,%22refId%22:%22A%22}]' - ) - ).toEqual(true); - }); - - it('isCompactUrl matches compact URL without segments', () => { - expect(isCompactUrl('http://localhost:3000/explore?orgId=1&left=[%22now-1h%22,%22now%22,%22gdev-loki%22]')).toEqual( - true - ); - }); - - it('isCompactUrl matches compact URL with right pane', () => { - expect( - isCompactUrl('http://localhost:3000/explore?orgId=1&right=[%22now-1h%22,%22now%22,%22gdev-loki%22]') - ).toEqual(true); - }); - - it('isCompactUrl does not match non-compact url', () => { - expect( - isCompactUrl( - 'http://localhost:3000/explore?orgId=1&left={"datasource":"test[datasource]","queries":[{"refId":"A","datasource":{"type":"prometheus","uid":"gdev-prometheus"}}],"range":{"from":"now-1h","to":"now"}}' - ) - ).toEqual(false); - }); -}); diff --git a/packages/grafana-ui/src/utils/dataLinks.ts b/packages/grafana-ui/src/utils/dataLinks.ts index 35fe1cffdf7..f889cf5a2a0 100644 --- a/packages/grafana-ui/src/utils/dataLinks.ts +++ b/packages/grafana-ui/src/utils/dataLinks.ts @@ -29,8 +29,3 @@ export const actionModelToContextMenuItems: (actions: ActionModel[]) => MenuItem }; }); }; - -export const isCompactUrl = (url: string) => { - const compactExploreUrlRegex = /\/explore\?.*&(left|right)=\[(.*\,){2,}(.*){1}\]/; - return compactExploreUrlRegex.test(url); -}; From 83d4f6e868cd2445c8faea4da674077bd2968f2f Mon Sep 17 00:00:00 2001 From: Oscar Kilhed Date: Wed, 29 Jan 2025 21:36:57 +0100 Subject: [PATCH 18/18] Remove e2e benchmark (#99695) --- package.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/package.json b/package.json index 0456907f286..1e7dde232a2 100644 --- a/package.json +++ b/package.json @@ -18,8 +18,6 @@ "e2e:enterprise": "./e2e/start-and-run-suite enterprise", "e2e:enterprise:dev": "./e2e/start-and-run-suite enterprise dev", "e2e:enterprise:debug": "./e2e/start-and-run-suite enterprise debug", - "build-benchmark": "NODE_ENV=dev nx exec -- webpack --config scripts/webpack/webpack.dev.js --env benchmark=1", - "e2e:playwright:benchmark": "yarn build-benchmark && ./e2e/plugin-e2e/start-and-benchmark", "e2e:playwright": "yarn playwright test", "e2e:playwright:server": "yarn e2e:plugin:build && ./e2e/plugin-e2e/start-and-run-suite", "e2e:storybook": "PORT=9001 ./e2e/run-suite storybook true",