diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 53fe69fabca..d4d31856d53 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -642,9 +642,6 @@ i18next.config.ts @grafana/grafana-frontend-platform # @grafana/plugin-configs /packages/grafana-plugin-configs/ @grafana/grafana-frontend-platform -# @grafana/prometheus -/packages/grafana-prometheus/ @grafana/data-sources-plugins - # @grafana/runtime /packages/grafana-runtime/CHANGELOG.md @grafana/grafana-frontend-platform /packages/grafana-runtime/LICENSE_APACHE2 @grafana/grafana-frontend-platform diff --git a/.github/workflows/i18n-crowdin-download.yml b/.github/workflows/i18n-crowdin-download.yml index e8e04c22029..3b4b9821659 100644 --- a/.github/workflows/i18n-crowdin-download.yml +++ b/.github/workflows/i18n-crowdin-download.yml @@ -13,4 +13,4 @@ jobs: crowdin_project_id: 5 pr_labels: 'area/frontend, area/internationalization, no-changelog, no-backport' github_board_id: 78 # Frontend Platform project - en_paths: public/locales/en-US/grafana.json, public/app/plugins/datasource/azuremonitor/locales/en-US/grafana-azure-monitor-datasource.json, public/app/plugins/datasource/mssql/locales/en-US/mssql.json, packages/grafana-prometheus/src/locales/en-US/grafana-prometheus.json, packages/grafana-sql/src/locales/en-US/grafana-sql.json + en_paths: public/locales/en-US/grafana.json, public/app/plugins/datasource/azuremonitor/locales/en-US/grafana-azure-monitor-datasource.json, public/app/plugins/datasource/mssql/locales/en-US/mssql.json, packages/grafana-sql/src/locales/en-US/grafana-sql.json diff --git a/.github/workflows/i18n-crowdin-upload.yml b/.github/workflows/i18n-crowdin-upload.yml index b61a7538bf0..cd483497e92 100644 --- a/.github/workflows/i18n-crowdin-upload.yml +++ b/.github/workflows/i18n-crowdin-upload.yml @@ -8,7 +8,6 @@ on: - 'public/app/plugins/datasource/azuremonitor/locales/en-US/grafana-azure-monitor-datasource.json' - 'public/app/plugins/datasource/mssql/locales/en-US/mssql.json' - 'packages/grafana-sql/src/locales/en-US/grafana-sql.json' - - 'packages/grafana-prometheus/src/locales/en-US/grafana-prometheus.json' branches: - main diff --git a/crowdin.yml b/crowdin.yml index 750bf8d1f4a..1f415e96ca7 100644 --- a/crowdin.yml +++ b/crowdin.yml @@ -27,10 +27,4 @@ files: [ "type": "i18next_json", "dest": "packages/grafana-sql/en-US/%original_file_name%" }, - { - "source": "packages/grafana-prometheus/src/locales/en-US/grafana-prometheus.json", - "translation": "packages/grafana-prometheus/src/locales/%locale%/%original_file_name%", - "type": "i18next_json", - "dest": "packages/grafana-prometheus/en-US/%original_file_name%" - }, ] diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 714072e6a70..3154614b5ab 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -342,89 +342,6 @@ "count": 1 } }, - "packages/grafana-prometheus/src/components/PromExploreExtraField.tsx": { - "@grafana/no-gf-form": { - "count": 4 - } - }, - "packages/grafana-prometheus/src/components/PromQueryField.tsx": { - "@grafana/no-gf-form": { - "count": 2 - } - }, - "packages/grafana-prometheus/src/components/metrics-browser/useMetricsLabelsValues.ts": { - "@grafana/no-direct-local-storage-access": { - "count": 6 - } - }, - "packages/grafana-prometheus/src/configuration/AlertingSettingsOverhaul.tsx": { - "@grafana/no-gf-form": { - "count": 5 - } - }, - "packages/grafana-prometheus/src/configuration/ExemplarSetting.tsx": { - "@grafana/no-gf-form": { - "count": 1 - } - }, - "packages/grafana-prometheus/src/datasource.ts": { - "@typescript-eslint/consistent-type-assertions": { - "count": 1 - }, - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "packages/grafana-prometheus/src/language_provider.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "packages/grafana-prometheus/src/language_provider.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "packages/grafana-prometheus/src/language_utils.ts": { - "@typescript-eslint/consistent-type-assertions": { - "count": 1 - } - }, - "packages/grafana-prometheus/src/querybuilder/components/LabelFilterItem.tsx": { - "@typescript-eslint/consistent-type-assertions": { - "count": 4 - } - }, - "packages/grafana-prometheus/src/querybuilder/components/LabelParamEditor.tsx": { - "@typescript-eslint/consistent-type-assertions": { - "count": 1 - } - }, - "packages/grafana-prometheus/src/querybuilder/shared/OperationEditor.tsx": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "packages/grafana-prometheus/src/querybuilder/shared/OperationParamEditorRegistry.tsx": { - "@typescript-eslint/consistent-type-assertions": { - "count": 3 - } - }, - "packages/grafana-prometheus/src/querybuilder/shared/types.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "packages/grafana-prometheus/src/resource_clients.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "packages/grafana-prometheus/src/types.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, "packages/grafana-runtime/src/analytics/types.ts": { "@typescript-eslint/no-explicit-any": { "count": 1 @@ -3956,4 +3873,4 @@ "count": 1 } } -} \ No newline at end of file +} diff --git a/eslint.config.js b/eslint.config.js index 1bc274c42fb..51d2b48775c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -385,7 +385,6 @@ module.exports = [ 'packages/grafana-ui/**/*.{ts,tsx,js,jsx}', 'packages/grafana-data/**/*.{ts,tsx,js,jsx}', 'packages/grafana-sql/**/*.{ts,tsx,js,jsx}', - 'packages/grafana-prometheus/**/*.{ts,tsx,js,jsx}', ...pluginsToTranslate.map((plugin) => `${plugin}/**/*.{ts,tsx,js,jsx}`), ], ignores: [ diff --git a/packages/grafana-prometheus/CHANGELOG.md b/packages/grafana-prometheus/CHANGELOG.md deleted file mode 100644 index 8d0fac75805..00000000000 --- a/packages/grafana-prometheus/CHANGELOG.md +++ /dev/null @@ -1,3 +0,0 @@ -# (2024-02-16) - -First public release. This release provides Prometheus exports in Grafana. Please be aware this is in the alpha state and there is likely to be breaking changes. diff --git a/packages/grafana-prometheus/LICENSE_AGPL b/packages/grafana-prometheus/LICENSE_AGPL deleted file mode 100644 index be3f7b28e56..00000000000 --- a/packages/grafana-prometheus/LICENSE_AGPL +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/packages/grafana-prometheus/README.md b/packages/grafana-prometheus/README.md deleted file mode 100644 index efbdb5791e1..00000000000 --- a/packages/grafana-prometheus/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Grafana Prometheus Library - -> **@grafana/prometheus is currently in ALPHA**. - -@grafana/prometheus is a collection of components used to build a Prometheus data source plugin in [Grafana](https://github.com/grafana/grafana). - -See [package source](https://github.com/grafana/grafana/tree/main/packages/grafana-prometheus) for more details. - -## Installation - -`yarn add @grafana/prometheus` - -`npm install @grafana/prometheus` diff --git a/packages/grafana-prometheus/i18next.config.ts b/packages/grafana-prometheus/i18next.config.ts deleted file mode 100644 index 6c0dccbd829..00000000000 --- a/packages/grafana-prometheus/i18next.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'i18next-cli'; - -export default defineConfig({ - locales: ['en-US'], // Only en-US is updated - Crowdin will PR with other languages - extract: { - input: ['src/**/*.{tsx,ts}'], - output: 'src/locales/{{language}}/{{namespace}}.json', - defaultNS: 'grafana-prometheus', - functions: ['t', '*.t'], - transComponents: ['Trans'], - warnOnConflicts: 'error', - }, -}); diff --git a/packages/grafana-prometheus/jest.config.js b/packages/grafana-prometheus/jest.config.js deleted file mode 100644 index 93995be84c2..00000000000 --- a/packages/grafana-prometheus/jest.config.js +++ /dev/null @@ -1,5 +0,0 @@ -const sharedConfig = require('../../jest.config.js'); -module.exports = { - ...sharedConfig, - rootDir: '../../', -}; diff --git a/packages/grafana-prometheus/package.json b/packages/grafana-prometheus/package.json deleted file mode 100644 index c5738c278c5..00000000000 --- a/packages/grafana-prometheus/package.json +++ /dev/null @@ -1,118 +0,0 @@ -{ - "author": "Grafana Labs", - "license": "AGPL-3.0-only", - "name": "@grafana/prometheus", - "private": true, - "version": "13.1.0-pre", - "description": "Grafana Prometheus Library", - "keywords": [ - "typescript", - "prometheus", - "grafana" - ], - "sideEffects": false, - "repository": { - "type": "git", - "url": "http://github.com/grafana/grafana.git", - "directory": "packages/grafana-prometheus" - }, - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", - "exports": { - "./package.json": "./package.json", - ".": { - "@grafana-app/source": "./src/index.ts", - "types": "./dist/types/index.d.ts", - "import": "./dist/esm/index.mjs", - "require": "./dist/cjs/index.cjs" - } - }, - "files": [ - "./dist", - "./README.md", - "./CHANGELOG.md", - "./LICENSE_AGPL" - ], - "publishConfig": { - "access": "public" - }, - "scripts": { - "build": "tsc -p ./tsconfig.build.json && rollup -c rollup.config.ts --configPlugin esbuild", - "bundle": "rollup -c rollup.config.ts --configPlugin esbuild", - "clean": "rimraf ./dist ./compiled ./package.tgz", - "i18n-extract": "i18next-cli extract --sync-primary", - "typecheck": "tsc --emitDeclarationOnly false --noEmit", - "prepack": "cp package.json package.json.bak && node ../../scripts/prepare-npm-package.js", - "postpack": "mv package.json.bak package.json" - }, - "dependencies": { - "@emotion/css": "11.13.5", - "@floating-ui/react": "0.27.19", - "@grafana/assistant": "0.1.24", - "@grafana/data": "13.1.0-pre", - "@grafana/e2e-selectors": "13.1.0-pre", - "@grafana/i18n": "13.1.0-pre", - "@grafana/plugin-ui": "^0.13.1", - "@grafana/runtime": "13.1.0-pre", - "@grafana/schema": "13.1.0-pre", - "@grafana/ui": "13.1.0-pre", - "@hello-pangea/dnd": "18.0.1", - "@leeoniya/ufuzzy": "1.0.19", - "@lezer/common": "1.5.2", - "@lezer/highlight": "1.2.3", - "@lezer/lr": "1.4.8", - "@prometheus-io/lezer-promql": "0.307.3", - "@types/debounce-promise": "3.1.9", - "@types/lodash": "4.17.20", - "@types/react": "18.3.18", - "@types/react-dom": "18.3.5", - "@types/react-highlight-words": "0.20.0", - "@types/semver": "7.7.1", - "@types/uuid": "11.0.0", - "debounce-promise": "3.1.2", - "lodash": "^4.17.23", - "moment": "2.30.1", - "moment-timezone": "0.5.47", - "monaco-editor": "0.34.1", - "monaco-promql": "1.8.0", - "pluralize": "8.0.0", - "prismjs": "1.30.0", - "react-highlight-words": "0.21.0", - "react-use": "17.6.0", - "react-window": "1.8.11", - "rxjs": "7.8.2", - "semver": "7.7.4", - "uuid": "13.0.0" - }, - "devDependencies": { - "@rollup/plugin-dynamic-import-vars": "2.1.5", - "@rollup/plugin-image": "3.0.3", - "@rollup/plugin-json": "6.1.0", - "@rollup/plugin-node-resolve": "16.0.1", - "@testing-library/jest-dom": "6.6.4", - "@testing-library/react": "16.3.0", - "@testing-library/user-event": "14.6.1", - "@types/jest": "29.5.14", - "@types/node": "24.10.1", - "@types/pluralize": "^0.0.33", - "@types/prismjs": "1.26.5", - "esbuild": "0.25.8", - "i18next-cli": "^1.48.0", - "jest": "29.7.0", - "jest-environment-jsdom": "29.7.0", - "react": "18.3.1", - "react-dom": "18.3.1", - "react-select-event": "5.5.1", - "rimraf": "6.0.1", - "rollup": "^4.60.1", - "rollup-plugin-esbuild": "6.2.1", - "rollup-plugin-node-externals": "^8.0.0", - "testing-library-selector": "0.3.1", - "typescript": "6.0.2" - }, - "peerDependencies": { - "react": "^18.0.0", - "react-dom": "^18.0.0" - } -} diff --git a/packages/grafana-prometheus/project.json b/packages/grafana-prometheus/project.json deleted file mode 100644 index 2e27390545a..00000000000 --- a/packages/grafana-prometheus/project.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "@grafana/prometheus", - "$schema": "../../node_modules/nx/schemas/project-schema.json", - "projectType": "library", - "tags": ["scope:package", "type:ui"], - "targets": { - "build": {} - } -} diff --git a/packages/grafana-prometheus/rollup.config.ts b/packages/grafana-prometheus/rollup.config.ts deleted file mode 100644 index 28083b2d26f..00000000000 --- a/packages/grafana-prometheus/rollup.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import dynamicImportVars from '@rollup/plugin-dynamic-import-vars'; -import image from '@rollup/plugin-image'; -import json from '@rollup/plugin-json'; -import { createRequire } from 'node:module'; - -import { cjsOutput, entryPoint, esmOutput, plugins } from '../rollup.config.parts'; - -const rq = createRequire(import.meta.url); -const pkg = rq('./package.json'); - -export default [ - { - input: entryPoint, - plugins: [...plugins, image(), json(), dynamicImportVars()], - output: [cjsOutput(pkg, 'grafana-prometheus'), esmOutput(pkg, 'grafana-prometheus')], - treeshake: false, - }, -]; diff --git a/packages/grafana-prometheus/src/add_label_to_query.test.ts b/packages/grafana-prometheus/src/add_label_to_query.test.ts deleted file mode 100644 index 7e70312e643..00000000000 --- a/packages/grafana-prometheus/src/add_label_to_query.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/add_label_to_query.test.ts -import { addLabelToQuery } from './add_label_to_query'; - -describe('addLabelToQuery()', () => { - it('should add label to simple query', () => { - expect(() => { - addLabelToQuery('foo', '', ''); - }).toThrow(); - expect(addLabelToQuery('foo', 'bar', 'baz')).toBe('foo{bar="baz"}'); - expect(addLabelToQuery('foo{}', 'bar', 'baz')).toBe('foo{bar="baz"}'); - expect(addLabelToQuery('foo{x="yy"}', 'bar', 'baz')).toBe('foo{x="yy", bar="baz"}'); - expect(addLabelToQuery('metric > 0.001', 'foo', 'bar')).toBe('metric{foo="bar"} > 0.001'); - }); - - it('should add custom operator', () => { - expect(addLabelToQuery('foo{}', 'bar', 'baz', '!=')).toBe('foo{bar!="baz"}'); - expect(addLabelToQuery('foo{x="yy"}', 'bar', 'baz', '!=')).toBe('foo{x="yy", bar!="baz"}'); - }); - - it('should not modify ranges', () => { - expect(addLabelToQuery('rate(metric[1m])', 'foo', 'bar')).toBe('rate(metric{foo="bar"}[1m])'); - }); - - it('should detect in-order function use', () => { - expect(addLabelToQuery('sum by (xx) (foo)', 'bar', 'baz')).toBe('sum by (xx) (foo{bar="baz"})'); - }); - - it('should convert number Infinity to +Inf', () => { - expect( - addLabelToQuery('sum(rate(prometheus_tsdb_compaction_chunk_size_bytes_bucket[5m])) by (le)', 'le', Infinity) - ).toBe('sum(rate(prometheus_tsdb_compaction_chunk_size_bytes_bucket{le="+Inf"}[5m])) by (le)'); - }); - - it('should handle selectors with punctuation', () => { - expect(addLabelToQuery('foo{instance="my-host.com:9100"}', 'bar', 'baz')).toBe( - 'foo{instance="my-host.com:9100", bar="baz"}' - ); - expect(addLabelToQuery('foo:metric:rate1m', 'bar', 'baz')).toBe('foo:metric:rate1m{bar="baz"}'); - expect(addLabelToQuery('avg(foo:metric:rate1m{a="b"})', 'bar', 'baz')).toBe( - 'avg(foo:metric:rate1m{a="b", bar="baz"})' - ); - expect(addLabelToQuery('foo{list="a,b,c"}', 'bar', 'baz')).toBe('foo{list="a,b,c", bar="baz"}'); - }); - - it('should work on arithmetical expressions', () => { - expect(addLabelToQuery('foo + foo', 'bar', 'baz')).toBe('foo{bar="baz"} + foo{bar="baz"}'); - expect(addLabelToQuery('foo{x="yy"} + metric', 'bar', 'baz')).toBe('foo{x="yy", bar="baz"} + metric{bar="baz"}'); - expect(addLabelToQuery('avg(foo) + sum(xx_yy)', 'bar', 'baz')).toBe('avg(foo{bar="baz"}) + sum(xx_yy{bar="baz"})'); - expect(addLabelToQuery('foo{x="yy"} * metric{y="zz",a="bb"} * metric2', 'bar', 'baz')).toBe( - 'foo{x="yy", bar="baz"} * metric{y="zz", a="bb", bar="baz"} * metric2{bar="baz"}' - ); - }); - - it('should not add duplicate labels to a query', () => { - expect(addLabelToQuery(addLabelToQuery('foo{x="yy"}', 'bar', 'baz', '!='), 'bar', 'baz', '!=')).toBe( - 'foo{x="yy", bar!="baz"}' - ); - expect(addLabelToQuery(addLabelToQuery('rate(metric[1m])', 'foo', 'bar'), 'foo', 'bar')).toBe( - 'rate(metric{foo="bar"}[1m])' - ); - expect(addLabelToQuery(addLabelToQuery('foo{list="a,b,c"}', 'bar', 'baz'), 'bar', 'baz')).toBe( - 'foo{list="a,b,c", bar="baz"}' - ); - expect(addLabelToQuery(addLabelToQuery('avg(foo) + sum(xx_yy)', 'bar', 'baz'), 'bar', 'baz')).toBe( - 'avg(foo{bar="baz"}) + sum(xx_yy{bar="baz"})' - ); - }); - - it('should modify existing labels if the operator is different', () => { - expect(addLabelToQuery(addLabelToQuery('foo{x="yy"}', 'bar', 'baz', '!='), 'bar', 'baz', '=')).toBe( - 'foo{x="yy", bar="baz"}' - ); - expect(addLabelToQuery(addLabelToQuery('foo{x="yy"}', 'bar', 'baz', '='), 'bar', 'baz', '!=')).toBe( - 'foo{x="yy", bar!="baz"}' - ); - }); - - it('should not remove filters', () => { - expect(addLabelToQuery('{x="y"} |="yy"', 'bar', 'baz')).toBe('{x="y", bar="baz"} |="yy"'); - expect(addLabelToQuery('{x="y"} |="yy" !~"xx"', 'bar', 'baz')).toBe('{x="y", bar="baz"} |="yy" !~"xx"'); - }); - - it('should add labels to metrics with logical operators', () => { - expect(addLabelToQuery('foo_info or bar_info', 'bar', 'baz')).toBe('foo_info{bar="baz"} or bar_info{bar="baz"}'); - expect(addLabelToQuery('foo_info and bar_info', 'bar', 'baz')).toBe('foo_info{bar="baz"} and bar_info{bar="baz"}'); - }); - - it('should not add ad-hoc filter to template variables', () => { - expect(addLabelToQuery('sum(rate({job="foo"}[2m])) by (value $variable)', 'bar', 'baz')).toBe( - 'sum(rate({job="foo", bar="baz"}[2m])) by (value $variable)' - ); - }); - - it('should not add ad-hoc filter to range', () => { - expect(addLabelToQuery('avg(rate((my_metric{job="foo"} > 0)[3h:])) by (label)', 'bar', 'baz')).toBe( - 'avg(rate((my_metric{job="foo", bar="baz"} > 0)[3h:])) by (label)' - ); - }); - it('should not add ad-hoc filter to labels in label list provided with the group modifier', () => { - expect( - addLabelToQuery( - 'max by (id, name, type) (my_metric{type=~"foo|bar|baz-test"}) * on(id) group_right(id, type, name) sum by (id) (my_metric) * 1000', - 'bar', - 'baz' - ) - ).toBe( - 'max by (id, name, type) (my_metric{type=~"foo|bar|baz-test", bar="baz"}) * on(id) group_right(id, type, name) sum by (id) (my_metric{bar="baz"}) * 1000' - ); - }); - it('should not add ad-hoc filter to labels in label list provided with the group modifier', () => { - expect(addLabelToQuery('rate(my_metric[${__range_s}s])', 'bar', 'baz')).toBe( - 'rate(my_metric{bar="baz"}[${__range_s}s])' - ); - }); - it('should not add ad-hoc filter to labels to math operations', () => { - expect(addLabelToQuery('count(my_metric{job!="foo"} < (5*1024*1024*1024) or vector(0)) - 1', 'bar', 'baz')).toBe( - 'count(my_metric{job!="foo", bar="baz"} < (5*1024*1024*1024) or vector(0)) - 1' - ); - }); - - it('should not add ad-hoc filter bool operator', () => { - expect(addLabelToQuery('ALERTS < bool 1', 'bar', 'baz')).toBe('ALERTS{bar="baz"} < bool 1'); - }); - - it('should add a utf8 label', () => { - expect(addLabelToQuery('{"metric.name"}', 'cenk.erdem', 'muhabbet')).toBe( - '{"metric.name", "cenk.erdem"="muhabbet"}' - ); - - expect(addLabelToQuery('metric{label="val"}', 'cenk.erdem', 'muhabbet')).toBe( - 'metric{label="val", "cenk.erdem"="muhabbet"}' - ); - }); - - it('should not add a utf8 label when it is already applied', () => { - expect(addLabelToQuery('{"metric.name", "cenk.erdem"="muhabbet"}', 'cenk.erdem', 'muhabbet')).toBe( - '{"metric.name", "cenk.erdem"="muhabbet"}' - ); - - expect(addLabelToQuery('metric{label="val", "cenk.erdem"="muhabbet"}', 'cenk.erdem', 'muhabbet')).toBe( - 'metric{label="val", "cenk.erdem"="muhabbet"}' - ); - }); -}); diff --git a/packages/grafana-prometheus/src/add_label_to_query.ts b/packages/grafana-prometheus/src/add_label_to_query.ts deleted file mode 100644 index c36e6d5f890..00000000000 --- a/packages/grafana-prometheus/src/add_label_to_query.ts +++ /dev/null @@ -1,109 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/add_label_to_query.ts -import { parser, VectorSelector } from '@prometheus-io/lezer-promql'; - -import { buildVisualQueryFromString } from './querybuilder/parsing'; -import { renderQuery } from './querybuilder/shared/rendering/query'; -import { type QueryBuilderLabelFilter } from './querybuilder/shared/types'; -import { type PromVisualQuery } from './querybuilder/types'; - -/** - * Adds label filter to existing query. Useful for query modification for example for ad hoc filters. - * - * It uses PromQL parser to find instances of metric and labels, alters them and then splices them back into the query. - * Ideally we could use the parse -> change -> render is a simple 3 steps but right now building the visual query - * object does not support all possible queries. - * - * So instead this just operates on substrings of the query with labels and operates just on those. This makes this - * more robust and can alter even invalid queries, and preserves in general the query structure and whitespace. - * @param query - * @param key - * @param value - * @param operator - */ -export function addLabelToQuery(query: string, key: string, value: string | number, operator = '='): string { - if (!key) { - throw new Error('Need label to add to query.'); - } - - const vectorSelectorPositions = getVectorSelectorPositions(query); - if (!vectorSelectorPositions.length) { - return query; - } - - const filter = toLabelFilter(key, value, operator); - return addFilter(query, vectorSelectorPositions, filter); -} - -type VectorSelectorPosition = { from: number; to: number; query: PromVisualQuery }; - -/** - * Parse the string and get all VectorSelector positions in the query together with parsed representation of the vector - * selector. - * @param query - */ -function getVectorSelectorPositions(query: string): VectorSelectorPosition[] { - const tree = parser.parse(query); - const positions: VectorSelectorPosition[] = []; - tree.iterate({ - enter: ({ to, from, type }): false | void => { - if (type.id === VectorSelector) { - const visQuery = buildVisualQueryFromString(query.substring(from, to)); - positions.push({ query: visQuery.query, from, to }); - return false; - } - }, - }); - return positions; -} - -function toLabelFilter(key: string, value: string | number, operator: string): QueryBuilderLabelFilter { - // We need to make sure that we convert the value back to string because it may be a number - const transformedValue = value === Infinity ? '+Inf' : value.toString(); - return { label: key, op: operator, value: transformedValue }; -} - -function addFilter( - query: string, - vectorSelectorPositions: VectorSelectorPosition[], - filter: QueryBuilderLabelFilter -): string { - let newQuery = ''; - let prev = 0; - - for (let i = 0; i < vectorSelectorPositions.length; i++) { - // This is basically just doing splice on a string for each matched vector selector. - - const match = vectorSelectorPositions[i]; - const isLast = i === vectorSelectorPositions.length - 1; - - const start = query.substring(prev, match.from); - const end = isLast ? query.substring(match.to) : ''; - - const labelToMatch = labelExists(match.query.labels, filter); - if (labelToMatch) { - // if label exists, check the operator, if it is different, update it. - // We don't want to add duplicate labels. - if (labelToMatch.op !== filter.op) { - match.query.labels = match.query.labels.map((label) => - label.label === filter.label && label.value === filter.value ? filter : label - ); - } - } else { - // label does not exist, add as is. - match.query.labels.push(filter); - } - const newLabels = renderQuery(match.query); - newQuery += start + newLabels + end; - prev = match.to; - } - return newQuery; -} - -/** - * Check if label exists in the list of labels but ignore the operator. - * @param labels - * @param filter - */ -function labelExists(labels: QueryBuilderLabelFilter[], filter: QueryBuilderLabelFilter) { - return labels.find((label) => label.label === filter.label && label.value === filter.value); -} diff --git a/packages/grafana-prometheus/src/annotations.test.ts b/packages/grafana-prometheus/src/annotations.test.ts deleted file mode 100644 index fcf2b1c36c6..00000000000 --- a/packages/grafana-prometheus/src/annotations.test.ts +++ /dev/null @@ -1,730 +0,0 @@ -import { Observable, of } from 'rxjs'; - -import { - type AnnotationEvent, - type AnnotationQuery, - type DataFrame, - type Field, - FieldType, - renderLegendFormat, -} from '@grafana/data'; - -import { PrometheusAnnotationSupport } from './annotations'; -import { type PrometheusDatasource } from './datasource'; -import { type PromQuery } from './types'; - -// Mock dependencies -jest.mock('@grafana/data', () => { - const original = jest.requireActual('@grafana/data'); - return { - ...original, - rangeUtil: { - ...original.rangeUtil, - intervalToSeconds: jest.fn().mockImplementation((interval: string) => { - if (interval === '60s') { - return 60; - } - if (interval === '30s') { - return 30; - } - if (interval === '2m0s') { - return 120; - } - return 60; // default - }), - }, - renderLegendFormat: jest.fn().mockImplementation((format: string, labels: Record) => { - if (!format) { - return ''; - } - return format.replace(/\{\{(\w+)\}\}/g, (_: string, key: string) => labels[key] || ''); - }), - }; -}); - -describe('PrometheusAnnotationSupport', () => { - // Create mock datasource - const mockDatasource = {} as PrometheusDatasource; - const annotationSupport = PrometheusAnnotationSupport(mockDatasource); - - // Mock the implementation to match our testing expectations - beforeEach(() => { - // Reset and setup mocks before each test - jest.clearAllMocks(); - jest.restoreAllMocks(); - }); - - describe('prepareAnnotation', () => { - it('should respect existing target values and not override them', () => { - const annotation: AnnotationQuery & { expr?: string; step?: string } = { - expr: 'rate(prometheus_http_requests_total[5m])', - step: '10s', - refId: 'testRefId', - target: { - expr: 'original_expr', - refId: 'originalRefId', - legendFormat: 'test', - interval: 'original_interval', - }, - datasource: { uid: 'prometheus' }, - enable: true, - name: 'Prometheus Annotation', - iconColor: 'red', - }; - - const result = annotationSupport.prepareAnnotation!(annotation); - - // Check target properties are preserved when already set - expect(result.target?.refId).toBe('originalRefId'); - expect(result.target?.expr).toBe('original_expr'); - expect(result.target?.interval).toBe('original_interval'); - expect(result.target?.legendFormat).toBe('test'); - - // Check the original properties are removed - expect(result.expr).toBeUndefined(); - expect(result.step).toBeUndefined(); - }); - - it('should transfer properties from json to target when target values are not set', () => { - const annotation: AnnotationQuery & { expr?: string; step?: string } = { - expr: 'rate(prometheus_http_requests_total[5m])', - step: '10s', - refId: 'testRefId', - target: { - expr: '', // Empty string - should be overridden - refId: '', // Empty string - should be overridden - legendFormat: 'test', - // interval not set - }, - datasource: { uid: 'prometheus' }, - enable: true, - name: 'Prometheus Annotation', - iconColor: 'red', - }; - - const result = annotationSupport.prepareAnnotation!(annotation); - - // Check target properties are set from json when target values are empty - expect(result.target?.refId).toBe('testRefId'); - expect(result.target?.expr).toBe('rate(prometheus_http_requests_total[5m])'); - expect(result.target?.interval).toBe('10s'); - expect(result.target?.legendFormat).toBe('test'); - - // Check the original properties are removed - expect(result.expr).toBeUndefined(); - expect(result.step).toBeUndefined(); - }); - - it('should use default refId if not provided in either target or json', () => { - const annotation: AnnotationQuery & { expr?: string; step?: string } = { - expr: 'up', - step: '30s', - target: { - expr: '', - refId: '', - }, - datasource: { uid: 'prometheus' }, - enable: true, - name: 'Prometheus Annotation', - iconColor: 'red', - }; - - const result = annotationSupport.prepareAnnotation!(annotation); - - expect(result.target?.refId).toBe('Anno'); - expect(result.target?.expr).toBe('up'); - expect(result.target?.interval).toBe('30s'); - }); - - it('should handle undefined target', () => { - const annotation: AnnotationQuery & { expr?: string; step?: string } = { - expr: 'up', - step: '30s', - datasource: { uid: 'prometheus' }, - enable: true, - name: 'Prometheus Annotation', - iconColor: 'red', - }; - - const result = annotationSupport.prepareAnnotation!(annotation); - - expect(result.target?.refId).toBe('Anno'); - expect(result.target?.expr).toBe('up'); - expect(result.target?.interval).toBe('30s'); - }); - - it('should handle undefined expr and step', () => { - const annotation: AnnotationQuery = { - target: { - expr: '', - refId: '', - }, - datasource: { uid: 'prometheus' }, - enable: true, - name: 'Prometheus Annotation', - iconColor: 'red', - }; - - const result = annotationSupport.prepareAnnotation!(annotation); - - expect(result.target?.refId).toBe('Anno'); - expect(result.target?.expr).toBe(''); - expect(result.target?.interval).toBe(''); - }); - - it('should handle empty strings vs undefined values correctly', () => { - const annotation: AnnotationQuery & { expr?: string; step?: string } = { - expr: 'test_expr', - step: '5s', - target: { - expr: '', // Empty string - refId: 'target_refId', - // interval not set at all - }, - datasource: { uid: 'prometheus' }, - enable: true, - name: 'Prometheus Annotation', - iconColor: 'red', - }; - - const result = annotationSupport.prepareAnnotation!(annotation); - - // refId is set in target - should be preserved - expect(result.target?.refId).toBe('target_refId'); - - // expr is empty in target - should be replaced with json.expr - expect(result.target?.expr).toBe('test_expr'); - - // interval not set in target - should be set from json.step - expect(result.target?.interval).toBe('5s'); - }); - }); - - describe('processEvents', () => { - it('should return empty observable when no frames are provided', () => { - const annotation = { - target: {} as PromQuery, - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - // Mock the implementation to match the real one - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return new Observable(); // This is what the implementation does - creates an Observable that never emits - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, []); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, []); - }); - - it('should process single frame into annotation events', () => { - const annotation = { - target: {} as PromQuery, - tagKeys: 'instance', - titleFormat: '{{instance}}', - textFormat: 'value: {{value}}', - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - const timeValues = [1000, 2000]; - const valueValues = [1, 1]; - const mockLabels = { instance: 'server1', value: '100' }; - - const frame: DataFrame = { - name: 'test', - length: timeValues.length, - fields: [ - createField('Time', FieldType.time, timeValues), - createField('Value', FieldType.number, valueValues, mockLabels), - ], - meta: { - executedQueryString: 'Step: 60s', - }, - }; - - // Create expected result - const expectedEvent: AnnotationEvent = { - time: 1000, - timeEnd: 2000, - annotation: annotation, - title: 'server1', - tags: ['server1'], - text: 'value: 100', - }; - - // Manually call renderLegendFormat with the expected arguments - // This simulates what happens inside the real implementation - renderLegendFormat('{{instance}}', mockLabels); - renderLegendFormat('value: {{value}}', mockLabels); - - // Mock the implementation to return our expected output - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of([expectedEvent]); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [frame]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [frame]); - - // Verify renderLegendFormat was called correctly - expect(renderLegendFormat).toHaveBeenCalledWith('{{instance}}', mockLabels); - expect(renderLegendFormat).toHaveBeenCalledWith('value: {{value}}', mockLabels); - }); - - it('should handle multiple frames', () => { - const annotation = { - target: {} as PromQuery, - tagKeys: 'app', - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - const frame1: DataFrame = { - name: 'test1', - length: 2, - fields: [ - createField('Time', FieldType.time, [1000, 2000]), - createField('Value', FieldType.number, [1, 1], { app: 'app1' }), - ], - meta: { - executedQueryString: 'Step: 60s', - }, - }; - - const frame2: DataFrame = { - name: 'test2', - length: 2, - fields: [ - createField('Time', FieldType.time, [3000, 4000]), - createField('Value', FieldType.number, [1, 1], { app: 'app2' }), - ], - meta: { - executedQueryString: 'Step: 60s', - }, - }; - - // Create expected events - const expectedEvents = [ - { - time: 1000, - timeEnd: 2000, - annotation: annotation, - title: '', - tags: ['app1'], - text: '', - }, - { - time: 3000, - timeEnd: 4000, - annotation: annotation, - title: '', - tags: ['app2'], - text: '', - }, - ]; - - // Mock the implementation - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of(expectedEvents); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [frame1, frame2]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [frame1, frame2]); - }); - - it('should group events within step intervals', () => { - const annotation = { - target: {} as PromQuery, - tagKeys: '', - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - // Create timestamps where some should be grouped and some not - // With 60s step (60000ms), events within that range will be grouped - const timeValues = [1000, 2000, 60000, 120000]; - const valueValues = [1, 1, 1, 1]; - - const frame: DataFrame = { - name: 'test', - length: timeValues.length, - fields: [createField('Time', FieldType.time, timeValues), createField('Value', FieldType.number, valueValues)], - meta: { - executedQueryString: 'Step: 60s', - }, - }; - - // Create expected events - grouped as per the implementation logic - const expectedEvents = [ - { - time: 1000, - timeEnd: 2000, - annotation: annotation, - title: '', - tags: [], - text: '', - }, - { - time: 60000, - timeEnd: 120000, - annotation: annotation, - title: '', - tags: [], - text: '', - }, - ]; - - // Mock the implementation - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of(expectedEvents); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [frame]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [frame]); - }); - - it('should handle useValueForTime option', () => { - const annotation = { - target: {} as PromQuery, - useValueForTime: true, - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - const frame: DataFrame = { - name: 'test', - length: 2, - fields: [ - createField('Time', FieldType.time, [1000, 2000]), - createField('Value', FieldType.number, ['3000', '4000']), // Values as strings for parseFloat - ], - meta: { - executedQueryString: 'Step: 60s', - }, - }; - - // Create expected events - time from value field - const expectedEvents = [ - { - time: 3000, - timeEnd: 4000, - annotation: annotation, - title: '', - tags: [], - text: '', - }, - ]; - - // Mock the implementation - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of(expectedEvents); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [frame]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [frame]); - }); - - it('should filter by zero values', () => { - const annotation = { - target: {} as PromQuery, - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - const frame: DataFrame = { - name: 'test', - length: 4, - fields: [ - createField('Time', FieldType.time, [1000, 2000, 3000, 4000]), - createField('Value', FieldType.number, [1, 0, 1, 0]), // Only non-zero values create events - ], - meta: { - executedQueryString: 'Step: 60s', - }, - }; - - // Create expected events - only for non-zero values - const expectedEvents = [ - { - time: 1000, - timeEnd: 1000, - annotation: annotation, - title: '', - tags: [], - text: '', - }, - { - time: 3000, - timeEnd: 3000, - annotation: annotation, - title: '', - tags: [], - text: '', - }, - ]; - - // Mock the implementation - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of(expectedEvents); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [frame]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [frame]); - }); - - it('should handle empty frames with no fields', () => { - const annotation = { - target: {} as PromQuery, - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - const emptyFrame: DataFrame = { - name: 'test', - length: 0, - fields: [], - }; - - // Create expected events - empty array for empty frame - const expectedEvents: AnnotationEvent[] = []; - - // Mock the implementation - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of(expectedEvents); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [emptyFrame]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [emptyFrame]); - }); - - // Additional tests from the old implementation - - it('should handle inactive regions with gaps', () => { - const annotation = { - target: {} as PromQuery, - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - // Recreate the test case from the old implementation - const timeValues = [2 * 60000, 3 * 60000, 5 * 60000, 6 * 60000, 7 * 60000, 8 * 60000, 9 * 60000]; - const valueValues = [1, 1, 1, 1, 1, 0, 1]; - - const frame: DataFrame = { - name: 'test', - length: timeValues.length, - fields: [createField('Time', FieldType.time, timeValues), createField('Value', FieldType.number, valueValues)], - meta: { - executedQueryString: 'Step: 60s', - }, - }; - - // Expected regions based on the old test - const expectedEvents = [ - { - time: 120000, - timeEnd: 180000, - annotation: annotation, - title: '', - tags: [], - text: '', - }, - { - time: 300000, - timeEnd: 420000, - annotation: annotation, - title: '', - tags: [], - text: '', - }, - { - time: 540000, - timeEnd: 540000, - annotation: annotation, - title: '', - tags: [], - text: '', - }, - ]; - - // Mock the implementation - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of(expectedEvents); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [frame]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [frame]); - }); - - it('should handle single region', () => { - const annotation = { - target: {} as PromQuery, - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - const timeValues = [2 * 60000, 3 * 60000]; - const valueValues = [1, 1]; - - const frame: DataFrame = { - name: 'test', - length: timeValues.length, - fields: [createField('Time', FieldType.time, timeValues), createField('Value', FieldType.number, valueValues)], - meta: { - executedQueryString: 'Step: 60s', - }, - }; - - const expectedEvents = [ - { - time: 120000, - timeEnd: 180000, - annotation: annotation, - title: '', - tags: [], - text: '', - }, - ]; - - // Mock the implementation - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of(expectedEvents); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [frame]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [frame]); - }); - - it('should handle larger step parameter for grouping', () => { - const annotation = { - target: {} as PromQuery, - enable: true, - name: 'test', - iconColor: 'red', - datasource: { uid: 'prometheus' }, - } as AnnotationQuery; - - // Data from the original test - const timeValues = [1 * 120000, 2 * 120000, 3 * 120000, 4 * 120000, 5 * 120000, 6 * 120000]; - const valueValues = [1, 1, 0, 0, 1, 1]; - - // First test with default 60s step - const frame1: DataFrame = { - name: 'test', - length: timeValues.length, - fields: [createField('Time', FieldType.time, timeValues), createField('Value', FieldType.number, valueValues)], - meta: { - executedQueryString: 'Step: 60s', - }, - }; - - // Expected results with default step - const expectedEvents1 = [ - { time: 120000, timeEnd: 120000 }, - { time: 240000, timeEnd: 240000 }, - { time: 600000, timeEnd: 600000 }, - { time: 720000, timeEnd: 720000 }, - ]; - - // Mock the implementation for default step - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of(expectedEvents1.map((e) => ({ ...e, annotation, title: '', tags: [], text: '' }))); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [frame1]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [frame1]); - - // Now test with larger 2m step - const frame2: DataFrame = { - name: 'test', - length: timeValues.length, - fields: [createField('Time', FieldType.time, timeValues), createField('Value', FieldType.number, valueValues)], - meta: { - executedQueryString: 'Step: 2m0s', - }, - }; - - // Expected results with larger step - const expectedEvents2 = [ - { time: 120000, timeEnd: 240000 }, - { time: 600000, timeEnd: 720000 }, - ]; - - // Mock the implementation for larger step - jest.spyOn(annotationSupport, 'processEvents').mockImplementation(() => { - return of(expectedEvents2.map((e) => ({ ...e, annotation, title: '', tags: [], text: '' }))); - }); - - // Call the function but don't store the unused result - annotationSupport.processEvents!(annotation, [frame2]); - - // Verify the mock was called with the right arguments - expect(annotationSupport.processEvents).toHaveBeenCalledWith(annotation, [frame2]); - }); - }); - - describe('QueryEditor', () => { - it('should have a QueryEditor component', () => { - expect(annotationSupport.QueryEditor).toBeDefined(); - }); - }); -}); - -// Helper function to create fields for testing -function createField(name: string, type: FieldType, values: unknown[], labels = {}): Field { - return { - name, - type, - values, - config: {}, - labels, - }; -} diff --git a/packages/grafana-prometheus/src/annotations.ts b/packages/grafana-prometheus/src/annotations.ts deleted file mode 100644 index 1fd5475cab0..00000000000 --- a/packages/grafana-prometheus/src/annotations.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { Observable, of } from 'rxjs'; - -import { - type AnnotationEvent, - type AnnotationQuery, - type AnnotationSupport, - type DataFrame, - rangeUtil, - renderLegendFormat, -} from '@grafana/data'; - -import { AnnotationQueryEditor } from './components/AnnotationQueryEditor'; -import { type PrometheusDatasource } from './datasource'; -import { type PromQuery } from './types'; - -const ANNOTATION_QUERY_STEP_DEFAULT = '60s'; - -export const PrometheusAnnotationSupport = (ds: PrometheusDatasource): AnnotationSupport => { - return { - QueryEditor: AnnotationQueryEditor, - prepareAnnotation(json: AnnotationQuery): AnnotationQuery { - // Initialize target if it doesn't exist - if (!json.target) { - json.target = { - expr: '', - refId: 'Anno', - }; - } - - // Create a new target, preserving existing values when present - json.target = { - ...json.target, - refId: json.target.refId || json.refId || 'Anno', - expr: json.target.expr || json.expr || '', - interval: json.target.interval || json.step || '', - }; - - // Remove properties that have been transferred to target - delete json.expr; - delete json.step; - - return json; - }, - processEvents(anno: AnnotationQuery, frames: DataFrame[]): Observable { - if (!frames.length) { - return new Observable(); - } - - const { tagKeys = '', titleFormat = '', textFormat = '' } = anno; - - const input = frames[0].meta?.executedQueryString || ''; - const regex = /Step:\s*([\d\w]+)/; - const match = input.match(regex); - const stepValue = match ? match[1] : null; - const step = rangeUtil.intervalToSeconds(stepValue || ANNOTATION_QUERY_STEP_DEFAULT) * 1000; - const tagKeysArray = tagKeys.split(','); - - const eventList: AnnotationEvent[] = []; - - for (const frame of frames) { - if (frame.fields.length === 0) { - continue; - } - const timeField = frame.fields[0]; - const valueField = frame.fields[1]; - const labels = valueField?.labels || {}; - - const tags = Object.keys(labels) - .filter((label) => tagKeysArray.includes(label)) - .map((label) => labels[label]); - - const timeValueTuple: Array<[number, number]> = []; - - let idx = 0; - valueField.values.forEach((value: string) => { - let timeStampValue: number; - let valueValue: number; - const time = timeField.values[idx]; - - // If we want to use value as a time, we use value as timeStampValue and valueValue will be 1 - if (anno.useValueForTime) { - timeStampValue = Math.floor(parseFloat(value)); - valueValue = 1; - } else { - timeStampValue = Math.floor(parseFloat(time)); - valueValue = parseFloat(value); - } - - idx++; - timeValueTuple.push([timeStampValue, valueValue]); - }); - - const activeValues = timeValueTuple.filter((value) => value[1] > 0); - const activeValuesTimestamps = activeValues.map((value) => value[0]); - - // Instead of creating singular annotation for each active event we group events into region if they are less - // or equal to `step` apart. - let latestEvent: AnnotationEvent | null = null; - - for (const timestamp of activeValuesTimestamps) { - // We already have event `open` and we have new event that is inside the `step` so we just update the end. - if (latestEvent && (latestEvent.timeEnd ?? 0) + step >= timestamp) { - latestEvent.timeEnd = timestamp; - continue; - } - - // Event exists but new one is outside of the `step` so we add it to eventList. - if (latestEvent) { - eventList.push(latestEvent); - } - - // We start a new region. - latestEvent = { - time: timestamp, - timeEnd: timestamp, - annotation: anno, - title: renderLegendFormat(titleFormat, labels), - tags, - text: renderLegendFormat(textFormat, labels), - }; - } - - // Finish up last point if we have one - if (latestEvent) { - latestEvent.timeEnd = activeValuesTimestamps[activeValuesTimestamps.length - 1]; - eventList.push(latestEvent); - } - } - - return of(eventList); - }, - }; -}; diff --git a/packages/grafana-prometheus/src/caching.test.ts b/packages/grafana-prometheus/src/caching.test.ts deleted file mode 100644 index ca03ecb6ab5..00000000000 --- a/packages/grafana-prometheus/src/caching.test.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { - getCacheDurationInMinutes, - getDaysToCacheMetadata, - getDebounceTimeInMilliseconds, - buildCacheHeaders, - getDefaultCacheHeaders, -} from './caching'; -import { PrometheusCacheLevel } from './types'; - -describe('caching', () => { - describe('getDebounceTimeInMilliseconds', () => { - it('should return 600ms for Medium cache level', () => { - expect(getDebounceTimeInMilliseconds(PrometheusCacheLevel.Medium)).toBe(600); - }); - - it('should return 1200ms for High cache level', () => { - expect(getDebounceTimeInMilliseconds(PrometheusCacheLevel.High)).toBe(1200); - }); - - it('should return 350ms for Low cache level', () => { - expect(getDebounceTimeInMilliseconds(PrometheusCacheLevel.Low)).toBe(350); - }); - - it('should return 350ms for None cache level', () => { - expect(getDebounceTimeInMilliseconds(PrometheusCacheLevel.None)).toBe(350); - }); - - it('should return default value (350ms) for unknown cache level', () => { - expect(getDebounceTimeInMilliseconds('invalid' as PrometheusCacheLevel)).toBe(350); - }); - }); - - describe('getDaysToCacheMetadata', () => { - it('should return 7 days for Medium cache level', () => { - expect(getDaysToCacheMetadata(PrometheusCacheLevel.Medium)).toBe(7); - }); - - it('should return 30 days for High cache level', () => { - expect(getDaysToCacheMetadata(PrometheusCacheLevel.High)).toBe(30); - }); - - it('should return 1 day for Low cache level', () => { - expect(getDaysToCacheMetadata(PrometheusCacheLevel.Low)).toBe(1); - }); - - it('should return 1 day for None cache level', () => { - expect(getDaysToCacheMetadata(PrometheusCacheLevel.None)).toBe(1); - }); - - it('should return default value (1 day) for unknown cache level', () => { - expect(getDaysToCacheMetadata('invalid' as PrometheusCacheLevel)).toBe(1); - }); - }); - - describe('getCacheDurationInMinutes', () => { - it('should return 10 minutes for Medium cache level', () => { - expect(getCacheDurationInMinutes(PrometheusCacheLevel.Medium)).toBe(10); - }); - - it('should return 60 minutes for High cache level', () => { - expect(getCacheDurationInMinutes(PrometheusCacheLevel.High)).toBe(60); - }); - - it('should return 1 minute for Low cache level', () => { - expect(getCacheDurationInMinutes(PrometheusCacheLevel.Low)).toBe(1); - }); - - it('should return 1 minute for None cache level', () => { - expect(getCacheDurationInMinutes(PrometheusCacheLevel.None)).toBe(1); - }); - - it('should return default value (1 minute) for unknown cache level', () => { - expect(getCacheDurationInMinutes('invalid' as PrometheusCacheLevel)).toBe(1); - }); - }); - - describe('buildCacheHeaders', () => { - it('should build cache headers with provided duration in seconds', () => { - const result = buildCacheHeaders(300); - expect(result).toEqual({ - headers: { - 'X-Grafana-Cache': 'private, max-age=300', - }, - }); - }); - - it('should handle zero duration', () => { - const result = buildCacheHeaders(0); - expect(result).toEqual({ - headers: { - 'X-Grafana-Cache': 'private, max-age=0', - }, - }); - }); - - it('should handle large duration values', () => { - const oneDayInSeconds = 86400; - const result = buildCacheHeaders(oneDayInSeconds); - expect(result).toEqual({ - headers: { - 'X-Grafana-Cache': 'private, max-age=86400', - }, - }); - }); - }); - - describe('getDefaultCacheHeaders', () => { - it('should return cache headers for Medium cache level', () => { - const result = getDefaultCacheHeaders(PrometheusCacheLevel.Medium); - expect(result).toEqual({ - headers: { - 'X-Grafana-Cache': 'private, max-age=600', // 10 minutes in seconds - }, - }); - }); - - it('should return cache headers for High cache level', () => { - const result = getDefaultCacheHeaders(PrometheusCacheLevel.High); - expect(result).toEqual({ - headers: { - 'X-Grafana-Cache': 'private, max-age=3600', // 60 minutes in seconds - }, - }); - }); - - it('should return cache headers for Low cache level', () => { - const result = getDefaultCacheHeaders(PrometheusCacheLevel.Low); - expect(result).toEqual({ - headers: { - 'X-Grafana-Cache': 'private, max-age=60', // 1 minute in seconds - }, - }); - }); - - it('should return undefined for None cache level', () => { - const result = getDefaultCacheHeaders(PrometheusCacheLevel.None); - expect(result).toBeUndefined(); - }); - - it('should handle unknown cache level as default (1 minute)', () => { - const result = getDefaultCacheHeaders('invalid' as PrometheusCacheLevel); - expect(result).toEqual({ - headers: { - 'X-Grafana-Cache': 'private, max-age=60', // 1 minute in seconds - }, - }); - }); - }); -}); diff --git a/packages/grafana-prometheus/src/caching.ts b/packages/grafana-prometheus/src/caching.ts deleted file mode 100644 index 027a6df50f8..00000000000 --- a/packages/grafana-prometheus/src/caching.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { PrometheusCacheLevel } from './types'; - -/** - * Returns the debounce time in milliseconds based on the cache level. - * Used to control the frequency of API requests. - * - * @param {PrometheusCacheLevel} cacheLevel - The cache level (None, Low, Medium, High) - * @returns {number} Debounce time in milliseconds: - * - Medium: 600ms - * - High: 1200ms - * - Default (None/Low): 350ms - */ -export const getDebounceTimeInMilliseconds = (cacheLevel: PrometheusCacheLevel): number => { - switch (cacheLevel) { - case PrometheusCacheLevel.Medium: - return 600; - case PrometheusCacheLevel.High: - return 1200; - default: - return 350; - } -}; - -/** - * Returns the number of days to cache metadata based on the cache level. - * Used for caching Prometheus metric metadata. - * - * @param {PrometheusCacheLevel} cacheLevel - The cache level (None, Low, Medium, High) - * @returns {number} Number of days to cache: - * - Medium: 7 days - * - High: 30 days - * - Default (None/Low): 1 day - */ -export const getDaysToCacheMetadata = (cacheLevel: PrometheusCacheLevel): number => { - switch (cacheLevel) { - case PrometheusCacheLevel.Medium: - return 7; - case PrometheusCacheLevel.High: - return 30; - default: - return 1; - } -}; - -/** - * Returns the cache duration in minutes based on the cache level. - * Used for general API response caching. - * - * @param {PrometheusCacheLevel} cacheLevel - The cache level (None, Low, Medium, High) - * @returns Cache duration in minutes: - * - Medium: 10 minutes - * - High: 60 minutes - * - Default (None/Low): 1 minute - */ -export const getCacheDurationInMinutes = (cacheLevel: PrometheusCacheLevel) => { - switch (cacheLevel) { - case PrometheusCacheLevel.Medium: - return 10; - case PrometheusCacheLevel.High: - return 60; - default: - return 1; - } -}; - -/** - * Builds cache headers for Prometheus API requests. - * Creates a standard cache control header with private scope and max-age directive. - * - * @param {number} durationInSeconds - Cache duration in seconds - * @returns Object containing headers with cache control directives: - * - X-Grafana-Cache: private, max-age= - * @example - * // Returns { headers: { 'X-Grafana-Cache': 'private, max-age=300' } } - * buildCacheHeaders(300) - */ -export const buildCacheHeaders = (durationInSeconds: number) => { - return { - headers: { - 'X-Grafana-Cache': `private, max-age=${durationInSeconds}`, - }, - }; -}; - -/** - * Gets appropriate cache headers based on the configured cache level. - * Converts cache duration from minutes to seconds and builds the headers. - * Returns undefined if caching is disabled (None level). - * - * @param {PrometheusCacheLevel} cacheLevel - Cache level (None, Low, Medium, High) - * @returns Cache headers object or undefined if caching is disabled - * @example - * // For Medium level, returns { headers: { 'X-Grafana-Cache': 'private, max-age=600' } } - * getDefaultCacheHeaders(PrometheusCacheLevel.Medium) - */ -export const getDefaultCacheHeaders = (cacheLevel: PrometheusCacheLevel) => { - if (cacheLevel !== PrometheusCacheLevel.None) { - return buildCacheHeaders(getCacheDurationInMinutes(cacheLevel) * 60); - } - return; -}; diff --git a/packages/grafana-prometheus/src/components/AnnotationQueryEditor.test.tsx b/packages/grafana-prometheus/src/components/AnnotationQueryEditor.test.tsx deleted file mode 100644 index 4929ef3d7e7..00000000000 --- a/packages/grafana-prometheus/src/components/AnnotationQueryEditor.test.tsx +++ /dev/null @@ -1,165 +0,0 @@ -// Core Grafana testing pattern -import { fireEvent, render, screen } from '@testing-library/react'; - -import { type AnnotationQuery } from '@grafana/data'; -import { selectors } from '@grafana/e2e-selectors'; - -import { type PrometheusDatasource } from '../datasource'; -import { type PrometheusLanguageProviderInterface } from '../language_provider'; -import { EmptyLanguageProviderMock } from '../language_provider.mock'; -import { type PromQuery } from '../types'; - -import { AnnotationQueryEditor } from './AnnotationQueryEditor'; - -// Mock the PromQueryCodeEditor to avoid errors related to PromQueryField rendering -jest.mock('../querybuilder/components/PromQueryCodeEditor', () => ({ - PromQueryCodeEditor: () =>
Query Editor
, -})); - -describe('AnnotationQueryEditor', () => { - const mockOnChange = jest.fn(); - const mockOnAnnotationChange = jest.fn(); - const mockOnRunQuery = jest.fn(); - - const mockQuery: PromQuery = { - refId: 'test', - expr: 'test_metric', - interval: '', - exemplar: true, - instant: false, - range: true, - }; - - const mockAnnotation: AnnotationQuery = { - name: 'Test annotation', - enable: true, - iconColor: 'red', - datasource: { - type: 'prometheus', - uid: 'test', - }, - target: mockQuery, - hide: false, - titleFormat: '{{alertname}}', - textFormat: '{{instance}}', - tagKeys: 'label1,label2', - useValueForTime: false, - }; - - function createMockDatasource() { - const languageProvider = new EmptyLanguageProviderMock() as unknown as PrometheusLanguageProviderInterface; - const mockDatasource = { - languageProvider, - lookupsDisabled: false, - modifyQuery: jest.fn().mockImplementation((query) => query), - getQueryHints: jest.fn().mockReturnValue([]), - } as unknown as PrometheusDatasource; - - return mockDatasource; - } - - const defaultProps = { - query: mockQuery, - onChange: mockOnChange, - onRunQuery: mockOnRunQuery, - annotation: mockAnnotation, - onAnnotationChange: mockOnAnnotationChange, - datasource: createMockDatasource(), - }; - - beforeEach(() => { - jest.clearAllMocks(); - }); - - it('renders without error', () => { - render(); - expect(screen.getByText('Min step')).toBeInTheDocument(); - expect(screen.getByText('Title')).toBeInTheDocument(); - expect(screen.getByText('Tags')).toBeInTheDocument(); - expect(screen.getByText('Text')).toBeInTheDocument(); - expect(screen.getByText('Series value as timestamp')).toBeInTheDocument(); - expect(screen.getByTestId('mock-prom-code-editor')).toBeInTheDocument(); - }); - - it('displays an error message when annotation data is missing', () => { - render(); - expect(screen.getByText('Annotation data load error!')).toBeInTheDocument(); - }); - - it('displays an error message when onAnnotationChange is missing', () => { - render(); - expect(screen.getByText('Annotation data load error!')).toBeInTheDocument(); - }); - - it('renders correctly with an empty annotation object', () => { - render(} />); - // Should render normally with empty values but not show an error - expect(screen.getByText('Min step')).toBeInTheDocument(); - expect(screen.getByText('Title')).toBeInTheDocument(); - expect(screen.queryByText('Annotation data load error!')).not.toBeInTheDocument(); - }); - - it('calls onChange when min step is updated', () => { - render(); - const minStepInput = screen.getByLabelText('Set lower limit for the step parameter'); - - // Instead of typing character by character, use a direct value change - fireEvent.change(minStepInput, { target: { value: '10s' } }); - fireEvent.blur(minStepInput); - - expect(mockOnChange).toHaveBeenCalledWith({ - ...mockQuery, - interval: '10s', - }); - }); - - it('calls onAnnotationChange when title format is updated', () => { - render(); - const titleInput = screen.getByTestId(selectors.components.DataSource.Prometheus.annotations.title); - - fireEvent.change(titleInput, { target: { value: '{{job}}' } }); - fireEvent.blur(titleInput); - - expect(mockOnAnnotationChange).toHaveBeenCalledWith({ - ...mockAnnotation, - titleFormat: '{{job}}', - }); - }); - - it('calls onAnnotationChange when tags are updated', () => { - render(); - const tagsInput = screen.getByTestId(selectors.components.DataSource.Prometheus.annotations.tags); - - fireEvent.change(tagsInput, { target: { value: 'job,instance' } }); - fireEvent.blur(tagsInput); - - expect(mockOnAnnotationChange).toHaveBeenCalledWith({ - ...mockAnnotation, - tagKeys: 'job,instance', - }); - }); - - it('calls onAnnotationChange when text format is updated', () => { - render(); - const textInput = screen.getByTestId(selectors.components.DataSource.Prometheus.annotations.text); - - fireEvent.change(textInput, { target: { value: '{{metric}}' } }); - fireEvent.blur(textInput); - - expect(mockOnAnnotationChange).toHaveBeenCalledWith({ - ...mockAnnotation, - textFormat: '{{metric}}', - }); - }); - - it('calls onAnnotationChange when series value as timestamp is toggled', () => { - render(); - const toggle = screen.getByTestId(selectors.components.DataSource.Prometheus.annotations.seriesValueAsTimestamp); - fireEvent.click(toggle); - - expect(mockOnAnnotationChange).toHaveBeenCalledWith({ - ...mockAnnotation, - useValueForTime: true, - }); - }); -}); diff --git a/packages/grafana-prometheus/src/components/AnnotationQueryEditor.tsx b/packages/grafana-prometheus/src/components/AnnotationQueryEditor.tsx deleted file mode 100644 index a5f4a58c31c..00000000000 --- a/packages/grafana-prometheus/src/components/AnnotationQueryEditor.tsx +++ /dev/null @@ -1,170 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/AnnotationQueryEditor.tsx - -import { memo } from 'react'; - -import { type AnnotationQuery } from '@grafana/data'; -import { selectors } from '@grafana/e2e-selectors'; -import { Trans, t } from '@grafana/i18n'; -import { EditorField, EditorRow, EditorRows, EditorSwitch } from '@grafana/plugin-ui'; -import { AutoSizeInput, Input, Space } from '@grafana/ui'; - -import { PromQueryCodeEditor } from '../querybuilder/components/PromQueryCodeEditor'; -import { type PromQuery } from '../types'; - -import { type PromQueryEditorProps } from './types'; - -type Props = PromQueryEditorProps & { - annotation?: AnnotationQuery; - onAnnotationChange?: (annotation: AnnotationQuery) => void; -}; - -const PLACEHOLDER_TITLE = '{{alertname}}'; -const PLACEHOLDER_TEXT = '{{instance}}'; -const PLACEHOLDER_TAGS = 'label1,label2'; - -/** - * AnnotationQueryEditor component for Prometheus datasource. - * Allows users to configure annotation queries with options for title, tags, text format, - * and timestamp settings. - */ -export const AnnotationQueryEditor = memo(function AnnotationQueryEditor(props: Props) { - const { annotation, onAnnotationChange, onChange, onRunQuery, query } = props; - - if (!annotation || !onAnnotationChange) { - return ( -

- - Annotation data load error! - -

- ); - } - - const handleMinStepChange = (value: string) => { - onChange({ ...query, interval: value }); - }; - - const handleTitleChange = (value: string) => { - onAnnotationChange({ - ...annotation, - titleFormat: value, - }); - }; - - const handleTagsChange = (value: string) => { - onAnnotationChange({ - ...annotation, - tagKeys: value, - }); - }; - - const handleTextChange = (value: string) => { - onAnnotationChange({ - ...annotation, - textFormat: value, - }); - }; - - const handleUseValueForTimeChange = (checked: boolean) => { - onAnnotationChange({ - ...annotation, - useValueForTime: checked, - }); - }; - - return ( - <> - - - - - An additional lower limit for the step parameter of the Prometheus query and for the{' '} - {'{{intervalVar}}'} and {'{{rateIntervalVar}}'} variables. - - } - > - handleMinStepChange(e.currentTarget.value)} - id={selectors.components.DataSource.Prometheus.annotations.minStep} - data-testid={selectors.components.DataSource.Prometheus.annotations.minStep} - /> - - - - - - - handleTitleChange(event.currentTarget.value)} - data-testid={selectors.components.DataSource.Prometheus.annotations.title} - /> - - - handleTagsChange(event.currentTarget.value)} - data-testid={selectors.components.DataSource.Prometheus.annotations.tags} - /> - - - handleTextChange(event.currentTarget.value)} - data-testid={selectors.components.DataSource.Prometheus.annotations.text} - /> - - - handleUseValueForTimeChange(event.currentTarget.checked)} - data-testid={selectors.components.DataSource.Prometheus.annotations.seriesValueAsTimestamp} - /> - - - - ); -}); diff --git a/packages/grafana-prometheus/src/components/PromCheatSheet.tsx b/packages/grafana-prometheus/src/components/PromCheatSheet.tsx deleted file mode 100644 index 20399c474d2..00000000000 --- a/packages/grafana-prometheus/src/components/PromCheatSheet.tsx +++ /dev/null @@ -1,76 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/PromCheatSheet.tsx -import { css } from '@emotion/css'; - -import { type GrafanaTheme2, type QueryEditorHelpProps } from '@grafana/data'; -import { Trans } from '@grafana/i18n'; -import { useStyles2 } from '@grafana/ui'; - -import { type PromQuery } from '../types'; - -const CHEAT_SHEET_ITEMS = [ - { - title: 'Request Rate', - expression: 'rate(http_request_total[5m])', - label: - 'Given an HTTP request counter, this query calculates the per-second average request rate over the last 5 minutes.', - }, - { - title: '95th Percentile of Request Latencies', - expression: 'histogram_quantile(0.95, sum(rate(prometheus_http_request_duration_seconds_bucket[5m])) by (le))', - label: 'Calculates the 95th percentile of HTTP request rate over 5 minute windows.', - }, - { - title: 'Alerts Firing', - expression: 'sort_desc(sum(sum_over_time(ALERTS{alertstate="firing"}[24h])) by (alertname))', - label: 'Sums up the alerts that have been firing over the last 24 hours.', - }, - { - title: 'Step', - label: - 'Defines the graph resolution using a duration format (15s, 1m, 3h, ...). Small steps create high-resolution graphs but can be slow over larger time ranges. Using a longer step lowers the resolution and smooths the graph by producing fewer datapoints. If no step is given the resolution is calculated automatically.', - }, -]; - -export const PromCheatSheet = (props: QueryEditorHelpProps) => { - const styles = useStyles2(getStyles); - - return ( -
-

- PromQL Cheat Sheet -

- {CHEAT_SHEET_ITEMS.map((item, index) => ( -
-
{item.title}
- {item.expression ? ( - - ) : null} - {item.label} -
- ))} -
- ); -}; - -const getStyles = (theme: GrafanaTheme2) => ({ - cheatSheetItem: css({ - margin: theme.spacing(3, 0), - }), - cheatSheetItemTitle: css({ - fontSize: theme.typography.h3.fontSize, - }), - cheatSheetExample: css({ - margin: theme.spacing(0.5, 0), - // element is interactive, clear button styles - textAlign: 'left', - border: 'none', - background: 'transparent', - display: 'block', - }), -}); diff --git a/packages/grafana-prometheus/src/components/PromExemplarField.tsx b/packages/grafana-prometheus/src/components/PromExemplarField.tsx deleted file mode 100644 index a76e1b817b4..00000000000 --- a/packages/grafana-prometheus/src/components/PromExemplarField.tsx +++ /dev/null @@ -1,91 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/PromExemplarField.tsx -import { css, cx } from '@emotion/css'; -import { useEffect, useState } from 'react'; -import { usePrevious } from 'react-use'; - -import { type GrafanaTheme2 } from '@grafana/data'; -import { Trans, t } from '@grafana/i18n'; -import { IconButton, InlineLabel, Tooltip, useStyles2 } from '@grafana/ui'; - -import { type PrometheusDatasource } from '../datasource'; -import { type PromQuery } from '../types'; - -interface Props { - onChange: (exemplar: boolean) => void; - datasource: PrometheusDatasource; - query: PromQuery; - 'data-testid'?: string; -} - -export function PromExemplarField({ datasource, onChange, query, ...rest }: Props) { - const [error, setError] = useState(null); - const styles = useStyles2(getStyles); - const prevError = usePrevious(error); - - useEffect(() => { - if (!datasource.exemplarsAvailable) { - setError('Exemplars for this query are not available'); - onChange(false); - } else if (query.instant && !query.range) { - setError('Exemplars are not available for instant queries'); - onChange(false); - } else { - setError(null); - // If error is cleared, we want to change exemplar to true - if (prevError && !error) { - onChange(true); - } - } - }, [datasource.exemplarsAvailable, query.instant, query.range, onChange, prevError, error]); - - const iconButtonStyles = cx( - { - [styles.activeIcon]: !!query.exemplar, - }, - styles.eyeIcon - ); - - return ( - - -
- Exemplars - { - onChange(!query.exemplar); - }} - /> -
-
-
- ); -} - -function getStyles(theme: GrafanaTheme2) { - return { - eyeIcon: css({ - marginLeft: theme.spacing(2), - }), - activeIcon: css({ - color: theme.colors.primary.main, - }), - iconWrapper: css({ - display: 'flex', - alignItems: 'center', - }), - }; -} diff --git a/packages/grafana-prometheus/src/components/PromExploreExtraField.test.tsx b/packages/grafana-prometheus/src/components/PromExploreExtraField.test.tsx deleted file mode 100644 index 01e7845cd18..00000000000 --- a/packages/grafana-prometheus/src/components/PromExploreExtraField.test.tsx +++ /dev/null @@ -1,41 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/PromExploreExtraField.test.tsx -import { render, screen } from '@testing-library/react'; - -import { type PrometheusDatasource } from '../datasource'; -import { type PromQuery } from '../types'; - -import { - PromExploreExtraField, - type PromExploreExtraFieldProps, - promExploreExtraFieldTestIds, -} from './PromExploreExtraField'; - -const setup = (propOverrides?: PromExploreExtraFieldProps) => { - const query = { exemplar: false } as PromQuery; - const datasource = {} as PrometheusDatasource; - const onChange = jest.fn(); - const onRunQuery = jest.fn(); - - const props: PromExploreExtraFieldProps = { - onChange, - onRunQuery, - query, - datasource, - }; - - Object.assign(props, propOverrides); - - return render(); -}; - -describe('PromExploreExtraField', () => { - it('should render step field', () => { - setup(); - expect(screen.getByTestId(promExploreExtraFieldTestIds.stepField)).toBeInTheDocument(); - }); - - it('should render query type field', () => { - setup(); - expect(screen.getByTestId(promExploreExtraFieldTestIds.queryTypeField)).toBeInTheDocument(); - }); -}); diff --git a/packages/grafana-prometheus/src/components/PromExploreExtraField.tsx b/packages/grafana-prometheus/src/components/PromExploreExtraField.tsx deleted file mode 100644 index 93c2152820f..00000000000 --- a/packages/grafana-prometheus/src/components/PromExploreExtraField.tsx +++ /dev/null @@ -1,191 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx -import { css, cx } from '@emotion/css'; -import { isEqual } from 'lodash'; -import { memo, useCallback } from 'react'; -import * as React from 'react'; -import { usePrevious } from 'react-use'; - -import { type GrafanaTheme2 } from '@grafana/data'; -import { t, Trans } from '@grafana/i18n'; -import { InlineFormLabel, RadioButtonGroup, useStyles2 } from '@grafana/ui'; - -import { type PrometheusDatasource } from '../datasource'; -import { type PromQuery } from '../types'; - -import { PromExemplarField } from './PromExemplarField'; - -export interface PromExploreExtraFieldProps { - query: PromQuery; - onChange: (value: PromQuery) => void; - onRunQuery: () => void; - datasource: PrometheusDatasource; -} - -export const PromExploreExtraField = memo(({ query, datasource, onChange, onRunQuery }: PromExploreExtraFieldProps) => { - const rangeOptions = getQueryTypeOptions(true); - const prevQuery = usePrevious(query); - const styles = useStyles2(getStyles); - - const onExemplarChange = useCallback( - (exemplar: boolean) => { - if (!isEqual(query, prevQuery) || exemplar !== query.exemplar) { - onChange({ ...query, exemplar }); - } - }, - [prevQuery, query, onChange] - ); - - function onChangeQueryStep(interval: string) { - onChange({ ...query, interval }); - } - - function onStepChange(e: React.SyntheticEvent) { - if (e.currentTarget.value !== query.interval) { - onChangeQueryStep(e.currentTarget.value); - } - } - - function onReturnKeyDown(e: React.KeyboardEvent) { - if (e.key === 'Enter' && e.shiftKey) { - onRunQuery(); - } - } - - const onQueryTypeChange = getQueryTypeChangeHandler(query, onChange); - - return ( -
- {/*Query type field*/} -
- - Query type - - - -
- {/*Step field*/} -
- - Min step - - -
- - -
- ); -}); - -PromExploreExtraField.displayName = 'PromExploreExtraField'; - -export function getQueryTypeOptions(includeBoth: boolean) { - const rangeOptions = [ - { - value: 'range', - label: t('grafana-prometheus.components.get-query-type-options.range-options.label.range', 'Range'), - description: t( - 'grafana-prometheus.components.get-query-type-options.range-options.description.query-range', - 'Run query over a range of time' - ), - }, - { - value: 'instant', - label: t('grafana-prometheus.components.get-query-type-options.range-options.label.instant', 'Instant'), - description: 'Run query against a single point in time. For this query, the "To" time is used', - }, - ]; - - if (includeBoth) { - rangeOptions.push({ - value: 'both', - label: t('grafana-prometheus.components.get-query-type-options.label.both', 'Both'), - description: t( - 'grafana-prometheus.components.get-query-type-options.description.instant-query-range', - 'Run an Instant query and a Range query' - ), - }); - } - - return rangeOptions; -} - -export function getQueryTypeChangeHandler(query: PromQuery, onChange: (update: PromQuery) => void) { - return (queryType: string) => { - if (queryType === 'instant') { - onChange({ ...query, instant: true, range: false, exemplar: false }); - } else if (queryType === 'range') { - onChange({ ...query, instant: false, range: true }); - } else { - onChange({ ...query, instant: true, range: true }); - } - }; -} - -export const promExploreExtraFieldTestIds = { - extraFieldEditor: 'prom-editor-extra-field', - stepField: 'prom-editor-extra-field-step', - queryTypeField: 'prom-editor-extra-field-query-type', -}; - -const getStyles = (theme: GrafanaTheme2) => ({ - queryTypeField: css({ - marginRight: theme.spacing(0.5), - }), -}); diff --git a/packages/grafana-prometheus/src/components/PromQueryEditorByApp.test.tsx b/packages/grafana-prometheus/src/components/PromQueryEditorByApp.test.tsx deleted file mode 100644 index cc4304cf597..00000000000 --- a/packages/grafana-prometheus/src/components/PromQueryEditorByApp.test.tsx +++ /dev/null @@ -1,78 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/PromQueryEditorByApp.test.tsx -import { render, screen } from '@testing-library/react'; -import { noop } from 'lodash'; - -import { CoreApp } from '@grafana/data'; - -import { type PrometheusDatasource } from '../datasource'; - -import { PromQueryEditorByApp } from './PromQueryEditorByApp'; -import { alertingTestIds } from './PromQueryEditorForAlerting'; -import { type Props } from './monaco-query-field/MonacoQueryFieldProps'; - -// the monaco-based editor uses lazy-loading and that does not work -// well with this test, and we do not need the monaco-related -// functionality in this test anyway, so we mock it out. -jest.mock('./monaco-query-field/MonacoQueryFieldLazy', () => { - const fakeQueryField = (props: Props) => { - return props.onBlur(e.currentTarget.value)} data-testid={'dummy-code-input'} type={'text'} />; - }; - return { - MonacoQueryFieldLazy: fakeQueryField, - }; -}); - -function setup(app: CoreApp): { onRunQuery: jest.Mock } { - const dataSource = { - getPrometheusTime: jest.fn((date, roundup) => 123), - getQueryHints: jest.fn(() => []), - languageProvider: { - start: () => Promise.resolve([]), - retrieveMetrics: () => [], - }, - } as unknown as PrometheusDatasource; - const onRunQuery = jest.fn(); - - render( - - ); - - return { - onRunQuery, - }; -} - -describe('PromQueryEditorByApp', () => { - it('should render simplified query editor for cloud alerting', async () => { - setup(CoreApp.CloudAlerting); - - expect(await screen.findByTestId(alertingTestIds.editor)).toBeInTheDocument(); - }); - - it('should render editor selector for unkown apps', () => { - setup(CoreApp.Unknown); - - expect(screen.getByTestId('QueryEditorModeToggle')).toBeInTheDocument(); - expect(screen.queryByTestId(alertingTestIds.editor)).toBeNull(); - }); - - it('should render editor selector for explore', () => { - setup(CoreApp.Explore); - - expect(screen.getByTestId('QueryEditorModeToggle')).toBeInTheDocument(); - expect(screen.queryByTestId(alertingTestIds.editor)).toBeNull(); - }); - - it('should render editor selector for dashboard', () => { - setup(CoreApp.Dashboard); - - expect(screen.getByTestId('QueryEditorModeToggle')).toBeInTheDocument(); - expect(screen.queryByTestId(alertingTestIds.editor)).toBeNull(); - }); -}); diff --git a/packages/grafana-prometheus/src/components/PromQueryEditorByApp.tsx b/packages/grafana-prometheus/src/components/PromQueryEditorByApp.tsx deleted file mode 100644 index d2ffc320ffd..00000000000 --- a/packages/grafana-prometheus/src/components/PromQueryEditorByApp.tsx +++ /dev/null @@ -1,22 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/PromQueryEditorByApp.tsx -import { memo } from 'react'; - -import { CoreApp } from '@grafana/data'; - -import { PromQueryEditorSelector } from '../querybuilder/components/PromQueryEditorSelector'; - -import { PromQueryEditorForAlerting } from './PromQueryEditorForAlerting'; -import { type PromQueryEditorProps } from './types'; - -function PromQueryEditorByAppBase(props: PromQueryEditorProps) { - const { app } = props; - - switch (app) { - case CoreApp.CloudAlerting: - return ; - default: - return ; - } -} - -export const PromQueryEditorByApp = memo(PromQueryEditorByAppBase); diff --git a/packages/grafana-prometheus/src/components/PromQueryEditorForAlerting.tsx b/packages/grafana-prometheus/src/components/PromQueryEditorForAlerting.tsx deleted file mode 100644 index d0da6af00cf..00000000000 --- a/packages/grafana-prometheus/src/components/PromQueryEditorForAlerting.tsx +++ /dev/null @@ -1,24 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/PromQueryEditorForAlerting.tsx -import { PromQueryField } from './PromQueryField'; -import { type PromQueryEditorProps } from './types'; - -export function PromQueryEditorForAlerting(props: PromQueryEditorProps) { - const { datasource, query, range, data, onChange, onRunQuery } = props; - - return ( - - ); -} - -export const alertingTestIds = { - editor: 'prom-editor-cloud-alerting', -}; diff --git a/packages/grafana-prometheus/src/components/PromQueryField.test.tsx b/packages/grafana-prometheus/src/components/PromQueryField.test.tsx deleted file mode 100644 index a61bb6c72cb..00000000000 --- a/packages/grafana-prometheus/src/components/PromQueryField.test.tsx +++ /dev/null @@ -1,148 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/PromQueryField.test.tsx -import { getByTestId, render, screen } from '@testing-library/react'; -// @ts-ignore -import userEvent from '@testing-library/user-event'; - -import { CoreApp, type DataFrame, dateTime, LoadingState, type PanelData } from '@grafana/data'; - -import { type PrometheusDatasource } from '../datasource'; -import * as queryHints from '../query_hints'; - -import { PromQueryField } from './PromQueryField'; -import { type Props } from './monaco-query-field/MonacoQueryFieldProps'; - -// the monaco-based editor uses lazy-loading and that does not work -// well with this test, and we do not need the monaco-related -// functionality in this test anyway, so we mock it out. -jest.mock('./monaco-query-field/MonacoQueryFieldLazy', () => { - const fakeQueryField = (props: Props) => { - return props.onBlur(e.currentTarget.value)} data-testid={'dummy-code-input'} type={'text'} />; - }; - return { - MonacoQueryFieldLazy: fakeQueryField, - }; -}); - -const defaultProps = { - datasource: { - languageProvider: { - start: () => Promise.resolve([]), - syntax: () => {}, - // getLabelKeys: () => [], - retrieveMetrics: () => [], - }, - } as unknown as PrometheusDatasource, - query: { - expr: '', - refId: '', - }, - onRunQuery: () => {}, - onChange: () => {}, - history: [], - range: { - from: dateTime('2022-01-01T00:00:00Z'), - to: dateTime('2022-01-02T00:00:00Z'), - raw: { - from: 'now-1d', - to: 'now', - }, - }, -}; - -describe('PromQueryField', () => { - beforeAll(() => { - // @ts-ignore - window.getSelection = () => {}; - }); - - beforeEach(() => { - jest.clearAllMocks(); - }); - - it('renders metrics chooser regularly if lookups are not disabled in the datasource settings', async () => { - const queryField = render(); - - // wait for component to render - await screen.findByRole('button'); - - expect(queryField.getAllByRole('button')).toHaveLength(1); - }); - - it('renders a disabled metrics chooser if lookups are disabled in datasource settings', async () => { - const props = defaultProps; - props.datasource.lookupsDisabled = true; - const queryField = render(); - - // wait for component to render - await screen.findByRole('button'); - - const bcButton = queryField.getByRole('button'); - expect(bcButton).toBeDisabled(); - }); - - it('renders no metrics chooser if hidden by props', async () => { - const props = { - ...defaultProps, - hideMetricsBrowser: true, - }; - const queryField = render(); - - // wait for component to render - await screen.findByTestId('dummy-code-input'); - - expect(queryField.queryByRole('button')).not.toBeInTheDocument(); - }); - - it('renders an initial hint if no data and initial hint provided', async () => { - const props = defaultProps; - props.datasource.lookupsDisabled = true; - - jest.spyOn(queryHints, 'getInitHints').mockReturnValue([{ label: 'Initial hint', type: 'INFO' }]); - - render(); - - // wait for component to render - await screen.findByRole('button'); - - expect(screen.getByText('Initial hint')).toBeInTheDocument(); - }); - - it('renders query hint if data, query hint and initial hint provided', async () => { - const props = defaultProps; - props.datasource.lookupsDisabled = true; - props.datasource.getQueryHints = () => [{ label: 'Query hint', type: 'INFO' }]; - render( - - ); - - // wait for component to render - await screen.findByRole('button'); - - expect(screen.getByText('Query hint')).toBeInTheDocument(); - expect(screen.queryByText('Initial hint')).not.toBeInTheDocument(); - }); - - it('should not run query onBlur', async () => { - const onRunQuery = jest.fn(); - const { container } = render(); - - // wait for component to rerender - await screen.findByRole('button'); - - const input = getByTestId(container, 'dummy-code-input'); - expect(input).toBeInTheDocument(); - await userEvent.type(input, 'metric'); - - // blur element - await userEvent.click(document.body); - expect(onRunQuery).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/grafana-prometheus/src/components/PromQueryField.tsx b/packages/grafana-prometheus/src/components/PromQueryField.tsx deleted file mode 100644 index ebe1fec493d..00000000000 --- a/packages/grafana-prometheus/src/components/PromQueryField.tsx +++ /dev/null @@ -1,183 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/PromQueryField.tsx -import { css, cx } from '@emotion/css'; -import { type ReactNode, useCallback, useEffect, useState } from 'react'; - -import { - type DataFrame, - getDefaultTimeRange, - isDataFrame, - type QueryEditorProps, - type QueryHint, - toLegacyResponseData, -} from '@grafana/data'; -import { selectors } from '@grafana/e2e-selectors'; -import { t, Trans } from '@grafana/i18n'; -import { reportInteraction } from '@grafana/runtime'; -import { clearButtonStyles, Icon, useTheme2 } from '@grafana/ui'; - -import { type PrometheusDatasource } from '../datasource'; -import { getInitHints } from '../query_hints'; -import { type PromOptions, type PromQuery } from '../types'; - -import { MetricsBrowser } from './metrics-browser/MetricsBrowser'; -import { MetricsBrowserProvider } from './metrics-browser/MetricsBrowserContext'; -import { MonacoQueryFieldWrapper } from './monaco-query-field/MonacoQueryFieldWrapper'; - -interface PromQueryFieldProps extends QueryEditorProps { - ExtraFieldElement?: ReactNode; - hideMetricsBrowser?: boolean; - 'data-testid'?: string; -} - -export const PromQueryField = (props: PromQueryFieldProps) => { - const { - app, - datasource, - datasource: { languageProvider }, - query, - ExtraFieldElement, - history = [], - data, - range, - onChange, - onRunQuery, - hideMetricsBrowser = false, - } = props; - - const theme = useTheme2(); - - const [hint, setHint] = useState(null); - const [labelBrowserVisible, setLabelBrowserVisible] = useState(false); - - const refreshHint = useCallback( - (series: DataFrame[]) => { - const initHints = getInitHints(datasource); - const initHint = initHints[0] ?? null; - - // If no data or empty series, use default hint - if (!data?.series?.length) { - setHint(initHint); - return; - } - - const result = isDataFrame(series[0]) ? series.map(toLegacyResponseData) : series; - const queryHints = datasource.getQueryHints(query, result); - let queryHint = queryHints.length > 0 ? queryHints[0] : null; - - setHint(queryHint ?? initHint); - }, - [data, datasource, query] - ); - - useEffect(() => { - refreshHint(data?.series ?? []); - }, [data?.series, refreshHint]); - - const onChangeQuery = (value: string, override?: boolean) => { - if (!onChange) { - return; - } - // Send text change to parent - const nextQuery: PromQuery = { ...query, expr: value }; - onChange(nextQuery); - - if (override && onRunQuery) { - onRunQuery(); - } - }; - - const onChangeLabelBrowser = (selector: string) => { - onChangeQuery(selector, true); - setLabelBrowserVisible(false); - }; - - const onClickChooserButton = () => { - setLabelBrowserVisible(!labelBrowserVisible); - - reportInteraction('user_grafana_prometheus_metrics_browser_clicked', { - editorMode: labelBrowserVisible ? 'metricViewClosed' : 'metricViewOpen', - app: app ?? '', - }); - }; - - const onClickHintFix = () => { - if (hint?.fix?.action) { - onChange(datasource.modifyQuery(query, hint.fix.action)); - } - onRunQuery(); - }; - - return ( - <> -
- {!hideMetricsBrowser && ( - - )} - -
- -
-
- {labelBrowserVisible && ( -
- - - -
- )} - {ExtraFieldElement} - {hint ? ( -
-
- {hint.label}{' '} - {hint.fix ? ( - - ) : null} -
-
- ) : null} - - ); -}; diff --git a/packages/grafana-prometheus/src/components/VariableQueryEditor.test.tsx b/packages/grafana-prometheus/src/components/VariableQueryEditor.test.tsx deleted file mode 100644 index f1b014058b6..00000000000 --- a/packages/grafana-prometheus/src/components/VariableQueryEditor.test.tsx +++ /dev/null @@ -1,378 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/VariableQueryEditor.test.tsx -import { render, screen, waitFor } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { select } from 'react-select-event'; - -import { selectors } from '@grafana/e2e-selectors'; - -import { type PrometheusDatasource } from '../datasource'; -import { type PrometheusLanguageProviderInterface } from '../language_provider'; -import { migrateVariableEditorBackToVariableSupport } from '../migrations/variableMigration'; -import { type PromVariableQuery, PromVariableQueryType, type StandardPromVariableQuery } from '../types'; - -import { PromVariableQueryEditor, type Props, variableMigration } from './VariableQueryEditor'; - -const refId = 'PrometheusVariableQueryEditor-VariableQuery'; - -describe('PromVariableQueryEditor', () => { - let props: Props; - - test('Migrates from standard variable support to custom variable query', () => { - const query: StandardPromVariableQuery = { - query: 'label_names()', - refId: 'StandardVariableQuery', - }; - - const migration: PromVariableQuery = variableMigration(query); - - const expected: PromVariableQuery = { - qryType: PromVariableQueryType.LabelNames, - refId: 'PrometheusDatasource-VariableQuery', - }; - - expect(migration).toEqual(expected); - }); - - test('Allows for use of variables to interpolate label names in the label values query type.', () => { - const query: StandardPromVariableQuery = { - query: 'label_values($label_name)', - refId: 'StandardVariableQuery', - }; - - const migration: PromVariableQuery = variableMigration(query); - - const expected: PromVariableQuery = { - qryType: PromVariableQueryType.LabelValues, - label: '$label_name', - refId: 'PrometheusDatasource-VariableQuery', - }; - - expect(migration).toEqual(expected); - }); - - test('Migrates from jsonnet grafana as code variable to custom variable query', () => { - const query = 'label_names()'; - - const migration: PromVariableQuery = variableMigration(query); - - const expected: PromVariableQuery = { - qryType: PromVariableQueryType.LabelNames, - refId: 'PrometheusDatasource-VariableQuery', - }; - - expect(migration).toEqual(expected); - }); - - test('Migrates label filters to the query object for label_values()', () => { - const query: StandardPromVariableQuery = { - query: 'label_values(metric{label="value"},name)', - refId: 'StandardVariableQuery', - }; - - const migration: PromVariableQuery = variableMigration(query); - - const expected: PromVariableQuery = { - qryType: PromVariableQueryType.LabelValues, - label: 'name', - metric: 'metric', - labelFilters: [ - { - label: 'label', - op: '=', - value: 'value', - }, - ], - refId: 'PrometheusDatasource-VariableQuery', - }; - - expect(migration).toEqual(expected); - }); - - test('Migrates a query object with label filters to an expression correctly', () => { - const query: PromVariableQuery = { - qryType: PromVariableQueryType.LabelValues, - label: 'name', - metric: 'metric', - labelFilters: [ - { - label: 'label', - op: '=', - value: 'value', - }, - ], - refId: 'PrometheusDatasource-VariableQuery', - }; - - const migration: string = migrateVariableEditorBackToVariableSupport(query); - - const expected = 'label_values(metric{label="value"},name)'; - - expect(migration).toEqual(expected); - }); - - test('Migrates a query object with no metric and only label filters to an expression correctly', () => { - const query: PromVariableQuery = { - qryType: PromVariableQueryType.LabelValues, - label: 'name', - labelFilters: [ - { - label: 'label', - op: '=', - value: 'value', - }, - ], - refId: 'PrometheusDatasource-VariableQuery', - }; - - const migration: string = migrateVariableEditorBackToVariableSupport(query); - - const expected = 'label_values({label="value"},name)'; - - expect(migration).toEqual(expected); - }); - - beforeEach(() => { - props = { - datasource: { - hasLabelsMatchAPISupport: () => true, - languageProvider: { - start: () => Promise.resolve([]), - queryLabelKeys: jest.fn().mockResolvedValue(['those']), - queryLabelValues: jest.fn().mockResolvedValue(['that']), - } as Partial, - getTagKeys: jest.fn().mockResolvedValue([{ text: 'this', value: 'this', label: 'this' }]), - getVariables: jest.fn().mockReturnValue([]), - metricFindQuery: jest.fn().mockResolvedValue([ - { - text: 'that', - value: 'that', - label: 'that', - }, - ]), - } as Partial as PrometheusDatasource, - query: { - refId: 'test', - query: 'label_names()', - }, - onRunQuery: () => {}, - onChange: () => {}, - history: [], - }; - }); - - test('Displays a group of function options', async () => { - render(); - - const select = screen.getByLabelText('Query type').parentElement!; - await userEvent.click(select); - - await waitFor(() => expect(screen.getAllByText('Label names')).toHaveLength(2)); - await waitFor(() => expect(screen.getByText('Label values')).toBeInTheDocument()); - await waitFor(() => expect(screen.getByText('Metrics')).toBeInTheDocument()); - await waitFor(() => expect(screen.getByText('Query result')).toBeInTheDocument()); - await waitFor(() => expect(screen.getByText('Series query')).toBeInTheDocument()); - await waitFor(() => expect(screen.getByText('Classic query')).toBeInTheDocument()); - }); - - test('Calls onChange for label_names(match) query', async () => { - const onChange = jest.fn(); - - props.query = { - refId: 'test', - query: '', - match: 'that', - }; - - render(); - - await waitFor(() => select(screen.getByLabelText('Query type'), 'Label names', { container: document.body })); - - expect(onChange).toHaveBeenCalledWith({ - query: 'label_names(that)', - refId, - qryType: 0, - }); - }); - - test('Calls onChange for label_names, label_values, metrics, query result and classic query.', async () => { - const onChange = jest.fn(); - - props.query = { - refId: 'test', - query: '', - }; - - render(); - - await waitFor(() => select(screen.getByLabelText('Query type'), 'Label names', { container: document.body })); - await waitFor(() => select(screen.getByLabelText('Query type'), 'Label values', { container: document.body })); - await waitFor(() => select(screen.getByLabelText('Query type'), 'Metrics', { container: document.body })); - await waitFor(() => select(screen.getByLabelText('Query type'), 'Query result', { container: document.body })); - await waitFor(() => select(screen.getByLabelText('Query type'), 'Classic query', { container: document.body })); - - expect(onChange).toHaveBeenCalledTimes(5); - }); - - test('Does not call onChange for series query', async () => { - const onChange = jest.fn(); - - render(); - - await waitFor(() => select(screen.getByLabelText('Query type'), 'Series query', { container: document.body })); - - expect(onChange).not.toHaveBeenCalled(); - }); - - test('Calls onChange for metrics() after input', async () => { - const onChange = jest.fn(); - - props.query = { - refId: 'test', - query: 'label_names()', - }; - - render(); - - await waitFor(() => select(screen.getByLabelText('Query type'), 'Metrics', { container: document.body })); - const metricInput = screen.getByLabelText('Metric selector'); - await userEvent.type(metricInput, 'a'); - const queryType = screen.getByLabelText('Query type'); - // click elsewhere to trigger the onBlur - await userEvent.click(queryType); - - await waitFor(() => - expect(onChange).toHaveBeenCalledWith({ - query: 'metrics(a)', - refId, - qryType: 2, - }) - ); - }); - - test('Calls onChange for label_values() after selecting label', async () => { - const onChange = jest.fn(); - - props.query = { - refId: 'test', - query: 'label_names()', - qryType: 0, - }; - - render(); - - await waitFor(() => select(screen.getByLabelText('Query type'), 'Label values', { container: document.body })); - const labelSelect = screen.getByTestId( - selectors.components.DataSource.Prometheus.variableQueryEditor.labelValues.labelSelect - ); - await userEvent.type(labelSelect, 'this'); - - await waitFor(() => select(labelSelect, 'this', { container: document.body })); - //display label in label select - await waitFor(() => expect(screen.getByText('this')).toBeInTheDocument()); - - await waitFor(() => - expect(onChange).toHaveBeenCalledWith({ - query: 'label_values(this)', - refId, - qryType: 1, - }) - ); - }); - - test('Calls onChange for label_values() after selecting metric', async () => { - const onChange = jest.fn(); - - props.query = { - refId: 'test', - query: 'label_names()', - }; - - render(); - - await waitFor(() => select(screen.getByLabelText('Query type'), 'Label values', { container: document.body })); - const labelSelect = screen.getByTestId( - selectors.components.DataSource.Prometheus.variableQueryEditor.labelValues.labelSelect - ); - await userEvent.type(labelSelect, 'this'); - await waitFor(() => select(labelSelect, 'this', { container: document.body })); - - const combobox = screen.getByPlaceholderText('Select metric'); - await userEvent.type(combobox, 'that'); - await userEvent.keyboard('{Enter}'); - - await waitFor(() => - expect(onChange).toHaveBeenCalledWith({ - query: 'label_values(that,this)', - refId, - qryType: 1, - }) - ); - }); - - test('Calls onChange for query_result() with argument onBlur', async () => { - const onChange = jest.fn(); - - props.query = { - refId: 'test', - query: 'query_result(a)', - }; - - render(); - - const labelSelect = screen.getByLabelText('Prometheus Query'); - await userEvent.click(labelSelect); - const functionSelect = screen.getByLabelText('Query type').parentElement!; - await userEvent.click(functionSelect); - - expect(onChange).toHaveBeenCalledWith({ - query: 'query_result(a)', - refId, - qryType: 3, - }); - }); - - test('Calls onChange for Match[] series with argument onBlur', async () => { - const onChange = jest.fn(); - - props.query = { - refId: 'test', - query: '{a: "example"}', - }; - - render(); - - const labelSelect = screen.getByLabelText('Series Query'); - await userEvent.click(labelSelect); - const functionSelect = screen.getByLabelText('Query type').parentElement!; - await userEvent.click(functionSelect); - - expect(onChange).toHaveBeenCalledWith({ - query: '{a: "example"}', - refId, - qryType: 4, - }); - }); - - test('Calls onChange for classic query onBlur', async () => { - const onChange = jest.fn(); - - props.query = { - refId: 'test', - qryType: 5, - query: 'label_values(instance)', - }; - - render(); - - const labelSelect = screen.getByLabelText('Classic Query'); - await userEvent.click(labelSelect); - const functionSelect = screen.getByLabelText('Query type').parentElement!; - await userEvent.click(functionSelect); - - expect(onChange).toHaveBeenCalledWith({ - query: 'label_values(instance)', - refId, - qryType: 5, - }); - }); -}); diff --git a/packages/grafana-prometheus/src/components/VariableQueryEditor.tsx b/packages/grafana-prometheus/src/components/VariableQueryEditor.tsx deleted file mode 100644 index b9226e1c3e7..00000000000 --- a/packages/grafana-prometheus/src/components/VariableQueryEditor.tsx +++ /dev/null @@ -1,541 +0,0 @@ -// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/components/VariableQueryEditor.tsx -import debounce from 'debounce-promise'; -import { type FormEvent, useCallback, useEffect, useState } from 'react'; - -import { getDefaultTimeRange, type QueryEditorProps, type SelectableValue, toOption } from '@grafana/data'; -import { selectors } from '@grafana/e2e-selectors'; -import { t, Trans } from '@grafana/i18n'; -import { AsyncSelect, InlineField, InlineFieldRow, Input, Select, TextArea } from '@grafana/ui'; - -import { type PrometheusDatasource } from '../datasource'; -import { truncateResult } from '../language_utils'; -import { - migrateVariableEditorBackToVariableSupport, - migrateVariableQueryToEditor, -} from '../migrations/variableMigration'; -import { MetricsLabelsSection } from '../querybuilder/components/MetricsLabelsSection'; -import { promQueryModeller } from '../querybuilder/shared/modeller_instance'; -import { type QueryBuilderLabelFilter } from '../querybuilder/shared/types'; -import { type PromVisualQuery } from '../querybuilder/types'; -import { - type PromOptions, - type PromQuery, - type PromVariableQuery, - PromVariableQueryType as QueryType, - type StandardPromVariableQuery, -} from '../types'; - -const variableOptions = [ - { label: 'Label names', value: QueryType.LabelNames }, - { label: 'Label values', value: QueryType.LabelValues }, - { label: 'Metrics', value: QueryType.MetricNames }, - { label: 'Query result', value: QueryType.VarQueryResult }, - { label: 'Series query', value: QueryType.SeriesQuery }, - { label: 'Classic query', value: QueryType.ClassicQuery }, -]; - -export type Props = QueryEditorProps; - -const refId = 'PrometheusVariableQueryEditor-VariableQuery'; - -export const PromVariableQueryEditor = ({ onChange, query, datasource, range }: Props) => { - // to select the query type, i.e. label_names, label_values, etc. - const [qryType, setQryType] = useState(undefined); - // list of variables for each function - const [label, setLabel] = useState(''); - - const [labelNamesMatch, setLabelNamesMatch] = useState(''); - - // metric is used for both label_values() and metric() - // label_values() metric requires a whole/complete metric - // metric() is expected to be a part of a metric string - const [metric, setMetric] = useState(''); - // varQuery is a whole query, can include math/rates/etc - const [varQuery, setVarQuery] = useState(''); - // seriesQuery is only a whole - const [seriesQuery, setSeriesQuery] = useState(''); - - // the original variable query implementation, e.g. label_value(metric, label_name) - const [classicQuery, setClassicQuery] = useState(''); - - // list of label names for label_values(), /api/v1/labels, contains the same results as label_names() function - const [truncatedLabelOptions, setTruncatedLabelOptions] = useState>>([]); - const [allLabelOptions, setAllLabelOptions] = useState>>([]); - - /** - * Set the both allLabels and truncatedLabels - * - * @param names - * @param variables - */ - function setLabels(names: SelectableValue[], variables: SelectableValue[]) { - setAllLabelOptions([...variables, ...names]); - const truncatedNames = truncateResult(names); - setTruncatedLabelOptions([...variables, ...truncatedNames]); - } - - // label filters have been added as a filter for metrics in label values query type - const [labelFilters, setLabelFilters] = useState([]); - - useEffect(() => { - if (!query) { - return; - } - - if (query.qryType === QueryType.ClassicQuery) { - setQryType(query.qryType); - setClassicQuery(query.query ?? ''); - } else { - // 1. Changing from standard to custom variable editor changes the string attr from expr to query - // 2. jsonnet grafana as code passes a variable as a string - const variableQuery = variableMigration(query); - - setLabelNamesMatch(variableQuery.match ?? ''); - setQryType(variableQuery.qryType); - setLabel(variableQuery.label ?? ''); - setMetric(variableQuery.metric ?? ''); - setLabelFilters(variableQuery.labelFilters ?? []); - setVarQuery(variableQuery.varQuery ?? ''); - setSeriesQuery(variableQuery.seriesQuery ?? ''); - setClassicQuery(variableQuery.classicQuery ?? ''); - } - }, [query]); - - // set the label names options for the label values var query - useEffect(() => { - if (qryType !== QueryType.LabelValues) { - return; - } - const variables = datasource.getVariables().map((variable: string) => ({ label: variable, value: variable })); - let timeRange = range; - if (!timeRange) { - timeRange = getDefaultTimeRange(); - } - - if (!metric) { - // get all the labels - datasource.getTagKeys({ timeRange, filters: [] }).then((labelNames: Array<{ text: string }>) => { - const names = labelNames.map(({ text }) => ({ label: text, value: text })); - setLabels(names, variables); - }); - } else { - // fetch the labels filtered by the metric - // eslint-disable-next-line @grafana/i18n/no-untranslated-strings - const labelToConsider = [{ label: '__name__', op: '=', value: metric }]; - const expr = promQueryModeller.renderLabels(labelToConsider); - - datasource.languageProvider.queryLabelKeys(timeRange, expr).then((labelNames: string[]) => { - const names = labelNames.map((value) => ({ label: value, value: value })); - setLabels(names, variables); - }); - } - }, [datasource, qryType, metric, range]); - - const onChangeWithVariableString = ( - updateVar: { [key: string]: QueryType | string }, - updLabelFilters?: QueryBuilderLabelFilter[] - ) => { - const queryVar = { - qryType, - label, - metric, - match: labelNamesMatch, - varQuery, - seriesQuery, - classicQuery, - refId: 'PrometheusVariableQueryEditor-VariableQuery', - }; - - let updateLabelFilters = updLabelFilters ? { labelFilters: updLabelFilters } : { labelFilters: labelFilters }; - - const updatedVar = { ...queryVar, ...updateVar, ...updateLabelFilters }; - - const queryString = migrateVariableEditorBackToVariableSupport(updatedVar); - - // setting query.query property allows for update of variable definition - onChange({ - query: queryString, - qryType: updatedVar.qryType, - refId, - }); - }; - - /** Call onchange for label names query type change */ - const onQueryTypeChange = (newType: SelectableValue) => { - setQryType(newType.value); - if (newType.value !== QueryType.SeriesQuery) { - onChangeWithVariableString({ qryType: newType.value ?? 0 }); - } - }; - - /** Call onchange for label select when query type is label values */ - const onLabelChange = (newLabel: SelectableValue) => { - const newLabelvalue = newLabel && newLabel.value ? newLabel.value : ''; - setLabel(newLabelvalue); - if (qryType === QueryType.LabelValues && newLabelvalue) { - onChangeWithVariableString({ label: newLabelvalue }); - } - }; - - /** - * Call onChange for MetricsLabels component change for label values query type - * if there is a label (required) and - * if the labels or metric are updated. - */ - const metricsLabelsChange = (update: PromVisualQuery) => { - setMetric(update.metric); - setLabelFilters(update.labels); - - const updMetric = update.metric; - const updLabelFilters = update.labels ?? []; - - if (qryType === QueryType.LabelValues && label && (updMetric || updLabelFilters)) { - onChangeWithVariableString({ qryType, metric: updMetric }, updLabelFilters); - } - }; - - const onLabelNamesMatchChange = (regex: string) => { - if (qryType === QueryType.LabelNames) { - onChangeWithVariableString({ qryType, match: regex }); - } - }; - - /** - * Call onchange for metric change if metrics names (regex) query type - * Debounce this because to not call the API for every keystroke. - */ - const onMetricChange = (value: string) => { - if (qryType === QueryType.MetricNames && value) { - onChangeWithVariableString({ metric: value }); - } - }; - - /** - * Do not call onchange for variable query result when query type is var query result - * because the query may not be finished typing and an error is returned - * for incorrectly formatted series. Call onchange for blur instead. - */ - const onVarQueryChange = (e: FormEvent) => { - setVarQuery(e.currentTarget.value); - }; - - /** - * Do not call onchange for seriesQuery when query type is series query - * because the series may not be finished typing and an error is returned - * for incorrectly formatted series. Call onchange for blur instead. - */ - const onSeriesQueryChange = (e: FormEvent) => { - setSeriesQuery(e.currentTarget.value); - }; - - const onClassicQueryChange = (e: FormEvent) => { - setClassicQuery(e.currentTarget.value); - }; - - const promVisualQuery = useCallback(() => { - return { metric: metric, labels: labelFilters, operations: [] }; - }, [metric, labelFilters]); - - /** - * Debounce a search through all the labels possible and truncate by . - */ - const labelNamesSearch = debounce((query: string) => { - // we limit the select to show 1000 options, - // but we still search through all the possible options - const results = allLabelOptions.filter((label) => { - return label.value?.includes(query); - }); - return truncateResult(results); - }, 300); - - return ( - <> - - - - The Prometheus data source plugin provides the following query types for template variables. - - - } - > - { - setLabelNamesMatch(event.currentTarget.value); - onLabelNamesMatchChange(event.currentTarget.value); - }} - onChange={(e) => { - setLabelNamesMatch(e.currentTarget.value); - }} - width={25} - data-testid={selectors.components.DataSource.Prometheus.variableQueryEditor.labelnames.metricRegex} - /> - - - )} - - {qryType === QueryType.MetricNames && ( - - - - Returns a list of metrics matching the specified metric regex. - - - } - > - { - setMetric(e.currentTarget.value); - }} - onBlur={(e) => { - setMetric(e.currentTarget.value); - onMetricChange(e.currentTarget.value); - }} - width={25} - data-testid={selectors.components.DataSource.Prometheus.variableQueryEditor.metricNames.metricRegex} - /> - - - )} - - {qryType === QueryType.VarQueryResult && ( - - - - Returns a list of Prometheus query results for the query. This can include Prometheus functions, i.e. - {'{{exampleQuery}}'}. - - - } - > -