diff --git a/.github/dev/docker-compose.ci.yml b/.github/dev/docker-compose.ci.yml index cbf8d4706..1810a882b 100644 --- a/.github/dev/docker-compose.ci.yml +++ b/.github/dev/docker-compose.ci.yml @@ -1,6 +1,6 @@ services: perses: - image: persesdev/perses:main-2026-02-26-739dc289-distroless-debug + image: persesdev/perses:main-2026-11-26-4d10594e-distroless-debug container_name: perses network_mode: host environment: diff --git a/clickhouse/README.md b/clickhouse/README.md index 07c9ba098..336b0cc19 100644 --- a/clickhouse/README.md +++ b/clickhouse/README.md @@ -1,41 +1,44 @@ -# Plugin Module: click-house +# ClickHouse plugin for Perses -### How to install +The ClickHouse plugin runs SQL against [ClickHouse](https://clickhouse.com) through its HTTP interface. It provides time series, log, trace and profile queries, a variable, an annotation and an explorer, and lists the alerts of [ClickStack](https://clickhouse.com/docs/use-cases/observability/clickstack). -This plugin requires react and react-dom 18 or 19. +The queries read any table. They know the tables written by the ClickHouse exporter of the OpenTelemetry Collector and by ClickStack: metrics with their histograms and exemplars, logs, traces and profiles. -Install peer dependencies: +See the [documentation](https://github.com/perses/plugins/blob/main/docs/clickhouse/README.md) of the plugins, and [Writing queries](https://github.com/perses/plugins/blob/main/docs/clickhouse/queries.md) for the macros, the variables and the columns each query expects. -```bash -npm install react@18 react-dom@18 # or react@19 react-dom@19 -``` +## Datasource setup -Install the plugin: +### ClickHouse -```bash -npm install @my-org/click-house -``` +Use a proxied datasource pointing at the HTTP interface of ClickHouse, such as `http://clickhouse.example.com:8123`, and allow `POST ^/$`, for the queries, and `GET ^/ping$`, for the connection test. Store the credentials of the ClickHouse user in a Perses Secret referenced by the proxy. -## Development +The plugin sends every query as read-only (`readonly=2`), with a few settings making the results unambiguous and bounded: ISO date/times, quoted 64-bit integers and a limit of 100 000 rows. This is no protection against a user editing a dashboard: connect with a ClickHouse user that is only granted `SELECT` on the tables to display. When that user is not allowed to change settings (`readonly=1`), the plugin stops sending them and reads the results as they come. -### Setup +Datasources created before queries were sent with `POST` allow `GET` on the root path only. They keep working: their queries are sent in the URL, which limits their size. -Install dependencies: +Set the default database of the datasource to the one holding the tables, for instance the database of the OpenTelemetry tables, to write queries without qualifying them. -```bash -npm install -``` +### ClickStack + +The ClickStack datasource reads the alerts from the API of ClickStack (HyperDX), at `http://:8000`, or at `http://:8080/api` when only the port of the UI is reachable. Use a proxied datasource allowing `GET ^/api/v2/alerts$` and `GET ^/api/v2$`, with a Secret holding an API key of ClickStack as a bearer token. ClickStack does not accept the requests of browsers other than the ones of its own UI. -### Get Started +The ClickHouse server of ClickStack is a ClickHouse datasource like any other. -Start the dev server: +## Development + +Install the dependencies from the root of the repository, then start the dev server of the plugin: ```bash -npm run dev +npm install +npm run dev -w clickhouse ``` -Build the plugin for distribution: +Check the plugin: ```bash -npm run build +npm run lint -w clickhouse +npm run type-check -w clickhouse +npm run test -w clickhouse +percli plugin test-schemas --plugin.path=clickhouse +(cd clickhouse && go test ./...) ``` diff --git a/clickhouse/package.json b/clickhouse/package.json index daad6d458..eb79bdd3e 100644 --- a/clickhouse/package.json +++ b/clickhouse/package.json @@ -84,6 +84,69 @@ }, "name": "ClickHouseLogQuery" } + }, + { + "kind": "TraceQuery", + "spec": { + "display": { + "name": "ClickHouse Trace Query" + }, + "name": "ClickHouseTraceQuery" + } + }, + { + "kind": "ProfileQuery", + "spec": { + "display": { + "name": "ClickHouse Profile Query" + }, + "name": "ClickHouseProfileQuery" + } + }, + { + "kind": "Variable", + "spec": { + "display": { + "name": "ClickHouse SQL Variable" + }, + "name": "ClickHouseSQLVariable" + } + }, + { + "kind": "Annotation", + "spec": { + "display": { + "name": "ClickHouse SQL Annotation" + }, + "name": "ClickHouseSQLAnnotation" + } + }, + { + "kind": "Datasource", + "spec": { + "display": { + "name": "ClickStack Datasource" + }, + "name": "ClickStackDatasource" + } + }, + { + "kind": "AlertsQuery", + "spec": { + "display": { + "name": "ClickStack Alerts Query" + }, + "name": "ClickStackAlertsQuery" + } + }, + { + "kind": "Explore", + "spec": { + "display": { + "name": "ClickHouse Explorer" + }, + "name": "ClickHouseExplorer" + } } ] } diff --git a/clickhouse/rsbuild.config.ts b/clickhouse/rsbuild.config.ts index 560f02616..aca63faa2 100644 --- a/clickhouse/rsbuild.config.ts +++ b/clickhouse/rsbuild.config.ts @@ -20,9 +20,16 @@ export default createConfigForPlugin({ }, moduleFederation: { exposes: { - './ClickHouseDatasource': './src/datasources/click-house-datasource', - './ClickHouseTimeSeriesQuery': './src/queries/click-house-time-series-query', - './ClickHouseLogQuery': './src/queries/click-house-log-query', + './ClickHouseDatasource': './src/datasources/click-house-datasource/ClickHouseDatasource.tsx', + './ClickHouseTimeSeriesQuery': './src/queries/click-house-time-series-query/ClickHouseQuery.tsx', + './ClickHouseLogQuery': './src/queries/click-house-log-query/ClickHouseLogQuery.tsx', + './ClickHouseTraceQuery': './src/queries/click-house-trace-query/ClickHouseTraceQuery.tsx', + './ClickHouseProfileQuery': './src/queries/click-house-profile-query/ClickHouseProfileQuery.tsx', + './ClickHouseSQLVariable': './src/variables/click-house-sql-variable/ClickHouseSQLVariable.tsx', + './ClickHouseSQLAnnotation': './src/annotations/click-house-sql-annotation/ClickHouseSQLAnnotation.tsx', + './ClickStackDatasource': './src/datasources/click-stack-datasource/ClickStackDatasource.tsx', + './ClickStackAlertsQuery': './src/queries/click-stack-alerts-query/ClickStackAlertsQuery.tsx', + './ClickHouseExplorer': './src/explore/ClickHouseExplorer.tsx', }, shared: { react: { requiredVersion: '^18.3.0 || ^19.0.0', singleton: true }, diff --git a/clickhouse/src/components/constants.ts b/clickhouse/schemas/annotations/click-house-sql-annotation/annotation.cue similarity index 55% rename from clickhouse/src/components/constants.ts rename to clickhouse/schemas/annotations/click-house-sql-annotation/annotation.cue index 0046c12a5..5a91df73a 100644 --- a/clickhouse/src/components/constants.ts +++ b/clickhouse/schemas/annotations/click-house-sql-annotation/annotation.cue @@ -11,22 +11,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -export const queryExample = `-- Time Series Query -SELECT - toStartOfMinute(timestamp) as time, - avg(cpu_usage) as avg_cpu, - max(memory_usage) as max_memory -FROM system_metrics -WHERE timestamp BETWEEN '{start}' AND '{end}' -GROUP BY time ORDER BY time --- Logs Query -SELECT - Timestamp as log_time, - Body, - ServiceName, - ResourceAttributes, - SeverityNumber, - SeverityText -FROM application_logs -WHERE timestamp >= '{start}' -ORDER BY time DESC LIMIT 1000`; +package model + +import ( + "strings" + ds "github.com/perses/plugins/clickhouse/schemas/datasources/click-house-datasource:model" +) + +kind: "ClickHouseSQLAnnotation" +spec: close({ + ds.#selector + + // Query returning one row per annotation, with a "time" column, or a "start" and an "end" column. + // Optional columns: "title" and "legend". The other columns are the tags of the annotation. + query: strings.MinRunes(1) +}) diff --git a/clickhouse/schemas/annotations/click-house-sql-annotation/tests/invalid/empty-query.json b/clickhouse/schemas/annotations/click-house-sql-annotation/tests/invalid/empty-query.json new file mode 100644 index 000000000..b9e2efca5 --- /dev/null +++ b/clickhouse/schemas/annotations/click-house-sql-annotation/tests/invalid/empty-query.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseSQLAnnotation", + "spec": { + "query": "" + } +} diff --git a/clickhouse/schemas/annotations/click-house-sql-annotation/tests/invalid/unknown-field.json b/clickhouse/schemas/annotations/click-house-sql-annotation/tests/invalid/unknown-field.json new file mode 100644 index 000000000..2dc54b631 --- /dev/null +++ b/clickhouse/schemas/annotations/click-house-sql-annotation/tests/invalid/unknown-field.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseSQLAnnotation", + "spec": { + "query": "SELECT now() AS time", + "title": "Deployment" + } +} diff --git a/clickhouse/schemas/annotations/click-house-sql-annotation/tests/valid/minimal.json b/clickhouse/schemas/annotations/click-house-sql-annotation/tests/valid/minimal.json new file mode 100644 index 000000000..9ac68583f --- /dev/null +++ b/clickhouse/schemas/annotations/click-house-sql-annotation/tests/valid/minimal.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseSQLAnnotation", + "spec": { + "query": "SELECT Timestamp AS time, Body AS title, ServiceName FROM otel_logs WHERE $__timeFilter(Timestamp) AND SeverityNumber >= 17" + } +} diff --git a/clickhouse/schemas/annotations/click-house-sql-annotation/tests/valid/with-datasource.json b/clickhouse/schemas/annotations/click-house-sql-annotation/tests/valid/with-datasource.json new file mode 100644 index 000000000..bf55722f1 --- /dev/null +++ b/clickhouse/schemas/annotations/click-house-sql-annotation/tests/valid/with-datasource.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseSQLAnnotation", + "spec": { + "datasource": "$clickhouse", + "query": "SELECT started AS start, finished AS end, name AS title FROM deployments WHERE $__timeFilter(started)" + } +} diff --git a/clickhouse/schemas/datasources/click-house-datasource/click-house-datasource.cue b/clickhouse/schemas/datasources/click-house-datasource/click-house-datasource.cue index 709efd5d7..3d0914dcf 100644 --- a/clickhouse/schemas/datasources/click-house-datasource/click-house-datasource.cue +++ b/clickhouse/schemas/datasources/click-house-datasource/click-house-datasource.cue @@ -1,12 +1,12 @@ // Copyright The Perses Authors -// Licensed under the Apache License, Version 2.0 (the \"License\"); +// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an \"AS IS\" BASIS, +// distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. @@ -23,6 +23,10 @@ import ( kind: #kind spec: { datasource.#HTTPDatasourceSpec + + // Database the unqualified table names of the queries are read from. + // Defaults to "default". + database?: string } #selector: common.#datasourceSelector & {_kind: #kind} diff --git a/clickhouse/schemas/datasources/click-house-datasource/tests/invalid/both-modes.json b/clickhouse/schemas/datasources/click-house-datasource/tests/invalid/both-modes.json new file mode 100644 index 000000000..cc3c29a21 --- /dev/null +++ b/clickhouse/schemas/datasources/click-house-datasource/tests/invalid/both-modes.json @@ -0,0 +1,12 @@ +{ + "kind": "ClickHouseDatasource", + "spec": { + "directUrl": "http://localhost:8123", + "proxy": { + "kind": "HTTPProxy", + "spec": { + "url": "http://clickhouse:8123" + } + } + } +} diff --git a/clickhouse/schemas/datasources/click-house-datasource/tests/invalid/database-not-string.json b/clickhouse/schemas/datasources/click-house-datasource/tests/invalid/database-not-string.json new file mode 100644 index 000000000..14221f789 --- /dev/null +++ b/clickhouse/schemas/datasources/click-house-datasource/tests/invalid/database-not-string.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseDatasource", + "spec": { + "directUrl": "http://localhost:8123", + "database": 1 + } +} diff --git a/clickhouse/schemas/datasources/click-house-datasource/tests/valid/direct-url.json b/clickhouse/schemas/datasources/click-house-datasource/tests/valid/direct-url.json new file mode 100644 index 000000000..b9e5916b0 --- /dev/null +++ b/clickhouse/schemas/datasources/click-house-datasource/tests/valid/direct-url.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseDatasource", + "spec": { + "directUrl": "http://localhost:8123" + } +} diff --git a/clickhouse/schemas/datasources/click-house-datasource/tests/valid/proxy-with-database.json b/clickhouse/schemas/datasources/click-house-datasource/tests/valid/proxy-with-database.json new file mode 100644 index 000000000..104cff8a7 --- /dev/null +++ b/clickhouse/schemas/datasources/click-house-datasource/tests/valid/proxy-with-database.json @@ -0,0 +1,23 @@ +{ + "kind": "ClickHouseDatasource", + "spec": { + "database": "otel", + "proxy": { + "kind": "HTTPProxy", + "spec": { + "url": "http://clickhouse:8123", + "allowedEndpoints": [ + { + "endpointPattern": "^/$", + "method": "POST" + }, + { + "endpointPattern": "^/ping$", + "method": "GET" + } + ], + "secret": "clickhouse" + } + } + } +} diff --git a/clickhouse/schemas/datasources/click-stack-datasource/click-stack-datasource.cue b/clickhouse/schemas/datasources/click-stack-datasource/click-stack-datasource.cue new file mode 100644 index 000000000..ac9cb8eaa --- /dev/null +++ b/clickhouse/schemas/datasources/click-stack-datasource/click-stack-datasource.cue @@ -0,0 +1,31 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package model + +import ( + "github.com/perses/shared/cue/common" + "github.com/perses/spec/cue/datasource" +) + +#kind: "ClickStackDatasource" + +kind: #kind +spec: { + datasource.#HTTPDatasourceSpec + + // URL of the ClickStack UI, as users open it in their browser. The alerts link to it. + uiUrl?: string +} + +#selector: common.#datasourceSelector & {_kind: #kind} diff --git a/clickhouse/schemas/datasources/click-stack-datasource/tests/invalid/no-url.json b/clickhouse/schemas/datasources/click-stack-datasource/tests/invalid/no-url.json new file mode 100644 index 000000000..56eb3a64a --- /dev/null +++ b/clickhouse/schemas/datasources/click-stack-datasource/tests/invalid/no-url.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickStackDatasource", + "spec": { + "uiUrl": "https://clickstack.example.com" + } +} diff --git a/clickhouse/schemas/datasources/click-stack-datasource/tests/invalid/ui-url-not-string.json b/clickhouse/schemas/datasources/click-stack-datasource/tests/invalid/ui-url-not-string.json new file mode 100644 index 000000000..076a94415 --- /dev/null +++ b/clickhouse/schemas/datasources/click-stack-datasource/tests/invalid/ui-url-not-string.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickStackDatasource", + "spec": { + "directUrl": "http://localhost:8000", + "uiUrl": true + } +} diff --git a/clickhouse/schemas/datasources/click-stack-datasource/tests/valid/direct-url.json b/clickhouse/schemas/datasources/click-stack-datasource/tests/valid/direct-url.json new file mode 100644 index 000000000..eca3e9d5a --- /dev/null +++ b/clickhouse/schemas/datasources/click-stack-datasource/tests/valid/direct-url.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickStackDatasource", + "spec": { + "directUrl": "http://localhost:8000" + } +} diff --git a/clickhouse/schemas/datasources/click-stack-datasource/tests/valid/proxy.json b/clickhouse/schemas/datasources/click-stack-datasource/tests/valid/proxy.json new file mode 100644 index 000000000..d322f27ea --- /dev/null +++ b/clickhouse/schemas/datasources/click-stack-datasource/tests/valid/proxy.json @@ -0,0 +1,23 @@ +{ + "kind": "ClickStackDatasource", + "spec": { + "uiUrl": "https://clickstack.example.com", + "proxy": { + "kind": "HTTPProxy", + "spec": { + "url": "http://clickstack:8000", + "allowedEndpoints": [ + { + "endpointPattern": "^/api/v2/alerts$", + "method": "GET" + }, + { + "endpointPattern": "^/api/v2$", + "method": "GET" + } + ], + "secret": "clickstack-api-key" + } + } + } +} diff --git a/clickhouse/schemas/queries/click-house-log-query/query.cue b/clickhouse/schemas/queries/click-house-log-query/query.cue index 23bb8dec3..62b8b15a3 100644 --- a/clickhouse/schemas/queries/click-house-log-query/query.cue +++ b/clickhouse/schemas/queries/click-house-log-query/query.cue @@ -1,12 +1,12 @@ // Copyright The Perses Authors -// Licensed under the Apache License, Version 2.0 (the \"License\"); +// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an \"AS IS\" BASIS, +// distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. diff --git a/clickhouse/schemas/queries/click-house-log-query/tests/invalid/empty-query.json b/clickhouse/schemas/queries/click-house-log-query/tests/invalid/empty-query.json new file mode 100644 index 000000000..72865ecf5 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-log-query/tests/invalid/empty-query.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseLogQuery", + "spec": { + "query": "" + } +} diff --git a/clickhouse/schemas/queries/click-house-log-query/tests/invalid/unknown-field.json b/clickhouse/schemas/queries/click-house-log-query/tests/invalid/unknown-field.json new file mode 100644 index 000000000..db9a47c0a --- /dev/null +++ b/clickhouse/schemas/queries/click-house-log-query/tests/invalid/unknown-field.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseLogQuery", + "spec": { + "query": "SELECT * FROM otel_logs", + "limit": 100 + } +} diff --git a/clickhouse/schemas/queries/click-house-log-query/tests/valid/minimal.json b/clickhouse/schemas/queries/click-house-log-query/tests/valid/minimal.json new file mode 100644 index 000000000..70ee12baa --- /dev/null +++ b/clickhouse/schemas/queries/click-house-log-query/tests/valid/minimal.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseLogQuery", + "spec": { + "query": "SELECT Timestamp, Body, SeverityText, ServiceName FROM otel_logs WHERE $__timeFilter(Timestamp) ORDER BY Timestamp DESC LIMIT 1000" + } +} diff --git a/clickhouse/schemas/queries/click-house-log-query/tests/valid/with-datasource.json b/clickhouse/schemas/queries/click-house-log-query/tests/valid/with-datasource.json new file mode 100644 index 000000000..5d2b0bf2a --- /dev/null +++ b/clickhouse/schemas/queries/click-house-log-query/tests/valid/with-datasource.json @@ -0,0 +1,10 @@ +{ + "kind": "ClickHouseLogQuery", + "spec": { + "datasource": { + "kind": "ClickHouseDatasource", + "name": "clickhouse" + }, + "query": "SELECT * FROM otel_logs WHERE $__timeFilter(Timestamp) ORDER BY Timestamp DESC LIMIT 100" + } +} diff --git a/clickhouse/schemas/queries/click-house-profile-query/query.cue b/clickhouse/schemas/queries/click-house-profile-query/query.cue new file mode 100644 index 000000000..989241d29 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-profile-query/query.cue @@ -0,0 +1,28 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package model + +import ( + "strings" + ds "github.com/perses/plugins/clickhouse/schemas/datasources/click-house-datasource:model" +) + +kind: "ClickHouseProfileQuery" +spec: close({ + ds.#selector + + // Query returning one row per sample, with a "stack" column: the frames of the sample, from the leaf to the + // root. Optional columns: "value", "time", "name" and "unit". + query: strings.MinRunes(1) +}) diff --git a/clickhouse/schemas/queries/click-house-profile-query/tests/invalid/empty-query.json b/clickhouse/schemas/queries/click-house-profile-query/tests/invalid/empty-query.json new file mode 100644 index 000000000..9c7d57ffb --- /dev/null +++ b/clickhouse/schemas/queries/click-house-profile-query/tests/invalid/empty-query.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseProfileQuery", + "spec": { + "query": "" + } +} diff --git a/clickhouse/schemas/queries/click-house-profile-query/tests/invalid/unknown-field.json b/clickhouse/schemas/queries/click-house-profile-query/tests/invalid/unknown-field.json new file mode 100644 index 000000000..5ed55d42c --- /dev/null +++ b/clickhouse/schemas/queries/click-house-profile-query/tests/invalid/unknown-field.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseProfileQuery", + "spec": { + "query": "SELECT FunctionNames AS stack FROM otel_profiles", + "profileType": "cpu" + } +} diff --git a/clickhouse/schemas/queries/click-house-profile-query/tests/valid/profile.json b/clickhouse/schemas/queries/click-house-profile-query/tests/valid/profile.json new file mode 100644 index 000000000..e4a79a941 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-profile-query/tests/valid/profile.json @@ -0,0 +1,10 @@ +{ + "kind": "ClickHouseProfileQuery", + "spec": { + "datasource": { + "kind": "ClickHouseDatasource", + "name": "clickhouse" + }, + "query": "SELECT Timestamp AS time, FunctionNames AS stack, length(TimestampsUnixNano) AS value FROM otel_profiles WHERE $__timeFilter(Timestamp)" + } +} diff --git a/clickhouse/schemas/queries/click-house-time-series-query/query.cue b/clickhouse/schemas/queries/click-house-time-series-query/query.cue index 51c4464ed..0a019be8e 100644 --- a/clickhouse/schemas/queries/click-house-time-series-query/query.cue +++ b/clickhouse/schemas/queries/click-house-time-series-query/query.cue @@ -1,12 +1,12 @@ // Copyright The Perses Authors -// Licensed under the Apache License, Version 2.0 (the \"License\"); +// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an \"AS IS\" BASIS, +// distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. @@ -15,6 +15,7 @@ package model import ( "strings" + "github.com/perses/shared/cue/common" ds "github.com/perses/plugins/clickhouse/schemas/datasources/click-house-datasource:model" ) @@ -22,4 +23,14 @@ kind: "ClickHouseTimeSeriesQuery" spec: close({ ds.#selector query: strings.MinRunes(1) + // Name of the series, with the labels of the series between double braces, e.g. "{{ServiceName}}". + seriesNameFormat?: string + // Query returning the exemplars of the series: a time column, a "value" column, the label columns of the + // series and the labels of the exemplars, e.g. "trace_id". + exemplarQuery?: string + // Lower bound of the interval of the query, which is the value of the "$__interval_s" family of macros: + // a duration, e.g. "1m", or a variable holding one. + minStep?: (=~#durationRegex & !="") | =~common.#variableSyntaxRegex }) + +#durationRegex: "^(\\d+y)?(\\d+w)?(\\d+d)?(\\d+h)?(\\d+m)?(\\d+s)?(\\d+ms)?$" diff --git a/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/empty-min-step.json b/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/empty-min-step.json new file mode 100644 index 000000000..5e6a24fe3 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/empty-min-step.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseTimeSeriesQuery", + "spec": { + "query": "SELECT 1 AS value", + "minStep": "" + } +} diff --git a/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/empty-query.json b/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/empty-query.json new file mode 100644 index 000000000..b08c160c4 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/empty-query.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseTimeSeriesQuery", + "spec": { + "query": "" + } +} diff --git a/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/invalid-min-step.json b/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/invalid-min-step.json new file mode 100644 index 000000000..347b63010 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/invalid-min-step.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseTimeSeriesQuery", + "spec": { + "query": "SELECT 1 AS value", + "minStep": "one minute" + } +} diff --git a/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/unknown-field.json b/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/unknown-field.json new file mode 100644 index 000000000..e1d96bb17 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-time-series-query/tests/invalid/unknown-field.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseTimeSeriesQuery", + "spec": { + "query": "SELECT 1 AS value", + "format": "JSON" + } +} diff --git a/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/full.json b/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/full.json new file mode 100644 index 000000000..d45881c26 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/full.json @@ -0,0 +1,13 @@ +{ + "kind": "ClickHouseTimeSeriesQuery", + "spec": { + "datasource": { + "kind": "ClickHouseDatasource", + "name": "clickhouse" + }, + "query": "SELECT $__timeInterval(Timestamp) AS time, ServiceName, count() / $__interval_s AS rps FROM otel_traces WHERE $__timeFilter(Timestamp) AND ServiceName IN (${service:sqlstring}) GROUP BY time, ServiceName ORDER BY time", + "seriesNameFormat": "{{ServiceName}}", + "exemplarQuery": "SELECT Timestamp AS time, Duration / 1e6 AS value, ServiceName, TraceId AS trace_id FROM otel_traces WHERE $__timeFilter(Timestamp) ORDER BY Duration DESC LIMIT 100", + "minStep": "1m" + } +} diff --git a/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/minimal.json b/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/minimal.json new file mode 100644 index 000000000..13cda0d11 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/minimal.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseTimeSeriesQuery", + "spec": { + "query": "SELECT $__timeInterval(Timestamp) AS time, count() AS spans FROM otel_traces WHERE $__timeFilter(Timestamp) GROUP BY time ORDER BY time" + } +} diff --git a/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/variable-datasource.json b/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/variable-datasource.json new file mode 100644 index 000000000..c5a0fece4 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/variable-datasource.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseTimeSeriesQuery", + "spec": { + "datasource": "$clickhouse", + "query": "SELECT 1 AS value" + } +} diff --git a/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/variable-min-step.json b/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/variable-min-step.json new file mode 100644 index 000000000..4ec223e85 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-time-series-query/tests/valid/variable-min-step.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseTimeSeriesQuery", + "spec": { + "query": "SELECT $__timeInterval(TimeUnix) AS time, avg(Value) AS value FROM otel_metrics_gauge WHERE $__timeFilter(TimeUnix) GROUP BY time ORDER BY time", + "minStep": "${resolution}" + } +} diff --git a/clickhouse/schemas/queries/click-house-trace-query/query.cue b/clickhouse/schemas/queries/click-house-trace-query/query.cue new file mode 100644 index 000000000..32440e31f --- /dev/null +++ b/clickhouse/schemas/queries/click-house-trace-query/query.cue @@ -0,0 +1,33 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package model + +import ( + "strings" + ds "github.com/perses/plugins/clickhouse/schemas/datasources/click-house-datasource:model" +) + +kind: "ClickHouseTraceQuery" +spec: close({ + ds.#selector + + // A trace ID, to read a trace, or a query returning the "TraceId" and "Timestamp" columns of the spans to + // search for. Both can come from variables. + query: strings.MinRunes(1) + // Table of the spans, in the schema of the OpenTelemetry Collector: "table" or "database.table". + // Defaults to "otel_traces". + table?: =~"^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)?$" + // Maximum number of traces returned by a search. Defaults to 20. + limit?: int & >=1 +}) diff --git a/clickhouse/schemas/queries/click-house-trace-query/tests/invalid/empty-query.json b/clickhouse/schemas/queries/click-house-trace-query/tests/invalid/empty-query.json new file mode 100644 index 000000000..b0bd49b32 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-trace-query/tests/invalid/empty-query.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseTraceQuery", + "spec": { + "query": "" + } +} diff --git a/clickhouse/schemas/queries/click-house-trace-query/tests/invalid/limit-not-positive.json b/clickhouse/schemas/queries/click-house-trace-query/tests/invalid/limit-not-positive.json new file mode 100644 index 000000000..04b60e4bf --- /dev/null +++ b/clickhouse/schemas/queries/click-house-trace-query/tests/invalid/limit-not-positive.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseTraceQuery", + "spec": { + "query": "SELECT TraceId, Timestamp FROM otel_traces", + "limit": 0 + } +} diff --git a/clickhouse/schemas/queries/click-house-trace-query/tests/invalid/table-not-a-name.json b/clickhouse/schemas/queries/click-house-trace-query/tests/invalid/table-not-a-name.json new file mode 100644 index 000000000..14c456bc6 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-trace-query/tests/invalid/table-not-a-name.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseTraceQuery", + "spec": { + "query": "$traceId", + "table": "otel_traces WHERE 1 = 1" + } +} diff --git a/clickhouse/schemas/queries/click-house-trace-query/tests/valid/search.json b/clickhouse/schemas/queries/click-house-trace-query/tests/valid/search.json new file mode 100644 index 000000000..1b367ae66 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-trace-query/tests/valid/search.json @@ -0,0 +1,12 @@ +{ + "kind": "ClickHouseTraceQuery", + "spec": { + "datasource": { + "kind": "ClickHouseDatasource", + "name": "clickhouse" + }, + "query": "SELECT TraceId, Timestamp FROM otel_traces WHERE $__timeFilter(Timestamp) AND StatusCode = 'Error'", + "table": "otel.otel_traces", + "limit": 50 + } +} diff --git a/clickhouse/schemas/queries/click-house-trace-query/tests/valid/trace-id-variable.json b/clickhouse/schemas/queries/click-house-trace-query/tests/valid/trace-id-variable.json new file mode 100644 index 000000000..110167b13 --- /dev/null +++ b/clickhouse/schemas/queries/click-house-trace-query/tests/valid/trace-id-variable.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseTraceQuery", + "spec": { + "query": "$traceId" + } +} diff --git a/clickhouse/schemas/queries/click-house-trace-query/tests/valid/trace-id.json b/clickhouse/schemas/queries/click-house-trace-query/tests/valid/trace-id.json new file mode 100644 index 000000000..d7e7cbc5b --- /dev/null +++ b/clickhouse/schemas/queries/click-house-trace-query/tests/valid/trace-id.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseTraceQuery", + "spec": { + "query": "5b8efff798038103d269b633813fc60c" + } +} diff --git a/clickhouse/schemas/queries/click-stack-alerts-query/query.cue b/clickhouse/schemas/queries/click-stack-alerts-query/query.cue new file mode 100644 index 000000000..76d4bf1ea --- /dev/null +++ b/clickhouse/schemas/queries/click-stack-alerts-query/query.cue @@ -0,0 +1,32 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package model + +import ( + ds "github.com/perses/plugins/clickhouse/schemas/datasources/click-stack-datasource:model" +) + +kind: "ClickStackAlertsQuery" +spec: close({ + ds.#selector + + // Only the alerts in one of these states. Defaults to the firing ("ALERT") and pending ones. + states?: [...("ALERT" | "PENDING" | "OK" | "INSUFFICIENT_DATA" | "DISABLED")] + // Only the alerts watching one of these kinds of sources. Defaults to all of them. + sources?: [...("saved_search" | "tile" | "inline")] + // Only the alerts with one of these tags. + tags?: [...string] + // Only the alerts whose name contains this text. + search?: string +}) diff --git a/clickhouse/schemas/queries/click-stack-alerts-query/tests/invalid/unknown-field.json b/clickhouse/schemas/queries/click-stack-alerts-query/tests/invalid/unknown-field.json new file mode 100644 index 000000000..9409fddf4 --- /dev/null +++ b/clickhouse/schemas/queries/click-stack-alerts-query/tests/invalid/unknown-field.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickStackAlertsQuery", + "spec": { + "active": true + } +} diff --git a/clickhouse/schemas/queries/click-stack-alerts-query/tests/invalid/unknown-state.json b/clickhouse/schemas/queries/click-stack-alerts-query/tests/invalid/unknown-state.json new file mode 100644 index 000000000..19eb5c9cf --- /dev/null +++ b/clickhouse/schemas/queries/click-stack-alerts-query/tests/invalid/unknown-state.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickStackAlertsQuery", + "spec": { + "states": ["firing"] + } +} diff --git a/clickhouse/schemas/queries/click-stack-alerts-query/tests/valid/full.json b/clickhouse/schemas/queries/click-stack-alerts-query/tests/valid/full.json new file mode 100644 index 000000000..4d4a8d924 --- /dev/null +++ b/clickhouse/schemas/queries/click-stack-alerts-query/tests/valid/full.json @@ -0,0 +1,13 @@ +{ + "kind": "ClickStackAlertsQuery", + "spec": { + "datasource": { + "kind": "ClickStackDatasource", + "name": "clickstack" + }, + "states": ["ALERT", "PENDING", "OK"], + "sources": ["saved_search", "tile"], + "tags": ["team:$team", "production"], + "search": "checkout" + } +} diff --git a/clickhouse/schemas/queries/click-stack-alerts-query/tests/valid/minimal.json b/clickhouse/schemas/queries/click-stack-alerts-query/tests/valid/minimal.json new file mode 100644 index 000000000..513e55625 --- /dev/null +++ b/clickhouse/schemas/queries/click-stack-alerts-query/tests/valid/minimal.json @@ -0,0 +1,4 @@ +{ + "kind": "ClickStackAlertsQuery", + "spec": {} +} diff --git a/clickhouse/schemas/queries/click-stack-alerts-query/tests/valid/variable-datasource.json b/clickhouse/schemas/queries/click-stack-alerts-query/tests/valid/variable-datasource.json new file mode 100644 index 000000000..11704e42e --- /dev/null +++ b/clickhouse/schemas/queries/click-stack-alerts-query/tests/valid/variable-datasource.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickStackAlertsQuery", + "spec": { + "datasource": "$clickstack" + } +} diff --git a/clickhouse/schemas/variables/click-house-sql-variable/tests/invalid/empty-query.json b/clickhouse/schemas/variables/click-house-sql-variable/tests/invalid/empty-query.json new file mode 100644 index 000000000..882caeb9f --- /dev/null +++ b/clickhouse/schemas/variables/click-house-sql-variable/tests/invalid/empty-query.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseSQLVariable", + "spec": { + "query": "" + } +} diff --git a/clickhouse/schemas/variables/click-house-sql-variable/tests/invalid/unknown-field.json b/clickhouse/schemas/variables/click-house-sql-variable/tests/invalid/unknown-field.json new file mode 100644 index 000000000..a337f407e --- /dev/null +++ b/clickhouse/schemas/variables/click-house-sql-variable/tests/invalid/unknown-field.json @@ -0,0 +1,7 @@ +{ + "kind": "ClickHouseSQLVariable", + "spec": { + "query": "SELECT 1", + "labelName": "service" + } +} diff --git a/clickhouse/schemas/variables/click-house-sql-variable/tests/valid/minimal.json b/clickhouse/schemas/variables/click-house-sql-variable/tests/valid/minimal.json new file mode 100644 index 000000000..c1f8b8497 --- /dev/null +++ b/clickhouse/schemas/variables/click-house-sql-variable/tests/valid/minimal.json @@ -0,0 +1,6 @@ +{ + "kind": "ClickHouseSQLVariable", + "spec": { + "query": "SELECT DISTINCT ServiceName FROM otel_traces WHERE $__timeFilter(Timestamp) ORDER BY ServiceName" + } +} diff --git a/clickhouse/schemas/variables/click-house-sql-variable/tests/valid/with-datasource.json b/clickhouse/schemas/variables/click-house-sql-variable/tests/valid/with-datasource.json new file mode 100644 index 000000000..31943a67f --- /dev/null +++ b/clickhouse/schemas/variables/click-house-sql-variable/tests/valid/with-datasource.json @@ -0,0 +1,10 @@ +{ + "kind": "ClickHouseSQLVariable", + "spec": { + "datasource": { + "kind": "ClickHouseDatasource", + "name": "clickhouse" + }, + "query": "SELECT DISTINCT SpanName AS value FROM otel_traces WHERE ServiceName IN (${service:sqlstring})" + } +} diff --git a/clickhouse/schemas/variables/click-house-sql-variable/variable.cue b/clickhouse/schemas/variables/click-house-sql-variable/variable.cue new file mode 100644 index 000000000..707c9de65 --- /dev/null +++ b/clickhouse/schemas/variables/click-house-sql-variable/variable.cue @@ -0,0 +1,28 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package model + +import ( + "strings" + ds "github.com/perses/plugins/clickhouse/schemas/datasources/click-house-datasource:model" +) + +kind: "ClickHouseSQLVariable" +spec: close({ + ds.#selector + + // Query returning the values of the variable: its "value" column, or else its first column. An optional + // "label" column holds the text displayed for each value. + query: strings.MinRunes(1) +}) diff --git a/clickhouse/sdk/go/annotation/sql/options.go b/clickhouse/sdk/go/annotation/sql/options.go new file mode 100644 index 000000000..f75608ffc --- /dev/null +++ b/clickhouse/sdk/go/annotation/sql/options.go @@ -0,0 +1,36 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package sql + +import ( + clickhouseDatasource "github.com/perses/plugins/clickhouse/sdk/go/datasource" +) + +func Query(expr string) Option { + return func(builder *Builder) error { + builder.Query = expr + return nil + } +} + +func Datasource(datasourceName string) Option { + return func(builder *Builder) error { + sel, err := clickhouseDatasource.Selector(datasourceName) + if err != nil { + return err + } + builder.Datasource = sel + return nil + } +} diff --git a/clickhouse/sdk/go/annotation/sql/sql.go b/clickhouse/sdk/go/annotation/sql/sql.go new file mode 100644 index 000000000..492455ee8 --- /dev/null +++ b/clickhouse/sdk/go/annotation/sql/sql.go @@ -0,0 +1,67 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package sql + +import ( + "github.com/perses/perses/go-sdk/annotation" + "github.com/perses/perses/go-sdk/datasource" + "github.com/perses/spec/go/plugin" +) + +const PluginKind = "ClickHouseSQLAnnotation" + +type PluginSpec struct { + Datasource *datasource.Selector `json:"datasource,omitempty" yaml:"datasource,omitempty"` + Query string `json:"query" yaml:"query"` +} + +type Option func(plugin *Builder) error + +func create(query string, options ...Option) (Builder, error) { + builder := &Builder{ + PluginSpec: PluginSpec{}, + } + + defaults := []Option{ + Query(query), + } + + for _, opt := range append(defaults, options...) { + if err := opt(builder); err != nil { + return *builder, err + } + } + + return *builder, nil +} + +type Builder struct { + PluginSpec `json:",inline" yaml:",inline"` +} + +// ClickHouseSQL reads annotations with a query returning one row per annotation: a "time" column, or a "start" and +// an "end" column, the optional "title" and "legend" columns, and any other column as a tag. +func ClickHouseSQL(expr string, options ...Option) annotation.Option { + return func(builder *annotation.Builder) error { + plg, err := create(expr, options...) + if err != nil { + return err + } + builder.Annotation.Plugin = plugin.Plugin{ + Kind: PluginKind, + Spec: plg, + } + return nil + } +} diff --git a/clickhouse/sdk/go/annotation/sql/sql_test.go b/clickhouse/sdk/go/annotation/sql/sql_test.go new file mode 100644 index 000000000..87503dc2c --- /dev/null +++ b/clickhouse/sdk/go/annotation/sql/sql_test.go @@ -0,0 +1,39 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package sql + +import ( + "encoding/json" + "testing" + + "github.com/perses/perses/go-sdk/annotation" +) + +func TestClickHouseSQLConfiguresAnAnnotation(t *testing.T) { + builder, err := annotation.New("Deployments", ClickHouseSQL( + "SELECT deployed_at AS time, version AS title FROM deployments WHERE $__timeFilter(deployed_at)", + Datasource("clickhouse"), + )) + if err != nil { + t.Fatal(err) + } + got, err := json.Marshal(builder.Annotation.Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickHouseSQLAnnotation","spec":{"datasource":{"kind":"ClickHouseDatasource","name":"clickhouse"},"query":"SELECT deployed_at AS time, version AS title FROM deployments WHERE $__timeFilter(deployed_at)"}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} diff --git a/clickhouse/sdk/go/clickstack/datasource/datasource.go b/clickhouse/sdk/go/clickstack/datasource/datasource.go new file mode 100644 index 000000000..3ded3ffe8 --- /dev/null +++ b/clickhouse/sdk/go/clickstack/datasource/datasource.go @@ -0,0 +1,63 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datasource + +import ( + "github.com/perses/perses/go-sdk/datasource" + datasourceSpec "github.com/perses/spec/go/datasource" +) + +const ( + PluginKind = "ClickStackDatasource" +) + +type Option func(plugin *Builder) error + +func create(options ...Option) (Builder, error) { + builder := &Builder{ + HTTPDatasourceSpec: datasourceSpec.HTTPDatasourceSpec{}, + } + + for _, opt := range options { + if err := opt(builder); err != nil { + return *builder, err + } + } + + return *builder, nil +} + +type Builder struct { + datasourceSpec.HTTPDatasourceSpec `json:",inline" yaml:",inline"` + // UIURL is the URL of the ClickStack UI, as users open it in their browser. The alerts link to it. + UIURL string `json:"uiUrl,omitempty" yaml:"uiUrl,omitempty"` +} + +// ClickStack configures a datasource of the API of ClickStack (HyperDX). +func ClickStack(options ...Option) datasource.Option { + return func(builder *datasource.Builder) error { + plugin, err := create(options...) + if err != nil { + return err + } + + builder.Spec.Plugin.Kind = PluginKind + builder.Spec.Plugin.Spec = plugin + return nil + } +} + +func Selector(name string) (*datasource.Selector, error) { + return datasource.NewSelector(PluginKind, name) +} diff --git a/clickhouse/sdk/go/clickstack/datasource/datasource_test.go b/clickhouse/sdk/go/clickstack/datasource/datasource_test.go new file mode 100644 index 000000000..cb3e3c2f3 --- /dev/null +++ b/clickhouse/sdk/go/clickstack/datasource/datasource_test.go @@ -0,0 +1,40 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datasource + +import ( + "encoding/json" + "testing" + + "github.com/perses/perses/go-sdk/datasource" + "github.com/perses/perses/go-sdk/http" +) + +func TestClickStackSpecMarshalsProxyAndUIURL(t *testing.T) { + builder, err := datasource.New("clickstack", ClickStack( + HTTPProxy("http://clickstack:8000", http.Secret("clickstack-api-key")), + UIURL("https://clickstack.example.com"), + )) + if err != nil { + t.Fatal(err) + } + got, err := json.Marshal(builder.Spec.Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickStackDatasource","spec":{"proxy":{"kind":"httpproxy","spec":{"url":"http://clickstack:8000","secret":"clickstack-api-key"}},"uiUrl":"https://clickstack.example.com"}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} diff --git a/clickhouse/sdk/go/clickstack/datasource/options.go b/clickhouse/sdk/go/clickstack/datasource/options.go new file mode 100644 index 000000000..fe2d6f4af --- /dev/null +++ b/clickhouse/sdk/go/clickstack/datasource/options.go @@ -0,0 +1,47 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datasource + +import ( + "github.com/perses/perses/go-sdk/http" +) + +func DirectURL(url string) Option { + return func(builder *Builder) error { + builder.DirectURL = url + return nil + } +} + +// HTTPProxy reaches the API of ClickStack through the Perses proxy: url is the URL of the API, e.g. +// "http://clickstack:8000". Its secret holds the API key of ClickStack as a bearer token. +func HTTPProxy(url string, options ...http.Option) Option { + return func(builder *Builder) error { + p, err := http.New(url, options...) + if err != nil { + return err + } + builder.Proxy = &p.Proxy + return nil + } +} + +// UIURL sets the URL of the ClickStack UI, as users open it in their browser. The alerts link to the dashboard or +// the saved search they watch. +func UIURL(url string) Option { + return func(builder *Builder) error { + builder.UIURL = url + return nil + } +} diff --git a/clickhouse/sdk/go/clickstack/query/alerts/alerts.go b/clickhouse/sdk/go/clickstack/query/alerts/alerts.go new file mode 100644 index 000000000..a1b56c7d6 --- /dev/null +++ b/clickhouse/sdk/go/clickstack/query/alerts/alerts.go @@ -0,0 +1,88 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package alerts + +import ( + "github.com/perses/perses/go-sdk/datasource" + "github.com/perses/perses/go-sdk/query" + "github.com/perses/spec/go/plugin" +) + +const PluginKind = "ClickStackAlertsQuery" + +// State is the state of a ClickStack alert. +type State string + +const ( + // StateAlert is the state of the firing alerts. + StateAlert State = "ALERT" + // StatePending is the state of the alerts over their threshold, but not for long enough to fire. + StatePending State = "PENDING" + // StateOK is the state of the alerts that are not firing. + StateOK State = "OK" + StateInsufficientData State = "INSUFFICIENT_DATA" + StateDisabled State = "DISABLED" +) + +// Source is what a ClickStack alert watches. +type Source string + +const ( + SourceSavedSearch Source = "saved_search" + // SourceTile is the source of the alerts watching a tile of a dashboard. + SourceTile Source = "tile" + // SourceInline is the source of the alerts watching their own chart. + SourceInline Source = "inline" +) + +type PluginSpec struct { + Datasource *datasource.Selector `json:"datasource,omitempty" yaml:"datasource,omitempty"` + States []State `json:"states,omitempty" yaml:"states,omitempty"` + Sources []Source `json:"sources,omitempty" yaml:"sources,omitempty"` + Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` + Search string `json:"search,omitempty" yaml:"search,omitempty"` +} + +type Option func(plugin *Builder) error + +func create(options ...Option) (Builder, error) { + builder := &Builder{ + PluginSpec: PluginSpec{}, + } + + for _, opt := range options { + if err := opt(builder); err != nil { + return *builder, err + } + } + + return *builder, nil +} + +type Builder struct { + PluginSpec `json:",inline" yaml:",inline"` +} + +// AlertsQuery lists the alerts of ClickStack. Without options, it lists the firing and pending ones. +func AlertsQuery(options ...Option) query.Option { + plg, err := create(options...) + return query.Option{ + Kind: plugin.KindAlertsQuery, + Plugin: plugin.Plugin{ + Kind: PluginKind, + Spec: plg, + }, + Error: err, + } +} diff --git a/clickhouse/sdk/go/clickstack/query/alerts/alerts_test.go b/clickhouse/sdk/go/clickstack/query/alerts/alerts_test.go new file mode 100644 index 000000000..018b2e5a7 --- /dev/null +++ b/clickhouse/sdk/go/clickstack/query/alerts/alerts_test.go @@ -0,0 +1,65 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package alerts + +import ( + "encoding/json" + "testing" + + "github.com/perses/spec/go/plugin" +) + +func TestAlertsQueryMarshalsItsFilters(t *testing.T) { + option := AlertsQuery( + Datasource("clickstack"), + States(StateAlert, StatePending, StateOK), + Sources(SourceTile), + Tags("team:$team", "production"), + Search("checkout"), + ) + if option.Error != nil { + t.Fatal(option.Error) + } + if option.Kind != plugin.KindAlertsQuery { + t.Fatalf("got kind %s, want %s", option.Kind, plugin.KindAlertsQuery) + } + got, err := json.Marshal(option.Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickStackAlertsQuery","spec":{"datasource":{"kind":"ClickStackDatasource","name":"clickstack"},"states":["ALERT","PENDING","OK"],"sources":["tile"],"tags":["team:$team","production"],"search":"checkout"}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} + +func TestAlertsQueryWithoutOptionsIsEmpty(t *testing.T) { + got, err := json.Marshal(AlertsQuery().Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickStackAlertsQuery","spec":{}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} + +func TestAlertsQueryRejectsUnknownValues(t *testing.T) { + if err := AlertsQuery(States("firing")).Error; err == nil { + t.Fatal("expected an error for an unknown state") + } + if err := AlertsQuery(Sources("dashboard")).Error; err == nil { + t.Fatal("expected an error for an unknown source") + } +} diff --git a/clickhouse/sdk/go/clickstack/query/alerts/options.go b/clickhouse/sdk/go/clickstack/query/alerts/options.go new file mode 100644 index 000000000..e7ad21c87 --- /dev/null +++ b/clickhouse/sdk/go/clickstack/query/alerts/options.go @@ -0,0 +1,77 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package alerts + +import ( + "fmt" + + clickstackDatasource "github.com/perses/plugins/clickhouse/sdk/go/clickstack/datasource" +) + +func Datasource(datasourceName string) Option { + return func(builder *Builder) error { + sel, err := clickstackDatasource.Selector(datasourceName) + if err != nil { + return err + } + builder.Datasource = sel + return nil + } +} + +// States lists the alerts in one of the states. By default, the firing and pending alerts are listed. +func States(states ...State) Option { + return func(builder *Builder) error { + for _, state := range states { + switch state { + case StateAlert, StatePending, StateOK, StateInsufficientData, StateDisabled: + default: + return fmt.Errorf("invalid alert state %q", state) + } + } + builder.States = states + return nil + } +} + +// Sources lists the alerts watching one of the kinds of sources. By default, all the alerts are listed. +func Sources(sources ...Source) Option { + return func(builder *Builder) error { + for _, source := range sources { + switch source { + case SourceSavedSearch, SourceTile, SourceInline: + default: + return fmt.Errorf("invalid alert source %q", source) + } + } + builder.Sources = sources + return nil + } +} + +// Tags lists the alerts with one of the tags. Variables are supported, e.g. "team:$team". +func Tags(tags ...string) Option { + return func(builder *Builder) error { + builder.Tags = tags + return nil + } +} + +// Search lists the alerts whose name contains the text. Variables are supported. +func Search(search string) Option { + return func(builder *Builder) error { + builder.Search = search + return nil + } +} diff --git a/clickhouse/sdk/go/datasource/datasource.go b/clickhouse/sdk/go/datasource/datasource.go index c25184e0c..240a17879 100644 --- a/clickhouse/sdk/go/datasource/datasource.go +++ b/clickhouse/sdk/go/datasource/datasource.go @@ -42,6 +42,8 @@ func create(options ...Option) (Builder, error) { type Builder struct { datasourceSpec.HTTPDatasourceSpec `json:",inline" yaml:",inline"` + // Database the unqualified table names of the queries are read from. + Database string `json:"database,omitempty" yaml:"database,omitempty"` } func ClickHouse(options ...Option) datasource.Option { @@ -52,7 +54,7 @@ func ClickHouse(options ...Option) datasource.Option { } builder.Spec.Plugin.Kind = PluginKind - builder.Spec.Plugin.Spec = plugin.HTTPDatasourceSpec + builder.Spec.Plugin.Spec = plugin return nil } } diff --git a/clickhouse/sdk/go/datasource/datasource_test.go b/clickhouse/sdk/go/datasource/datasource_test.go new file mode 100644 index 000000000..59637c7b3 --- /dev/null +++ b/clickhouse/sdk/go/datasource/datasource_test.go @@ -0,0 +1,55 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datasource + +import ( + "encoding/json" + "testing" + + "github.com/perses/perses/go-sdk/datasource" + "github.com/perses/perses/go-sdk/http" +) + +func TestClickHouseSpecMarshalsDatabaseAndProxy(t *testing.T) { + builder, err := datasource.New("clickhouse", ClickHouse( + Database("otel"), + HTTPProxy("http://clickhouse:8123", http.Secret("clickhouse")), + )) + if err != nil { + t.Fatal(err) + } + got, err := json.Marshal(builder.Spec.Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickHouseDatasource","spec":{"proxy":{"kind":"httpproxy","spec":{"url":"http://clickhouse:8123","secret":"clickhouse"}},"database":"otel"}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} + +func TestClickHouseSpecMarshalsDirectURLOnly(t *testing.T) { + builder, err := datasource.New("clickhouse", ClickHouse(DirectURL("http://localhost:8123"))) + if err != nil { + t.Fatal(err) + } + got, err := json.Marshal(builder.Spec.Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickHouseDatasource","spec":{"directUrl":"http://localhost:8123"}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} diff --git a/clickhouse/sdk/go/datasource/options.go b/clickhouse/sdk/go/datasource/options.go index 07f0d2303..9883adbda 100644 --- a/clickhouse/sdk/go/datasource/options.go +++ b/clickhouse/sdk/go/datasource/options.go @@ -34,3 +34,12 @@ func HTTPProxy(url string, options ...http.Option) Option { return nil } } + +// Database sets the database the unqualified table names of the queries are read from, e.g. the one holding the +// OpenTelemetry tables. It defaults to the database named "default". +func Database(database string) Option { + return func(builder *Builder) error { + builder.Database = database + return nil + } +} diff --git a/clickhouse/sdk/go/query/profile/options.go b/clickhouse/sdk/go/query/profile/options.go new file mode 100644 index 000000000..1494dde5b --- /dev/null +++ b/clickhouse/sdk/go/query/profile/options.go @@ -0,0 +1,36 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package profile + +import ( + clickhouseDatasource "github.com/perses/plugins/clickhouse/sdk/go/datasource" +) + +func Query(expr string) Option { + return func(builder *Builder) error { + builder.Query = expr + return nil + } +} + +func Datasource(datasourceName string) Option { + return func(builder *Builder) error { + sel, err := clickhouseDatasource.Selector(datasourceName) + if err != nil { + return err + } + builder.Datasource = sel + return nil + } +} diff --git a/clickhouse/sdk/go/query/profile/profile.go b/clickhouse/sdk/go/query/profile/profile.go new file mode 100644 index 000000000..92632b7da --- /dev/null +++ b/clickhouse/sdk/go/query/profile/profile.go @@ -0,0 +1,65 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package profile + +import ( + "github.com/perses/perses/go-sdk/datasource" + "github.com/perses/perses/go-sdk/query" + "github.com/perses/spec/go/plugin" +) + +const PluginKind = "ClickHouseProfileQuery" + +type PluginSpec struct { + Datasource *datasource.Selector `json:"datasource,omitempty" yaml:"datasource,omitempty"` + Query string `json:"query" yaml:"query"` +} + +type Option func(plugin *Builder) error + +func create(query string, options ...Option) (Builder, error) { + builder := &Builder{ + PluginSpec: PluginSpec{}, + } + + defaults := []Option{ + Query(query), + } + + for _, opt := range append(defaults, options...) { + if err := opt(builder); err != nil { + return *builder, err + } + } + + return *builder, nil +} + +type Builder struct { + PluginSpec `json:",inline" yaml:",inline"` +} + +// ClickHouseProfileQuery builds a profile from the samples returned by expr: one row per sample, with a "stack" +// column holding the frames of the sample from the leaf to the root. +func ClickHouseProfileQuery(expr string, options ...Option) query.Option { + plg, err := create(expr, options...) + return query.Option{ + Kind: plugin.KindProfileQuery, + Plugin: plugin.Plugin{ + Kind: PluginKind, + Spec: plg, + }, + Error: err, + } +} diff --git a/clickhouse/sdk/go/query/profile/profile_test.go b/clickhouse/sdk/go/query/profile/profile_test.go new file mode 100644 index 000000000..cccdffac6 --- /dev/null +++ b/clickhouse/sdk/go/query/profile/profile_test.go @@ -0,0 +1,39 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package profile + +import ( + "encoding/json" + "testing" + + "github.com/perses/spec/go/plugin" +) + +func TestClickHouseProfileQueryMarshalsItsOptions(t *testing.T) { + option := ClickHouseProfileQuery("SELECT FunctionNames AS stack FROM otel_profiles", Datasource("clickhouse")) + if option.Error != nil { + t.Fatal(option.Error) + } + if option.Kind != plugin.KindProfileQuery { + t.Fatalf("got kind %s, want %s", option.Kind, plugin.KindProfileQuery) + } + got, err := json.Marshal(option.Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickHouseProfileQuery","spec":{"datasource":{"kind":"ClickHouseDatasource","name":"clickhouse"},"query":"SELECT FunctionNames AS stack FROM otel_profiles"}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} diff --git a/clickhouse/sdk/go/query/time-series/options.go b/clickhouse/sdk/go/query/time-series/options.go index 13ea7934f..7f0dc91ca 100644 --- a/clickhouse/sdk/go/query/time-series/options.go +++ b/clickhouse/sdk/go/query/time-series/options.go @@ -14,7 +14,10 @@ package timeseries import ( + "time" + clickhouseDatasource "github.com/perses/plugins/clickhouse/sdk/go/datasource" + "github.com/perses/spec/go/common" ) func Query(expr string) Option { @@ -34,3 +37,30 @@ func Datasource(datasourceName string) Option { return nil } } + +// SeriesNameFormat sets the format of the names of the series, e.g. "{{ServiceName}}": each "{{label}}" is +// replaced by the value of the label of the series. +func SeriesNameFormat(format string) Option { + return func(builder *Builder) error { + builder.SeriesNameFormat = format + return nil + } +} + +// ExemplarQuery sets the query returning the exemplars of the series: a time column, a "value" column, the label +// columns of the series, and the labels of the exemplars, such as "trace_id". +func ExemplarQuery(expr string) Option { + return func(builder *Builder) error { + builder.ExemplarQuery = expr + return nil + } +} + +// MinStep sets the lower bound of the interval of the query, which is the value of the "$__interval_s" family of +// macros: typically the interval the data is written at, when a panel asks for a shorter one. +func MinStep(step time.Duration) Option { + return func(builder *Builder) error { + builder.MinStep = common.Duration(step) + return nil + } +} diff --git a/clickhouse/sdk/go/query/time-series/time-series.go b/clickhouse/sdk/go/query/time-series/time-series.go index f7d44e156..8989e436a 100644 --- a/clickhouse/sdk/go/query/time-series/time-series.go +++ b/clickhouse/sdk/go/query/time-series/time-series.go @@ -16,14 +16,18 @@ package timeseries import ( "github.com/perses/perses/go-sdk/datasource" "github.com/perses/perses/go-sdk/query" + "github.com/perses/spec/go/common" "github.com/perses/spec/go/plugin" ) const PluginKind = "ClickHouseTimeSeriesQuery" type PluginSpec struct { - Datasource *datasource.Selector `json:"datasource,omitempty" yaml:"datasource,omitempty"` - Query string `json:"query" yaml:"query"` + Datasource *datasource.Selector `json:"datasource,omitempty" yaml:"datasource,omitempty"` + Query string `json:"query" yaml:"query"` + SeriesNameFormat string `json:"seriesNameFormat,omitempty" yaml:"seriesNameFormat,omitempty"` + ExemplarQuery string `json:"exemplarQuery,omitempty" yaml:"exemplarQuery,omitempty"` + MinStep common.Duration `json:"minStep,omitempty" yaml:"minStep,omitempty"` } type Option func(plugin *Builder) error diff --git a/clickhouse/sdk/go/query/time-series/time-series_test.go b/clickhouse/sdk/go/query/time-series/time-series_test.go new file mode 100644 index 000000000..85e8444bc --- /dev/null +++ b/clickhouse/sdk/go/query/time-series/time-series_test.go @@ -0,0 +1,52 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package timeseries + +import ( + "encoding/json" + "testing" + "time" +) + +func TestClickHouseTimeSeriesQueryMarshalsItsOptions(t *testing.T) { + option := ClickHouseTimeSeriesQuery( + "SELECT time, ServiceName, value FROM metrics", + Datasource("clickhouse"), + SeriesNameFormat("{{ServiceName}}"), + ExemplarQuery("SELECT time, value, ServiceName, trace_id FROM exemplars"), + MinStep(time.Minute), + ) + if option.Error != nil { + t.Fatal(option.Error) + } + got, err := json.Marshal(option.Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickHouseTimeSeriesQuery","spec":{"datasource":{"kind":"ClickHouseDatasource","name":"clickhouse"},"query":"SELECT time, ServiceName, value FROM metrics","seriesNameFormat":"{{ServiceName}}","exemplarQuery":"SELECT time, value, ServiceName, trace_id FROM exemplars","minStep":"1m"}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} + +func TestClickHouseTimeSeriesQueryOmitsUnsetOptions(t *testing.T) { + got, err := json.Marshal(ClickHouseTimeSeriesQuery("SELECT 1 AS value").Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickHouseTimeSeriesQuery","spec":{"query":"SELECT 1 AS value"}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} diff --git a/clickhouse/sdk/go/query/trace/options.go b/clickhouse/sdk/go/query/trace/options.go new file mode 100644 index 000000000..70dfb444d --- /dev/null +++ b/clickhouse/sdk/go/query/trace/options.go @@ -0,0 +1,64 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "fmt" + "regexp" + + clickhouseDatasource "github.com/perses/plugins/clickhouse/sdk/go/datasource" +) + +var tableName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$`) + +func Query(expr string) Option { + return func(builder *Builder) error { + builder.Query = expr + return nil + } +} + +func Datasource(datasourceName string) Option { + return func(builder *Builder) error { + sel, err := clickhouseDatasource.Selector(datasourceName) + if err != nil { + return err + } + builder.Datasource = sel + return nil + } +} + +// Table sets the table of the spans, in the schema of the OpenTelemetry Collector: "table" or "database.table". +// It defaults to "otel_traces". +func Table(table string) Option { + return func(builder *Builder) error { + if !tableName.MatchString(table) { + return fmt.Errorf("invalid trace table %q: expected \"table\" or \"database.table\"", table) + } + builder.Table = table + return nil + } +} + +// Limit sets the maximum number of traces returned by a search. It defaults to 20. +func Limit(limit int) Option { + return func(builder *Builder) error { + if limit < 1 { + return fmt.Errorf("invalid trace limit %d: expected a positive number", limit) + } + builder.Limit = &limit + return nil + } +} diff --git a/clickhouse/sdk/go/query/trace/trace.go b/clickhouse/sdk/go/query/trace/trace.go new file mode 100644 index 000000000..9273d916d --- /dev/null +++ b/clickhouse/sdk/go/query/trace/trace.go @@ -0,0 +1,67 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "github.com/perses/perses/go-sdk/datasource" + "github.com/perses/perses/go-sdk/query" + "github.com/perses/spec/go/plugin" +) + +const PluginKind = "ClickHouseTraceQuery" + +type PluginSpec struct { + Datasource *datasource.Selector `json:"datasource,omitempty" yaml:"datasource,omitempty"` + Query string `json:"query" yaml:"query"` + Table string `json:"table,omitempty" yaml:"table,omitempty"` + Limit *int `json:"limit,omitempty" yaml:"limit,omitempty"` +} + +type Option func(plugin *Builder) error + +func create(query string, options ...Option) (Builder, error) { + builder := &Builder{ + PluginSpec: PluginSpec{}, + } + + defaults := []Option{ + Query(query), + } + + for _, opt := range append(defaults, options...) { + if err := opt(builder); err != nil { + return *builder, err + } + } + + return *builder, nil +} + +type Builder struct { + PluginSpec `json:",inline" yaml:",inline"` +} + +// ClickHouseTraceQuery reads a trace, when expr is a trace ID or a variable holding one, or searches the traces of +// the spans returned by expr, a query returning their "TraceId" and "Timestamp" columns. +func ClickHouseTraceQuery(expr string, options ...Option) query.Option { + plg, err := create(expr, options...) + return query.Option{ + Kind: plugin.KindTraceQuery, + Plugin: plugin.Plugin{ + Kind: PluginKind, + Spec: plg, + }, + Error: err, + } +} diff --git a/clickhouse/sdk/go/query/trace/trace_test.go b/clickhouse/sdk/go/query/trace/trace_test.go new file mode 100644 index 000000000..1a822371b --- /dev/null +++ b/clickhouse/sdk/go/query/trace/trace_test.go @@ -0,0 +1,53 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package trace + +import ( + "encoding/json" + "testing" + + "github.com/perses/spec/go/plugin" +) + +func TestClickHouseTraceQueryMarshalsItsOptions(t *testing.T) { + option := ClickHouseTraceQuery( + "SELECT TraceId, Timestamp FROM otel_traces WHERE StatusCode = 'Error'", + Datasource("clickhouse"), + Table("otel.otel_traces"), + Limit(50), + ) + if option.Error != nil { + t.Fatal(option.Error) + } + if option.Kind != plugin.KindTraceQuery { + t.Fatalf("got kind %s, want %s", option.Kind, plugin.KindTraceQuery) + } + got, err := json.Marshal(option.Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickHouseTraceQuery","spec":{"datasource":{"kind":"ClickHouseDatasource","name":"clickhouse"},"query":"SELECT TraceId, Timestamp FROM otel_traces WHERE StatusCode = 'Error'","table":"otel.otel_traces","limit":50}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} + +func TestClickHouseTraceQueryRejectsInvalidOptions(t *testing.T) { + if err := ClickHouseTraceQuery("$traceId", Table("otel_traces WHERE 1 = 1")).Error; err == nil { + t.Fatal("expected an error for a table that is not a table name") + } + if err := ClickHouseTraceQuery("$traceId", Limit(0)).Error; err == nil { + t.Fatal("expected an error for a limit that is not positive") + } +} diff --git a/clickhouse/sdk/go/variable/sql/options.go b/clickhouse/sdk/go/variable/sql/options.go new file mode 100644 index 000000000..f75608ffc --- /dev/null +++ b/clickhouse/sdk/go/variable/sql/options.go @@ -0,0 +1,36 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package sql + +import ( + clickhouseDatasource "github.com/perses/plugins/clickhouse/sdk/go/datasource" +) + +func Query(expr string) Option { + return func(builder *Builder) error { + builder.Query = expr + return nil + } +} + +func Datasource(datasourceName string) Option { + return func(builder *Builder) error { + sel, err := clickhouseDatasource.Selector(datasourceName) + if err != nil { + return err + } + builder.Datasource = sel + return nil + } +} diff --git a/clickhouse/sdk/go/variable/sql/sql.go b/clickhouse/sdk/go/variable/sql/sql.go new file mode 100644 index 000000000..6f1ef745c --- /dev/null +++ b/clickhouse/sdk/go/variable/sql/sql.go @@ -0,0 +1,64 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package sql + +import ( + "github.com/perses/perses/go-sdk/datasource" + listvariable "github.com/perses/perses/go-sdk/variable/list-variable" +) + +const PluginKind = "ClickHouseSQLVariable" + +type PluginSpec struct { + Datasource *datasource.Selector `json:"datasource,omitempty" yaml:"datasource,omitempty"` + Query string `json:"query" yaml:"query"` +} + +type Option func(plugin *Builder) error + +func create(query string, options ...Option) (Builder, error) { + builder := &Builder{ + PluginSpec: PluginSpec{}, + } + + defaults := []Option{ + Query(query), + } + + for _, opt := range append(defaults, options...) { + if err := opt(builder); err != nil { + return *builder, err + } + } + + return *builder, nil +} + +type Builder struct { + PluginSpec `json:",inline" yaml:",inline"` +} + +// ClickHouseSQL lists the values of a variable with a query: the values are its "value" column, or else its first +// column, and their display labels its optional "label" column. +func ClickHouseSQL(expr string, options ...Option) listvariable.Option { + return func(builder *listvariable.Builder) error { + plg, err := create(expr, options...) + if err != nil { + return err + } + builder.ListVariableSpec.Plugin.Kind = PluginKind + builder.ListVariableSpec.Plugin.Spec = plg + return nil + } +} diff --git a/clickhouse/sdk/go/variable/sql/sql_test.go b/clickhouse/sdk/go/variable/sql/sql_test.go new file mode 100644 index 000000000..1784483d0 --- /dev/null +++ b/clickhouse/sdk/go/variable/sql/sql_test.go @@ -0,0 +1,40 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package sql + +import ( + "encoding/json" + "testing" + + listvariable "github.com/perses/perses/go-sdk/variable/list-variable" +) + +func TestClickHouseSQLConfiguresAListVariable(t *testing.T) { + builder := &listvariable.Builder{} + err := ClickHouseSQL( + "SELECT DISTINCT ServiceName FROM otel_traces WHERE $__timeFilter(Timestamp)", + Datasource("clickhouse"), + )(builder) + if err != nil { + t.Fatal(err) + } + got, err := json.Marshal(builder.ListVariableSpec.Plugin) + if err != nil { + t.Fatal(err) + } + want := `{"kind":"ClickHouseSQLVariable","spec":{"datasource":{"kind":"ClickHouseDatasource","name":"clickhouse"},"query":"SELECT DISTINCT ServiceName FROM otel_traces WHERE $__timeFilter(Timestamp)"}}` + if string(got) != want { + t.Fatalf("got %s, want %s", got, want) + } +} diff --git a/clickhouse/src/annotations/click-house-sql-annotation/ClickHouseSQLAnnotation.tsx b/clickhouse/src/annotations/click-house-sql-annotation/ClickHouseSQLAnnotation.tsx new file mode 100644 index 000000000..e4859fa22 --- /dev/null +++ b/clickhouse/src/annotations/click-house-sql-annotation/ClickHouseSQLAnnotation.tsx @@ -0,0 +1,26 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { AnnotationPlugin } from '@perses-dev/plugin-system'; + +import { queryDependencies } from '../../model/execute-query'; +import type { ClickHouseSQLAnnotationSpec } from './click-house-sql-annotation-types'; +import { ClickHouseSQLAnnotationEditor } from './ClickHouseSQLAnnotationEditor'; +import { getAnnotationData } from './get-annotation-data'; + +export const ClickHouseSQLAnnotation: AnnotationPlugin = { + getAnnotationData, + dependsOn: (spec) => queryDependencies(spec.datasource, spec.query), + OptionsEditorComponent: ClickHouseSQLAnnotationEditor, + createInitialOptions: () => ({ query: '' }), +}; diff --git a/clickhouse/src/annotations/click-house-sql-annotation/ClickHouseSQLAnnotationEditor.tsx b/clickhouse/src/annotations/click-house-sql-annotation/ClickHouseSQLAnnotationEditor.tsx new file mode 100644 index 000000000..41596b6f9 --- /dev/null +++ b/clickhouse/src/annotations/click-house-sql-annotation/ClickHouseSQLAnnotationEditor.tsx @@ -0,0 +1,44 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { Stack } from '@mui/material'; +import type { OptionsEditorProps } from '@perses-dev/plugin-system'; +import type { ReactElement } from 'react'; + +import { ClickHouseDatasourceSelect, QueryExamples, SQLField } from '../../components'; +import { ANNOTATION_EXAMPLES } from '../../components/query-examples'; +import type { ClickHouseSQLAnnotationSpec } from './click-house-sql-annotation-types'; + +type ClickHouseSQLAnnotationEditorProps = OptionsEditorProps; + +export function ClickHouseSQLAnnotationEditor(props: ClickHouseSQLAnnotationEditorProps): ReactElement { + const { onChange, value, isReadonly } = props; + + return ( + + onChange({ ...value, datasource })} + isReadonly={isReadonly} + /> + onChange({ ...value, query })} + placeholder="Enter a ClickHouse SQL query returning the annotations" + isReadonly={isReadonly} + /> + + + ); +} diff --git a/clickhouse/src/model/click-house-data-types.ts b/clickhouse/src/annotations/click-house-sql-annotation/click-house-sql-annotation-types.ts similarity index 69% rename from clickhouse/src/model/click-house-data-types.ts rename to clickhouse/src/annotations/click-house-sql-annotation/click-house-sql-annotation-types.ts index 0827850aa..cc7be20e9 100644 --- a/clickhouse/src/model/click-house-data-types.ts +++ b/clickhouse/src/annotations/click-house-sql-annotation/click-house-sql-annotation-types.ts @@ -11,13 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -import type { LogData, TimeSeriesData } from '@perses-dev/spec'; +import type { ClickHouseQuerySpec } from '../../model/execute-query'; -export interface ClickHouseTimeSeriesData extends TimeSeriesData { - logs?: LogData; -} - -export interface TimeSeriesEntry { - time: string; - [key: string]: number | string | null | undefined; -} +export type ClickHouseSQLAnnotationSpec = ClickHouseQuerySpec; diff --git a/clickhouse/src/annotations/click-house-sql-annotation/click-house-sql-annotation.test.ts b/clickhouse/src/annotations/click-house-sql-annotation/click-house-sql-annotation.test.ts new file mode 100644 index 000000000..64725aff6 --- /dev/null +++ b/clickhouse/src/annotations/click-house-sql-annotation/click-house-sql-annotation.test.ts @@ -0,0 +1,85 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { stubResponse } from '../../test/stubs'; +import { buildAnnotations } from './get-annotation-data'; + +describe('buildAnnotations', () => { + it('reads a row as an annotation: its time, its texts, and its other columns as tags', () => { + expect( + buildAnnotations( + stubResponse( + [ + ['time', "DateTime('UTC')"], + ['title', 'String'], + ['legend', 'String'], + ['service', 'String'], + ['attributes', 'Map(String, String)'], + ['empty', 'String'], + ], + [ + ['2026-01-01T10:00:00Z', 'Deployment', 'v1.2', 'api', { author: 'me' }, ''], + // Not a time: left out. + ['soon', 'Skipped', '', 'api', {}, ''], + ], + ), + ), + ).toEqual([ + { + start: Date.UTC(2026, 0, 1, 10), + title: 'Deployment', + legend: 'v1.2', + tags: { service: 'api', 'attributes.author': 'me' }, + }, + ]); + }); + + it('reads the "start" and "end" columns as a time span', () => { + expect( + buildAnnotations( + stubResponse( + [ + ['end', "DateTime('UTC')"], + ['start', "DateTime('UTC')"], + ], + [ + ['2026-01-01T10:30:00Z', '2026-01-01T10:00:00Z'], + // An end that is not after the start is no time span. + ['2026-01-01T09:00:00Z', '2026-01-01T10:00:00Z'], + ], + ), + ), + ).toEqual([ + { start: Date.UTC(2026, 0, 1, 10), end: Date.UTC(2026, 0, 1, 10, 30) }, + { start: Date.UTC(2026, 0, 1, 10) }, + ]); + }); + + it('falls back to the first date/time column, and fails without any', () => { + expect( + buildAnnotations( + stubResponse( + [ + ['name', 'String'], + ['deployed_at', 'DateTime'], + ], + [['api', '2026-01-01 11:00:00']], + { timeZone: 'Europe/Paris' }, + ), + ), + ).toEqual([{ start: Date.UTC(2026, 0, 1, 10), tags: { name: 'api' } }]); + expect(() => buildAnnotations(stubResponse([['name', 'String']], [['api']]))).toThrow( + /must return a "time" column/, + ); + }); +}); diff --git a/clickhouse/src/annotations/click-house-sql-annotation/get-annotation-data.ts b/clickhouse/src/annotations/click-house-sql-annotation/get-annotation-data.ts new file mode 100644 index 000000000..1655987be --- /dev/null +++ b/clickhouse/src/annotations/click-house-sql-annotation/get-annotation-data.ts @@ -0,0 +1,90 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { AnnotationPlugin } from '@perses-dev/plugin-system'; +import type { AnnotationData } from '@perses-dev/spec'; + +import type { ClickHouseQueryResponse } from '../../model/click-house-client'; +import { findColumn, getTypeTimeZone, isTimeType } from '../../model/click-house-types'; +import { executeQuery } from '../../model/execute-query'; +import { addLabels, toText, toUnixMs } from '../../model/values'; +import type { ClickHouseSQLAnnotationSpec } from './click-house-sql-annotation-types'; + +/** Names of the column holding the start of an annotation, by priority, compared case-insensitively. */ +const START_COLUMNS = ['start', 'time', 'timestamp'] as const; + +/** + * buildAnnotations converts a result into annotations. Each row is an annotation: it starts at its `start` or + * `time` column, or else at its first date/time column, and spans up to its `end` column when it has one. Its + * `title` and `legend` columns are its texts, and its other columns are its tags. + */ +export function buildAnnotations(response: ClickHouseQueryResponse): AnnotationData[] { + const { columns, rows } = response; + const end = findColumn(columns, ['end']); + const named = findColumn(columns, START_COLUMNS); + const start = named !== -1 ? named : columns.findIndex((column, index) => index !== end && isTimeType(column.type)); + if (rows.length > 0 && start === -1) { + throw new Error('An annotation query must return a "time" column, or a "start" and an "end" column.'); + } + const startTimeZone = getTypeTimeZone(columns[start]?.type ?? '') ?? response.timeZone; + const endTimeZone = getTypeTimeZone(columns[end]?.type ?? '') ?? response.timeZone; + const title = findColumn(columns, ['title']); + const legend = findColumn(columns, ['legend']); + + const annotations: AnnotationData[] = []; + for (const row of rows) { + const startMs = toUnixMs(row[start], startTimeZone); + if (Number.isNaN(startMs)) continue; + const annotation: AnnotationData = { start: startMs }; + const endMs = end === -1 ? NaN : toUnixMs(row[end], endTimeZone); + // An end at or before the start is no time span: the annotation is a point in time. + if (endMs > startMs) annotation.end = endMs; + const titleText = title === -1 ? '' : toText(row[title]); + if (titleText) annotation.title = titleText; + const legendText = legend === -1 ? '' : toText(row[legend]); + if (legendText) annotation.legend = legendText; + + const tags: Record = {}; + for (let index = 0; index < columns.length; index++) { + if (index !== start && index !== end && index !== title && index !== legend) { + addLabels(tags, columns[index]?.name ?? '', row[index]); + } + } + for (const name of Object.keys(tags)) { + if (tags[name] === '') delete tags[name]; + } + if (Object.keys(tags).length > 0) annotation.tags = tags; + annotations.push(annotation); + } + return annotations; +} + +export const getAnnotationData: AnnotationPlugin['getAnnotationData'] = async ( + spec, + context, + abortSignal, +) => { + if (!spec.query?.trim()) { + return []; + } + const result = await executeQuery( + spec, + { + datasourceStore: context.datasourceStore, + variableState: context.variableState, + timeRange: context.absoluteTimeRange, + }, + abortSignal, + ); + return buildAnnotations(result); +}; diff --git a/clickhouse/src/annotations/click-house-sql-annotation/index.ts b/clickhouse/src/annotations/click-house-sql-annotation/index.ts new file mode 100644 index 000000000..61f897537 --- /dev/null +++ b/clickhouse/src/annotations/click-house-sql-annotation/index.ts @@ -0,0 +1,17 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export * from './ClickHouseSQLAnnotation'; +export * from './ClickHouseSQLAnnotationEditor'; +export * from './get-annotation-data'; +export * from './click-house-sql-annotation-types'; diff --git a/clickhouse/src/queries/constants.ts b/clickhouse/src/annotations/index.ts similarity index 83% rename from clickhouse/src/queries/constants.ts rename to clickhouse/src/annotations/index.ts index 52447366e..55be74096 100644 --- a/clickhouse/src/queries/constants.ts +++ b/clickhouse/src/annotations/index.ts @@ -11,5 +11,4 @@ // See the License for the specific language governing permissions and // limitations under the License. -export const DATASOURCE_KIND = 'ClickHouseDatasource'; -export const DEFAULT_DATASOURCE = { kind: DATASOURCE_KIND }; +export * from './click-house-sql-annotation'; diff --git a/clickhouse/src/components/ClickHouseDatasourceSelect.tsx b/clickhouse/src/components/ClickHouseDatasourceSelect.tsx new file mode 100644 index 000000000..fdefce7df --- /dev/null +++ b/clickhouse/src/components/ClickHouseDatasourceSelect.tsx @@ -0,0 +1,52 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { DatasourceSelectProps } from '@perses-dev/plugin-system'; +import { DatasourceSelect } from '@perses-dev/plugin-system'; +import type { ReactElement } from 'react'; + +import type { ClickHouseDatasourceSelectValue } from '../model/click-house-selectors'; +import { + CLICKHOUSE_DATASOURCE_KIND, + DEFAULT_CLICKHOUSE, + isClickHouseDatasourceSelectValue, +} from '../model/click-house-selectors'; + +export interface ClickHouseDatasourceSelectProps { + value: ClickHouseDatasourceSelectValue | undefined; + onChange: (next: ClickHouseDatasourceSelectValue) => void; + isReadonly?: boolean; +} + +/** ClickHouseDatasourceSelect selects the ClickHouse datasource of a query, or a variable holding its name. */ +export function ClickHouseDatasourceSelect(props: ClickHouseDatasourceSelectProps): ReactElement { + const { value, onChange, isReadonly } = props; + + const handleChange: DatasourceSelectProps['onChange'] = (next) => { + if (!isClickHouseDatasourceSelectValue(next)) { + throw new Error('Got unexpected non ClickHouse datasource selection'); + } + onChange(next); + }; + + return ( + + ); +} diff --git a/clickhouse/src/components/ClickQLEditor.tsx b/clickhouse/src/components/ClickQLEditor.tsx index 8da728ae3..f12fecba1 100644 --- a/clickhouse/src/components/ClickQLEditor.tsx +++ b/clickhouse/src/components/ClickQLEditor.tsx @@ -16,12 +16,36 @@ import { useTheme, InputLabel, Stack } from '@mui/material'; import type { ReactCodeMirrorProps } from '@uiw/react-codemirror'; import CodeMirror from '@uiw/react-codemirror'; import type { ReactElement } from 'react'; +import { useMemo } from 'react'; -export type ClickQLEditorProps = Omit; +export type ClickQLEditorProps = Omit & { + /** Label displayed above the editor. */ + label?: string; +}; + +const BASIC_SETUP: ReactCodeMirrorProps['basicSetup'] = { + highlightActiveLine: false, + highlightActiveLineGutter: false, + foldGutter: false, + syntaxHighlighting: true, +}; + +const EXTENSIONS = [ + EditorView.lineWrapping, + EditorView.theme({ + '.cm-content': { + paddingTop: '8px', + paddingBottom: '8px', + paddingRight: '40px', + }, + }), +]; export function ClickQLEditor(props: ClickQLEditorProps): ReactElement { + const { label = 'ClickHouse Query', ...editorProps } = props; const theme = useTheme(); - const isDarkMode = theme.palette.mode === 'dark'; + // The editor is reconfigured each time its extensions change: keep them stable. + const extensions = useMemo(() => [...EXTENSIONS, EditorView.contentAttributes.of({ 'aria-label': label })], [label]); return ( @@ -32,29 +56,15 @@ export function ClickQLEditor(props: ClickQLEditorProps): ReactElement { color: theme.palette.text.primary, }} > - ClickHouse Query + {label} ); diff --git a/clickhouse/src/components/DraftTextField.tsx b/clickhouse/src/components/DraftTextField.tsx new file mode 100644 index 000000000..d8d7f712f --- /dev/null +++ b/clickhouse/src/components/DraftTextField.tsx @@ -0,0 +1,51 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { TextFieldProps } from '@mui/material'; +import { TextField } from '@mui/material'; +import type { ReactElement } from 'react'; + +import { useDraftText } from './use-draft-text'; + +export type DraftTextFieldProps = Omit & { + value: string | undefined; + /** Called with the edited text when the field loses the focus, or on Enter. */ + onChange: (next: string) => void; + isReadonly?: boolean; +}; + +/** DraftTextField is a text field that saves its value when it loses the focus rather than on every keystroke. */ +export function DraftTextField(props: DraftTextFieldProps): ReactElement { + const { value, onChange, isReadonly, slotProps, ...textFieldProps } = props; + const { draft, setDraft, commit } = useDraftText(value, onChange); + + return ( + setDraft(event.target.value)} + onBlur={commit} + onKeyDown={(event) => { + if (event.key === 'Enter') commit(); + }} + slotProps={{ + ...slotProps, + input: { readOnly: isReadonly, ...slotProps?.input }, + // A placeholder is only visible under a label that stays above the field. + inputLabel: { ...(textFieldProps.placeholder ? { shrink: true } : undefined), ...slotProps?.inputLabel }, + }} + /> + ); +} diff --git a/clickhouse/src/components/QueryExamples.tsx b/clickhouse/src/components/QueryExamples.tsx new file mode 100644 index 000000000..bb14530bc --- /dev/null +++ b/clickhouse/src/components/QueryExamples.tsx @@ -0,0 +1,47 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { Box } from '@mui/material'; +import type { ReactElement } from 'react'; + +export interface QueryExamplesProps { + /** Commented SQL statements showing what the queries of a plugin look like. */ + examples: string; +} + +/** QueryExamples is a foldable block of example queries. */ +export function QueryExamples({ examples }: QueryExamplesProps): ReactElement { + return ( +
+ + Query Examples + + ({ + margin: 0, + fontSize: '11px', + color: theme.palette.text.secondary, + backgroundColor: theme.palette.background.default, + padding: '8px', + borderRadius: '4px', + fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace', + whiteSpace: 'pre-wrap', + lineHeight: '1.3', + })} + > + {examples} + +
+ ); +} diff --git a/clickhouse/src/components/SQLField.tsx b/clickhouse/src/components/SQLField.tsx new file mode 100644 index 000000000..2dc7061d0 --- /dev/null +++ b/clickhouse/src/components/SQLField.tsx @@ -0,0 +1,45 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { createModEnterHandler } from '@perses-dev/dashboards'; +import type { ReactElement } from 'react'; + +import { ClickQLEditor } from './ClickQLEditor'; +import { useDraftText } from './use-draft-text'; + +export interface SQLFieldProps { + label: string; + value: string | undefined; + /** Called with the edited statement when the editor loses the focus, or on Ctrl/Cmd + Enter. */ + onChange: (next: string) => void; + placeholder?: string; + isReadonly?: boolean; +} + +/** SQLField edits a SQL statement of a query spec. */ +export function SQLField(props: SQLFieldProps): ReactElement { + const { label, value, onChange, placeholder, isReadonly } = props; + const { draft, setDraft, commit } = useDraftText(value, onChange); + + return ( + + ); +} diff --git a/clickhouse/src/components/index.ts b/clickhouse/src/components/index.ts index ee5fd806d..f787fc666 100644 --- a/clickhouse/src/components/index.ts +++ b/clickhouse/src/components/index.ts @@ -11,4 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +export * from './ClickHouseDatasourceSelect'; export * from './ClickQLEditor'; +export * from './DraftTextField'; +export * from './QueryExamples'; +export * from './SQLField'; +export * from './use-draft-text'; diff --git a/clickhouse/src/components/query-examples.ts b/clickhouse/src/components/query-examples.ts new file mode 100644 index 000000000..e5de50305 --- /dev/null +++ b/clickhouse/src/components/query-examples.ts @@ -0,0 +1,123 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const MACROS = `-- Macros (the time range and the interval come from the dashboard): +-- $__timeFilter(column) column >= AND column <= , with second precision +-- $__timeFilter_ms(column) same, with millisecond precision +-- $__timeInterval(column) toStartOfInterval(toDateTime(column), INTERVAL second) +-- $__interval_s interval between two points, in seconds +-- $__fromTime, $__toTime start and end of the time range, as DateTime +-- $__conditionalAll(condition, $variable) the condition, or 1=1 when "All" is selected +-- Variables: \${variable:sqlstring} quotes the values, e.g. ServiceName IN (\${service:sqlstring})`; + +export const TIME_SERIES_EXAMPLES = `-- A query returns a "time" column, numeric columns for the values, +-- and optional other columns: the rows are then split in one series per value of these columns. + +-- Requests per service, from the OpenTelemetry traces +SELECT + $__timeInterval(Timestamp) AS time, + ServiceName, + count() / $__interval_s AS rps +FROM otel_traces +WHERE $__timeFilter(Timestamp) AND SpanKind = 'Server' +GROUP BY time, ServiceName +ORDER BY time + +-- An OpenTelemetry gauge, split by one of its attributes +SELECT + $__timeInterval(TimeUnix) AS time, + Attributes['state'] AS state, + avg(Value) AS value +FROM otel_metrics_gauge +WHERE $__timeFilter(TimeUnix) AND MetricName = 'system.memory.utilization' +GROUP BY time, state +ORDER BY time + +-- Exemplar query: a "time" and a "value" column, the label columns of the series (here ServiceName), +-- and the labels of the exemplar +SELECT Timestamp AS time, Duration / 1e6 AS value, ServiceName, TraceId AS trace_id, SpanId AS span_id +FROM otel_traces +WHERE $__timeFilter(Timestamp) AND SpanKind = 'Server' +ORDER BY Duration DESC +LIMIT 100 + +${MACROS}`; + +export const LOG_EXAMPLES = `-- A query returns a time column ("Timestamp", "timestamp" or "time") and, for the log line, +-- a "Body", "message" or "line" column. The other columns are the labels of the log. + +-- OpenTelemetry logs +SELECT Timestamp, Body, SeverityText, ServiceName, TraceId, LogAttributes, ResourceAttributes +FROM otel_logs +WHERE $__timeFilter(Timestamp) AND ServiceName IN (\${service:sqlstring}) +ORDER BY Timestamp DESC +LIMIT 1000 + +${MACROS}`; + +export const TRACE_EXAMPLES = `-- Either a trace ID (or a variable holding one), to display a trace, +-- or a query returning the "TraceId" and the "Timestamp" of the spans to search for: +-- their traces are then listed, the most recent ones first. + +-- Traces with a slow or failed request of a service +SELECT TraceId, Timestamp +FROM otel_traces +WHERE $__timeFilter(Timestamp) + AND ServiceName = 'checkout' + AND (StatusCode = 'Error' OR Duration > 1e9) + +-- A trace, from a dashboard variable +$traceId + +${MACROS}`; + +export const PROFILE_EXAMPLES = `-- A query returns one row per sample, with a "stack" column: the array of the frames of the sample, +-- from the leaf to the root, as in OpenTelemetry. Optional columns: "value" (1 by default), +-- "time" (for the timeline), "unit" and "name". + +-- CPU samples of a service, from the OpenTelemetry profiles +SELECT + Timestamp AS time, + arrayMap((name, file) -> if(name != '', name, file), FunctionNames, MappingFileNames) AS stack, + length(TimestampsUnixNano) AS value, + SampleType AS name, + SampleUnit AS unit +FROM otel_profiles +WHERE $__timeFilter(Timestamp) AND SampleType = 'samples' AND ServiceName = 'checkout' + +${MACROS}`; + +export const VARIABLE_EXAMPLES = `-- The values of the variable are the "value" column, or else the first column of the result. +-- An optional "label" column holds the text displayed for each value. + +-- Services sending traces +SELECT DISTINCT ServiceName FROM otel_traces WHERE $__timeFilter(Timestamp) ORDER BY ServiceName + +-- Values of another variable +SELECT DISTINCT SpanName AS value +FROM otel_traces +WHERE $__timeFilter(Timestamp) AND ServiceName IN (\${service:sqlstring}) + +${MACROS}`; + +export const ANNOTATION_EXAMPLES = `-- A query returns one row per annotation, with a "time" column (or "start" and "end" for a time span). +-- Optional columns: "title" and "legend". The other columns are the tags of the annotation. + +-- Errors logged by the services +SELECT Timestamp AS time, Body AS title, ServiceName +FROM otel_logs +WHERE $__timeFilter(Timestamp) AND SeverityNumber >= 17 +ORDER BY Timestamp +LIMIT 100 + +${MACROS}`; diff --git a/clickhouse/src/components/use-draft-text.ts b/clickhouse/src/components/use-draft-text.ts new file mode 100644 index 000000000..3c1c5899e --- /dev/null +++ b/clickhouse/src/components/use-draft-text.ts @@ -0,0 +1,46 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { useState } from 'react'; + +export interface DraftText { + /** Text being edited. */ + draft: string; + setDraft: (next: string) => void; + /** Saves the draft, when it differs from the saved text. */ + commit: () => void; +} + +/** + * useDraftText keeps a local copy of a text of a spec while it is edited, and only saves it when asked to: on blur + * or on demand. Saving on every keystroke would run the query of a panel preview again and again. + */ +export function useDraftText(saved: string | undefined, onCommit: (next: string) => void): DraftText { + const [draft, setDraft] = useState(saved ?? ''); + + // When the spec changes outside of this editor, show its new text. + const [lastSaved, setLastSaved] = useState(saved); + if (saved !== lastSaved) { + setDraft(saved ?? ''); + setLastSaved(saved); + } + + const commit = (): void => { + if (draft !== (saved ?? '')) { + setLastSaved(draft); + onCommit(draft); + } + }; + + return { draft, setDraft, commit }; +} diff --git a/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasource.test.ts b/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasource.test.ts index 396c5a0cf..9b463e112 100644 --- a/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasource.test.ts +++ b/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasource.test.ts @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +import { allowsConnectionTest, getQueryMethod } from './allowed-endpoints'; import { ClickHouseDatasource } from './ClickHouseDatasource'; describe('ClickHouseDatasource.createClient', () => { @@ -19,25 +20,73 @@ describe('ClickHouseDatasource.createClient', () => { }); it('uses the custom fetch from options and not the global fetch', async () => { - const mockFetch = vi.fn().mockResolvedValue({ - ok: true, - status: 200, - json: () => Promise.resolve({ data: [] }), - }); + const mockFetch = vi.fn(async () => new Response('["a"]\n["UInt8"]\n[1]\n', { status: 200 })); const globalFetchSpy = vi.spyOn(globalThis, 'fetch'); const client = ClickHouseDatasource.createClient( - { directUrl: 'http://clickhouse.example.com' }, - { proxyUrl: 'http://proxy:8080', fetch: mockFetch as unknown as typeof fetch }, + { directUrl: 'http://clickhouse.example.com', database: 'otel' }, + { proxyUrl: 'http://proxy:8080', fetch: mockFetch }, ); - await client.query({ - query: 'SELECT 1', - start: '2025-01-01 00:00:00', - end: '2025-01-02 00:00:00', - }); + await expect(client.query({ query: 'SELECT 1 AS a' })).resolves.toMatchObject({ rows: [[1]] }); expect(mockFetch).toHaveBeenCalled(); expect(globalFetchSpy).not.toHaveBeenCalled(); + const url = new URL(String(mockFetch.mock.calls[0]?.[0])); + expect(url.origin).toBe('http://clickhouse.example.com'); + expect(url.searchParams.get('database')).toBe('otel'); + // The browser calls ClickHouse directly: it needs the CORS headers. + expect(url.searchParams.get('add_http_cors_header')).toBe('1'); + }); + + it('reads the tables of the "default" database unless the datasource names another one', async () => { + const mockFetch = vi.fn(async () => new Response('["a"]\n["UInt8"]\n[1]\n', { status: 200 })); + const client = ClickHouseDatasource.createClient({}, { proxyUrl: '/proxy/globaldatasources/ch', fetch: mockFetch }); + + await client.query({ query: 'SELECT 1 AS a' }); + + expect(new URL(String(mockFetch.mock.calls[0]?.[0])).searchParams.get('database')).toBe('default'); + }); + + it('fails without a URL', () => { + expect(() => ClickHouseDatasource.createClient({}, {})).toThrow(/No URL specified/); + }); +}); + +describe('getQueryMethod', () => { + it('sends queries with POST when the proxy lets them through', () => { + expect(getQueryMethod(undefined)).toBe('POST'); + expect(getQueryMethod([])).toBe('POST'); + expect( + getQueryMethod([ + { endpointPattern: '^/$', method: 'POST' }, + { endpointPattern: '^/ping$', method: 'GET' }, + ]), + ).toBe('POST'); + }); + + it('keeps sending them with GET through a proxy that only allows it', () => { + expect(getQueryMethod([{ endpointPattern: '/', method: 'GET' }])).toBe('GET'); + // POST is allowed, but not on the path of the queries. + expect( + getQueryMethod([ + { endpointPattern: '^/$', method: 'GET' }, + { endpointPattern: '^/write$', method: 'POST' }, + ]), + ).toBe('GET'); + }); +}); + +describe('allowsConnectionTest', () => { + it('tells whether the proxy lets the connection test through', () => { + expect(allowsConnectionTest(undefined)).toBe(true); + expect( + allowsConnectionTest([ + { endpointPattern: '^/$', method: 'POST' }, + { endpointPattern: '^/ping$', method: 'GET' }, + ]), + ).toBe(true); + // The datasources created before the connection test only allow the queries. + expect(allowsConnectionTest([{ endpointPattern: '^/$', method: 'GET' }])).toBe(false); }); }); diff --git a/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasource.tsx b/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasource.tsx index 7dc40f733..7362aa9c1 100644 --- a/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasource.tsx +++ b/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasource.tsx @@ -12,16 +12,21 @@ // limitations under the License. import type { DatasourcePlugin } from '@perses-dev/plugin-system'; +import type { BuiltinVariableDefinition } from '@perses-dev/spec'; -import { query } from '../../model/click-house-client'; +import { createClickHouseClient } from '../../model/click-house-client'; +import { getQueryMethod, HEALTH_CHECK_PATH } from './allowed-endpoints'; import type { ClickHouseDatasourceSpec, ClickHouseDatasourceClient } from './click-house-datasource-types'; import { ClickHouseDatasourceEditor } from './ClickHouseDatasourceEditor'; +/** Database of the queries of a datasource that does not name one. */ +export const DEFAULT_DATABASE = 'default'; + const createClient: DatasourcePlugin['createClient'] = ( spec, options, ) => { - const { directUrl, proxy } = spec; + const { directUrl, proxy, database } = spec; const { proxyUrl, fetch: customFetch } = options; const datasourceUrl = directUrl ?? proxyUrl; @@ -31,18 +36,60 @@ const createClient: DatasourcePlugin query(params, { datasourceUrl, headers: headers ?? specHeaders, fetch: customFetch }), + ...client, }; }; +// The macros are replaced by the queries. Declaring them makes the editors document them as variables. +const getBuiltinVariableDefinitions = (): BuiltinVariableDefinition[] => + [ + { + name: '__interval_s', + description: + 'Interval between two data points, in seconds: a round duration of at least the step of the panel. Use it to size time buckets, e.g. `toStartOfInterval(Timestamp, INTERVAL $__interval_s second)`.', + }, + { + name: '__interval_ms', + description: 'Same as $__interval_s but in milliseconds.', + }, + { + name: '__fromTime', + description: 'Start of the time range as a DateTime. $__fromTime_ms has millisecond precision.', + }, + { + name: '__toTime', + description: 'End of the time range as a DateTime. $__toTime_ms has millisecond precision.', + }, + ].map(({ name, description }) => ({ + kind: 'BuiltinVariable', + spec: { + name, + // Left as is: the queries replace it with the value computed for their time range and panel. + value: () => `$${name}`, + source: 'ClickHouse', + display: { name, description, hidden: true }, + }, + })); + export const ClickHouseDatasource: DatasourcePlugin = { createClient, + getBuiltinVariableDefinitions, + healthCheckPath: HEALTH_CHECK_PATH, OptionsEditorComponent: ClickHouseDatasourceEditor, createInitialOptions: () => ({ directUrl: '' }), }; diff --git a/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasourceEditor.tsx b/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasourceEditor.tsx index 280894581..2bb7164b6 100644 --- a/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasourceEditor.tsx +++ b/clickhouse/src/datasources/click-house-datasource/ClickHouseDatasourceEditor.tsx @@ -11,46 +11,79 @@ // See the License for the specific language governing permissions and // limitations under the License. +import { Alert, TextField, Typography } from '@mui/material'; +import type { DatasourceEditorProps } from '@perses-dev/plugin-system'; import { HTTPSettingsEditor } from '@perses-dev/plugin-system'; import type { ReactElement } from 'react'; +import { allowsConnectionTest, HEALTH_CHECK_PATH } from './allowed-endpoints'; import type { ClickHouseDatasourceSpec } from './click-house-datasource-types'; -export interface ClickHouseDatasourceEditorProps { - value: ClickHouseDatasourceSpec; - onChange: (next: ClickHouseDatasourceSpec) => void; - isReadonly?: boolean; -} - -export function ClickHouseDatasourceEditor(props: ClickHouseDatasourceEditorProps): ReactElement { - const { value, onChange, isReadonly } = props; +export type ClickHouseDatasourceEditorProps = DatasourceEditorProps; - const initialSpecDirect: ClickHouseDatasourceSpec = { - directUrl: '', - }; +const initialSpecDirect: ClickHouseDatasourceSpec = { + directUrl: '', +}; - const initialSpecProxy: ClickHouseDatasourceSpec = { - proxy: { - kind: 'HTTPProxy', - spec: { - allowedEndpoints: [ - { - endpointPattern: '/', - method: 'GET', - }, - ], - url: '', - }, +const initialSpecProxy: ClickHouseDatasourceSpec = { + proxy: { + kind: 'HTTPProxy', + spec: { + allowedEndpoints: [ + // Queries. The plugin sends them with `readonly=2`, but only the grants of the ClickHouse user are a guarantee: + // connect with a read-only user. + { + endpointPattern: '^/$', + method: 'POST', + }, + // Connection test + { + endpointPattern: '^/ping$', + method: 'GET', + }, + ], + url: '', }, - }; + }, +}; + +export function ClickHouseDatasourceEditor(props: ClickHouseDatasourceEditorProps): ReactElement { + const { value, onChange, isReadonly, testConnection } = props; return ( - + <> + + General Settings + + onChange({ ...value, database: event.target.value || undefined })} + helperText="Database of the tables that queries do not qualify, e.g. the one holding the OpenTelemetry tables. Leave it empty to use the database named default." + sx={{ mb: 2 }} + /> + + {value.proxy && !allowsConnectionTest(value.proxy.spec.allowedEndpoints) && ( + + The connection test calls GET {HEALTH_CHECK_PATH}, which the allowed endpoints of the proxy do + not include: add the ^{HEALTH_CHECK_PATH}$ pattern with the GET method to test the connection. + + )} + ); } diff --git a/clickhouse/src/datasources/click-house-datasource/allowed-endpoints.ts b/clickhouse/src/datasources/click-house-datasource/allowed-endpoints.ts new file mode 100644 index 000000000..d5a2b480f --- /dev/null +++ b/clickhouse/src/datasources/click-house-datasource/allowed-endpoints.ts @@ -0,0 +1,51 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { HTTPAllowedEndpoint } from '@perses-dev/spec'; + +const QUERY_PATH = '/'; +/** Path of the connection test, which Perses calls with GET. */ +export const HEALTH_CHECK_PATH = '/ping'; + +function allows(endpoint: HTTPAllowedEndpoint, method: string, path: string): boolean { + if (endpoint.method.toUpperCase() !== method) return false; + try { + return new RegExp(endpoint.endpointPattern).test(path); + } catch { + // The pattern is a Go regular expression: when JavaScript can not read it, let the proxy decide. + return true; + } +} + +function allowsQueries(endpoint: HTTPAllowedEndpoint, method: string): boolean { + return allows(endpoint, method, QUERY_PATH); +} + +/** + * allowsConnectionTest reports whether a proxy lets the connection test through. The datasources created before it + * existed only allow the queries. + */ +export function allowsConnectionTest(allowedEndpoints: HTTPAllowedEndpoint[] | undefined): boolean { + if (!allowedEndpoints || allowedEndpoints.length === 0) return true; + return allowedEndpoints.some((endpoint) => allows(endpoint, 'GET', HEALTH_CHECK_PATH)); +} + +/** + * getQueryMethod picks the HTTP method of the queries. They are sent with POST, which has no size limit, unless the + * proxy of the datasource only lets GET requests through, as the datasources created before POST was used do. + */ +export function getQueryMethod(allowedEndpoints: HTTPAllowedEndpoint[] | undefined): 'GET' | 'POST' { + if (!allowedEndpoints || allowedEndpoints.length === 0) return 'POST'; + if (allowedEndpoints.some((endpoint) => allowsQueries(endpoint, 'POST'))) return 'POST'; + return allowedEndpoints.some((endpoint) => allowsQueries(endpoint, 'GET')) ? 'GET' : 'POST'; +} diff --git a/clickhouse/src/datasources/click-house-datasource/click-house-datasource-types.ts b/clickhouse/src/datasources/click-house-datasource/click-house-datasource-types.ts index 7145f8771..dd24bcf61 100644 --- a/clickhouse/src/datasources/click-house-datasource/click-house-datasource-types.ts +++ b/clickhouse/src/datasources/click-house-datasource/click-house-datasource-types.ts @@ -11,34 +11,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -import type { RequestHeaders } from '@perses-dev/client'; import type { DatasourceClient } from '@perses-dev/plugin-system'; -import type { HTTPProxy } from '@perses-dev/spec'; +import type { HTTPDatasourceSpec } from '@perses-dev/spec'; -export interface ClickHouseDatasourceSpec { - directUrl?: string; - proxy?: HTTPProxy; -} +import type { ClickHouseClient, ClickHouseQueryResponse } from '../../model/click-house-client'; -interface QueryRequestParameters extends Record { - query: string; - start: string; - end: string; +export interface ClickHouseDatasourceSpec extends HTTPDatasourceSpec { + /** Database the unqualified table names of the queries are read from. Defaults to `default`. */ + database?: string; } interface ClickHouseDatasourceClientOptions { datasourceUrl: string; - headers?: RequestHeaders; + database: string; } -export interface ClickHouseDatasourceResponse { - status: string; - warnings?: string[]; - // TODO: adjust this type to match your datasource response shape - data: unknown; -} +export type ClickHouseDatasourceResponse = ClickHouseQueryResponse; -export interface ClickHouseDatasourceClient extends DatasourceClient { +export interface ClickHouseDatasourceClient extends DatasourceClient, ClickHouseClient { options: ClickHouseDatasourceClientOptions; - query(params: QueryRequestParameters, headers?: RequestHeaders): Promise; + healthCheck: () => Promise; } diff --git a/clickhouse/src/datasources/click-stack-datasource/ClickStackDatasource.tsx b/clickhouse/src/datasources/click-stack-datasource/ClickStackDatasource.tsx new file mode 100644 index 000000000..5fce7c83d --- /dev/null +++ b/clickhouse/src/datasources/click-stack-datasource/ClickStackDatasource.tsx @@ -0,0 +1,48 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { DatasourcePlugin } from '@perses-dev/plugin-system'; + +import { API_ROOT_PATH, createClickStackClient } from '../../model/click-stack-client'; +import type { ClickStackDatasourceClient, ClickStackDatasourceSpec } from './click-stack-datasource-types'; +import { ClickStackDatasourceEditor } from './ClickStackDatasourceEditor'; + +const createClient: DatasourcePlugin['createClient'] = ( + spec, + options, +) => { + const { directUrl, proxy, uiUrl } = spec; + const { proxyUrl, fetch: customFetch } = options; + + const datasourceUrl = directUrl ?? proxyUrl; + if (datasourceUrl === undefined) { + throw new Error( + 'No URL specified for ClickStackDatasource client. You can use directUrl in the spec to configure it.', + ); + } + + return { + options: { + datasourceUrl, + uiUrl: uiUrl || undefined, + }, + ...createClickStackClient({ datasourceUrl, headers: proxy?.spec.headers, fetch: customFetch }), + }; +}; + +export const ClickStackDatasource: DatasourcePlugin = { + createClient, + healthCheckPath: API_ROOT_PATH, + OptionsEditorComponent: ClickStackDatasourceEditor, + createInitialOptions: () => ({ directUrl: '' }), +}; diff --git a/clickhouse/src/datasources/click-stack-datasource/ClickStackDatasourceEditor.tsx b/clickhouse/src/datasources/click-stack-datasource/ClickStackDatasourceEditor.tsx new file mode 100644 index 000000000..25735956f --- /dev/null +++ b/clickhouse/src/datasources/click-stack-datasource/ClickStackDatasourceEditor.tsx @@ -0,0 +1,82 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { TextField, Typography } from '@mui/material'; +import type { DatasourceEditorProps } from '@perses-dev/plugin-system'; +import { HTTPSettingsEditor } from '@perses-dev/plugin-system'; +import type { ReactElement } from 'react'; + +import type { ClickStackDatasourceSpec } from './click-stack-datasource-types'; + +export type ClickStackDatasourceEditorProps = DatasourceEditorProps; + +const initialSpecDirect: ClickStackDatasourceSpec = { + directUrl: '', +}; + +// ClickStack only answers to the browsers of its own UI and needs an API key: it is reached through the proxy, +// with a secret holding the key as a bearer token. +const initialSpecProxy: ClickStackDatasourceSpec = { + proxy: { + kind: 'HTTPProxy', + spec: { + allowedEndpoints: [ + { + endpointPattern: '^/api/v2/alerts$', + method: 'GET', + }, + // Connection test + { + endpointPattern: '^/api/v2$', + method: 'GET', + }, + ], + url: '', + }, + }, +}; + +export function ClickStackDatasourceEditor(props: ClickStackDatasourceEditorProps): ReactElement { + const { value, onChange, isReadonly, testConnection } = props; + + return ( + <> + + General Settings + + onChange({ ...value, uiUrl: event.target.value || undefined })} + helperText="URL of the ClickStack UI, as you open it in your browser. Alerts link to the dashboard or the saved search they watch. Leave it empty for alerts without links." + sx={{ mb: 2 }} + /> + + + ); +} diff --git a/clickhouse/src/datasources/click-stack-datasource/click-stack-datasource-types.ts b/clickhouse/src/datasources/click-stack-datasource/click-stack-datasource-types.ts new file mode 100644 index 000000000..9df237456 --- /dev/null +++ b/clickhouse/src/datasources/click-stack-datasource/click-stack-datasource-types.ts @@ -0,0 +1,31 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { DatasourceClient } from '@perses-dev/plugin-system'; +import type { HTTPDatasourceSpec } from '@perses-dev/spec'; + +import type { ClickStackClient } from '../../model/click-stack-client'; + +export interface ClickStackDatasourceSpec extends HTTPDatasourceSpec { + /** URL of the ClickStack UI, as users open it in their browser. The alerts link to it. */ + uiUrl?: string; +} + +interface ClickStackDatasourceClientOptions { + datasourceUrl: string; + uiUrl?: string; +} + +export interface ClickStackDatasourceClient extends DatasourceClient, ClickStackClient { + options: ClickStackDatasourceClientOptions; +} diff --git a/clickhouse/src/datasources/click-stack-datasource/index.ts b/clickhouse/src/datasources/click-stack-datasource/index.ts new file mode 100644 index 000000000..3423155da --- /dev/null +++ b/clickhouse/src/datasources/click-stack-datasource/index.ts @@ -0,0 +1,16 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export * from './click-stack-datasource-types'; +export * from './ClickStackDatasource'; +export * from './ClickStackDatasourceEditor'; diff --git a/clickhouse/src/datasources/index.ts b/clickhouse/src/datasources/index.ts index f0857cd28..8adf69055 100644 --- a/clickhouse/src/datasources/index.ts +++ b/clickhouse/src/datasources/index.ts @@ -12,3 +12,4 @@ // limitations under the License. export * from './click-house-datasource'; +export * from './click-stack-datasource'; diff --git a/clickhouse/src/explore/ClickHouseExplorer.test.tsx b/clickhouse/src/explore/ClickHouseExplorer.test.tsx new file mode 100644 index 000000000..ad27a955f --- /dev/null +++ b/clickhouse/src/explore/ClickHouseExplorer.test.tsx @@ -0,0 +1,226 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type * as PluginSystemModule from '@perses-dev/plugin-system'; +import type { QueryDefinition } from '@perses-dev/spec'; +import { fireEvent, render, screen } from '@testing-library/react'; +import type { ReactElement, ReactNode } from 'react'; + +import { ClickHouseExplorer, getTableTransforms } from './ClickHouseExplorer'; +import type { ClickHouseExplorerQueryParams } from './links'; +import { linkToSpan, linkToTrace } from './links'; + +const mocks = vi.hoisted(() => ({ + data: {} as ClickHouseExplorerQueryParams, + setData: vi.fn(), + refresh: vi.fn(), + panels: [] as string[], + editors: [] as Array<{ queryTypes: string[]; queries: QueryDefinition[] }>, +})); + +vi.mock('@perses-dev/explore', () => ({ + useExplorerManagerContext: (): unknown => ({ data: mocks.data, setData: mocks.setData }), +})); + +vi.mock('@perses-dev/dashboards', () => ({ + Panel: ({ definition }: { definition: { spec: { plugin: { kind: string } } } }): null => { + mocks.panels.push(definition.spec.plugin.kind); + return null; + }, +})); + +vi.mock('use-resize-observer', () => ({ + useResizeObserver: (): unknown => ({ width: 1000, ref: vi.fn() }), +})); + +vi.mock('@perses-dev/plugin-system', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useTimeRange: (): unknown => ({ refresh: mocks.refresh }), + useSuggestedStepMs: (): number => 15_000, + useDataQueries: (): unknown => ({ queryResults: [], isFetching: false, isPending: false }), + DataQueriesProvider: ({ children }: { children: ReactNode }): ReactNode => children, + MultiQueryEditor: ({ + queryTypes, + queries, + onChange, + onQueryRun, + }: { + queryTypes: string[]; + queries: QueryDefinition[]; + onChange: (queries: QueryDefinition[]) => void; + onQueryRun: () => void; + }): ReactElement => { + mocks.editors.push({ queryTypes, queries }); + return ( + <> + + + + ); + }, + }; +}); + +function traceQuery(query: string, spec: Record = {}): QueryDefinition { + return { kind: 'TraceQuery', spec: { plugin: { kind: 'ClickHouseTraceQuery', spec: { ...spec, query } } } }; +} + +function profileQuery(query: string): QueryDefinition { + return { kind: 'ProfileQuery', spec: { plugin: { kind: 'ClickHouseProfileQuery', spec: { query } } } }; +} + +const TIME_SERIES_QUERY: QueryDefinition = { + kind: 'TimeSeriesQuery', + spec: { plugin: { kind: 'ClickHouseTimeSeriesQuery', spec: { query: 'SELECT 1 AS value' } } }, +}; + +function parseLink(link: string): { explorer: string | null; data: unknown; tz: string | null } { + const params = new URLSearchParams(link.split('?')[1]); + return { explorer: params.get('explorer'), data: JSON.parse(params.get('data') ?? 'null'), tz: params.get('tz') }; +} + +describe('ClickHouseExplorer', () => { + beforeEach(() => { + mocks.setData.mockClear(); + mocks.refresh.mockClear(); + mocks.panels = []; + mocks.editors = []; + }); + + it('graphs the time series queries by default, and lists them in the table tab', () => { + mocks.data = { queries: [TIME_SERIES_QUERY] }; + const { unmount } = render(); + expect(mocks.panels).toEqual(['TimeSeriesChart']); + expect(mocks.editors.at(-1)).toEqual({ queryTypes: ['TimeSeriesQuery'], queries: [TIME_SERIES_QUERY] }); + unmount(); + + mocks.panels = []; + mocks.data = { tab: 'table', queries: [TIME_SERIES_QUERY] }; + render(); + expect(mocks.panels).toEqual(['Table']); + }); + + it('keeps the queries of the other tabs when it switches tab or runs queries', () => { + mocks.data = { tab: 'traces', queries: [TIME_SERIES_QUERY], traceQueries: [traceQuery('SELECT 1')], spanId: 'a' }; + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Edit' })); + fireEvent.click(screen.getByRole('button', { name: 'Run Query' })); + fireEvent.click(screen.getByRole('tab', { name: 'Profiles' })); + + expect(mocks.setData).toHaveBeenNthCalledWith(1, { + tab: 'traces', + queries: [TIME_SERIES_QUERY], + traceQueries: [traceQuery('SELECT TraceId, Timestamp FROM otel_traces')], + // The selected span was the one of the previous trace. + spanId: undefined, + }); + expect(mocks.setData).toHaveBeenNthCalledWith(2, { ...mocks.data, tab: 'profiles' }); + expect(mocks.refresh).not.toHaveBeenCalled(); + }); + + it('refreshes the queries when they are run again unchanged', () => { + // A structurally equal copy, as when the state of the explorer is read back from the URL. + mocks.data = { tab: 'traces', traceQueries: [traceQuery('SELECT 1')] }; + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Run Query' })); + + expect(mocks.setData).toHaveBeenCalledWith({ tab: 'traces', traceQueries: [traceQuery('SELECT 1')] }); + expect(mocks.refresh).toHaveBeenCalledTimes(1); + }); + + it('displays the trace when the query is a trace ID, and shows the queries of a followed link', () => { + mocks.data = { tab: 'traces', traceQueries: [traceQuery('SELECT 1')] }; + const { rerender } = render(); + expect(mocks.panels).toEqual([]); + + // A link to a trace replaces the state of the explorer. + mocks.data = { tab: 'traces', traceQueries: [traceQuery('5b8efff798038103d269b633813fc60c')], spanId: 'abc' }; + rerender(); + + expect(mocks.panels).toEqual(['TracingGanttChart']); + expect(mocks.editors.at(-1)?.queries).toEqual([traceQuery('5b8efff798038103d269b633813fc60c')]); + }); + + it('draws the profile once a query is written', () => { + mocks.data = { tab: 'profiles', profileQueries: [profileQuery('')] }; + const { rerender } = render(); + expect(mocks.panels).toEqual([]); + + mocks.data = { tab: 'profiles', profileQueries: [profileQuery('SELECT FunctionNames AS stack FROM p')] }; + rerender(); + expect(mocks.panels).toEqual(['FlameChart']); + }); +}); + +describe('getTableTransforms', () => { + it('pivots the value columns of a query whose rows have a single label column', () => { + expect( + getTableTransforms([ + { __name__: 'spans', service: 'api' }, + { __name__: 'errors', service: 'api' }, + ]), + ).toEqual([{ kind: 'PivotByLabel', spec: { columnLabel: '__name__', rowField: 'service' } }]); + }); + + it('leaves the other results as they are', () => { + // A single value column. + expect(getTableTransforms([{ service: 'api' }, { service: 'web' }])).toEqual([]); + // Rows identified by several columns can not be pivoted. + expect(getTableTransforms([{ __name__: 'spans', service: 'api', kind: 'Server' }])).toEqual([]); + expect(getTableTransforms([{ __name__: 'spans' }, undefined])).toEqual([]); + }); +}); + +describe('trace links', () => { + const searchQuery = traceQuery('SELECT TraceId, Timestamp FROM otel_traces', { + datasource: { kind: 'ClickHouseDatasource', name: 'traces' }, + table: 'otel.otel_traces', + limit: 50, + }); + + it('opens a trace in the explorer, where the search found it', () => { + const link = linkToTrace(searchQuery, 'America/New_York'); + + expect(parseLink(link)).toEqual({ + explorer: 'ClickHouse-ClickHouseExplorer', + data: { + tab: 'traces', + traceQueries: [ + traceQuery('${traceId}', { + datasource: { kind: 'ClickHouseDatasource', name: 'traces' }, + table: 'otel.otel_traces', + }), + ], + }, + tz: 'America/New_York', + }); + // The panels replace the variables of the link: they are not encoded. + expect(link).toContain('${traceId}'); + expect(link).not.toContain('%24%7B'); + }); + + it('opens a span of a trace, with the default datasource and table', () => { + const link = linkToSpan(traceQuery('abcd'), 'local'); + + expect(parseLink(link).data).toEqual({ + tab: 'traces', + traceQueries: [traceQuery('${traceId}')], + spanId: '${spanId}', + }); + expect(link).toContain('${spanId}'); + }); +}); diff --git a/clickhouse/src/explore/ClickHouseExplorer.tsx b/clickhouse/src/explore/ClickHouseExplorer.tsx new file mode 100644 index 000000000..b04d04a0f --- /dev/null +++ b/clickhouse/src/explore/ClickHouseExplorer.tsx @@ -0,0 +1,376 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { Box, Stack, Tab, Tabs } from '@mui/material'; +import { ErrorAlert, ErrorBoundary, LoadingOverlay, NoDataOverlay, useTimeZone } from '@perses-dev/components'; +import { Panel } from '@perses-dev/dashboards'; +import { useExplorerManagerContext } from '@perses-dev/explore'; +import { + DataQueriesProvider, + MultiQueryEditor, + useDataQueries, + useSuggestedStepMs, + useTimeRange, +} from '@perses-dev/plugin-system'; +import type { Labels, QueryDefinition, QueryPluginType } from '@perses-dev/spec'; +import { isValidTraceId } from '@perses-dev/spec'; +import isEqual from 'lodash/isEqual'; +import type { ReactElement } from 'react'; +import { useMemo, useState } from 'react'; +import { useResizeObserver } from 'use-resize-observer'; + +import type { ClickHouseProfileQuerySpec } from '../queries/click-house-profile-query/click-house-profile-query-types'; +import { NAME_LABEL } from '../queries/click-house-time-series-query/time-series'; +import type { ClickHouseTraceQuerySpec } from '../queries/click-house-trace-query/click-house-trace-query-types'; +import type { ClickHouseExplorerQueryParams } from './links'; +import { linkToSpan, linkToTrace, TRACE_QUERY_KIND } from './links'; + +type ExplorerTab = 'graph' | 'table' | 'traces' | 'profiles'; + +const TABS: ReadonlyArray<{ value: ExplorerTab; label: string }> = [ + { value: 'graph', label: 'Graph' }, + { value: 'table', label: 'Table' }, + { value: 'traces', label: 'Traces' }, + { value: 'profiles', label: 'Profiles' }, +]; +const DEFAULT_TAB: ExplorerTab = 'graph'; + +const PANEL_HEIGHT = 700; +const PROFILE_PANEL_HEIGHT = 980; +const NO_QUERIES: QueryDefinition[] = []; + +// The explorer only runs the queries of this plugin: the other datasources have their own explorers. +const TIME_SERIES_QUERY_TYPES: QueryPluginType[] = ['TimeSeriesQuery']; +const TIME_SERIES_QUERY_PLUGINS = ['ClickHouseTimeSeriesQuery']; +const TRACE_QUERY_TYPES: QueryPluginType[] = ['TraceQuery']; +const TRACE_QUERY_PLUGINS = [TRACE_QUERY_KIND]; +const PROFILE_QUERY_TYPES: QueryPluginType[] = ['ProfileQuery']; +const PROFILE_QUERY_PLUGINS = ['ClickHouseProfileQuery']; + +const PANEL_OPTIONS = { hideHeader: true }; +const GRAPH_SPEC = { legend: { position: 'bottom', mode: 'list' } }; +// The time of the rows is the one of the query: only their values and labels are worth a column. +const TABLE_SPEC = { density: 'compact', columnSettings: [{ name: 'timestamp', hide: true }] }; +const FLAME_CHART_SPEC = { + palette: 'package-name', + showSettings: true, + showSeries: true, + showTable: true, + showFlameGraph: true, +}; + +function isExplorerTab(tab: string | undefined): tab is ExplorerTab { + return TABS.some(({ value }) => value === tab); +} + +interface QueryDrafts { + /** Queries being edited. */ + drafts: QueryDefinition[]; + setDrafts: (queries: QueryDefinition[]) => void; + /** Runs the edited queries: saves them in the state of the explorer. */ + run: () => void; +} + +/** + * useQueryDrafts keeps the queries of a tab while they are edited, apart from the ones that ran last, which are part + * of the state of the explorer. + */ +function useQueryDrafts(saved: QueryDefinition[], save: (queries: QueryDefinition[]) => void): QueryDrafts { + const [drafts, setDrafts] = useState(saved); + const { refresh } = useTimeRange(); + + // When the state of the explorer changes from elsewhere, e.g. a link opening a trace, show its queries. + const [lastSaved, setLastSaved] = useState(saved); + if (!isEqual(saved, lastSaved)) { + setLastSaved(saved); + setDrafts(saved); + } + + const run = (): void => { + setLastSaved(drafts); + save(drafts); + // Queries are cached by their content: running unchanged queries again needs a refresh. + if (isEqual(drafts, saved)) refresh(); + }; + + return { drafts, setDrafts, run }; +} + +function GraphPanel({ queries }: { queries: QueryDefinition[] }): ReactElement { + const { width, ref } = useResizeObserver(); + const suggestedStepMs = useSuggestedStepMs(width); + + return ( + + {/* The step of the queries follows the width of the graph: wait for it rather than run them twice. */} + {width === undefined ? null : ( + + + + )} + + ); +} + +/** + * getTableTransforms returns the transforms displaying the series of a query as the table the query returns. A + * query returning several value columns gives one series per column, named by the `__name__` label: when its rows + * are identified by a single label column, the series are pivoted back into one column per value. + */ +export function getTableTransforms(seriesLabels: Array): Array> { + const labelNames = new Set(); + let hasValueNames = false; + for (const labels of seriesLabels) { + for (const name of Object.keys(labels ?? {})) { + if (name === NAME_LABEL) { + hasValueNames = true; + } else { + labelNames.add(name); + } + } + } + const [rowField] = labelNames; + if (!hasValueNames || labelNames.size !== 1 || rowField === undefined) return []; + return [{ kind: 'PivotByLabel', spec: { columnLabel: NAME_LABEL, rowField } }]; +} + +function ResultTable({ queries }: { queries: QueryDefinition[] }): ReactElement { + const { queryResults } = useDataQueries('TimeSeriesQuery'); + // With several queries, the table suffixes their columns: they are left as they are. + const series = queryResults.length === 1 ? queryResults[0]?.data?.series : undefined; + const spec = useMemo( + () => ({ ...TABLE_SPEC, transforms: getTableTransforms((series ?? []).map((entry) => entry.labels)) }), + [series], + ); + + return ( + + ); +} + +function TablePanel({ queries }: { queries: QueryDefinition[] }): ReactElement { + return ( + + + + + + ); +} + +function TimeSeriesExplorer({ view }: { view: 'graph' | 'table' }): ReactElement { + const { data, setData } = useExplorerManagerContext(); + const queries = data.queries ?? NO_QUERIES; + const { drafts, setDrafts, run } = useQueryDrafts(queries, (next) => setData({ ...data, queries: next })); + + return ( + + + {view === 'table' ? : } + + ); +} + +function TraceSearchResults({ queries }: { queries: QueryDefinition[] }): ReactElement | null { + const { timeZone } = useTimeZone(); + const { isFetching, isPending, queryResults } = useDataQueries('TraceQuery'); + + if (queryResults.length === 0) { + return null; + } + if (isPending || isFetching) { + return ; + } + const failed = queryResults.find((result) => result.error); + if (failed) { + // Displayed by the error boundary of the explorer. + throw failed.error; + } + if (!queryResults.some((result) => (result.data?.searchResult ?? []).length > 0)) { + return ; + } + + const traceLink = linkToTrace(queries[0], timeZone); + return ( + + + + + + + ); +} + +function TracePanel({ queries, spanId }: { queries: QueryDefinition[]; spanId?: string }): ReactElement { + const { timeZone } = useTimeZone(); + const traceId = (queries[0]?.spec.plugin.spec as Partial | undefined)?.query; + + return ( + + ); +} + +function TracesExplorer(): ReactElement { + const { data, setData } = useExplorerManagerContext(); + const queries = data.traceQueries ?? NO_QUERIES; + const { drafts, setDrafts, run } = useQueryDrafts(queries, (next) => + // The selected span belongs to the trace that was displayed. + setData({ ...data, traceQueries: next, spanId: undefined }), + ); + const firstQuery = (queries[0]?.spec.plugin.spec as Partial | undefined)?.query; + // As for the trace query: a trace ID displays the trace, anything else is a search. + const isSingleTrace = isValidTraceId(firstQuery?.trim() ?? ''); + + return ( + + + + + + {isSingleTrace ? ( + + ) : ( + + )} + + + + + ); +} + +function ProfilesExplorer(): ReactElement { + const { data, setData } = useExplorerManagerContext(); + const queries = data.profileQueries ?? NO_QUERIES; + const { drafts, setDrafts, run } = useQueryDrafts(queries, (next) => setData({ ...data, profileQueries: next })); + // The flame chart has nothing to draw before a query is written. + const hasQuery = queries.some((query) => + (query.spec.plugin.spec as Partial | undefined)?.query?.trim(), + ); + + return ( + + + {hasQuery ? ( + + + + + + ) : null} + + ); +} + +function ExplorerTabContent({ tab }: { tab: ExplorerTab }): ReactElement { + switch (tab) { + case 'traces': + return ; + case 'profiles': + return ; + default: + // The graph and the table share their queries: switching between them keeps the editor as it is. + return ; + } +} + +/** + * ClickHouseExplorer runs ad hoc ClickHouse queries: time series as a graph or a table, trace searches and traces, + * and profiles. Logs are explored with the log explorer, which runs the log queries of every datasource. + */ +export function ClickHouseExplorer(): ReactElement { + const { data, setData } = useExplorerManagerContext(); + const tab = isExplorerTab(data.tab) ? data.tab : DEFAULT_TAB; + + return ( + + setData({ ...data, tab: next })} + variant="scrollable" + sx={{ borderBottom: 1, borderColor: 'divider' }} + > + {TABS.map(({ value, label }) => ( + + ))} + + + + ); +} diff --git a/clickhouse/src/explore/index.ts b/clickhouse/src/explore/index.ts new file mode 100644 index 000000000..6832c747b --- /dev/null +++ b/clickhouse/src/explore/index.ts @@ -0,0 +1,15 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export * from './ClickHouseExplorer'; +export * from './links'; diff --git a/clickhouse/src/explore/links.ts b/clickhouse/src/explore/links.ts new file mode 100644 index 000000000..0beb3a95f --- /dev/null +++ b/clickhouse/src/explore/links.ts @@ -0,0 +1,69 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { QueryDefinition } from '@perses-dev/spec'; + +import type { ClickHouseTraceQuerySpec } from '../queries/click-house-trace-query/click-house-trace-query-types'; + +/** Identifier of the ClickHouse explorer among the explorers of Perses: `-`. */ +export const CLICKHOUSE_EXPLORER_KEY = 'ClickHouse-ClickHouseExplorer'; + +export const TRACE_QUERY_KIND = 'ClickHouseTraceQuery'; + +/** State of the ClickHouse explorer, kept in the URL of the page. */ +export interface ClickHouseExplorerQueryParams { + tab?: string; + /** Time series queries of the graph and of the table. */ + queries?: QueryDefinition[]; + traceQueries?: QueryDefinition[]; + profileQueries?: QueryDefinition[]; + /** Span to select in the trace. */ + spanId?: string; +} + +function buildTraceLink(searchQuery: QueryDefinition | undefined, timeZone: string, spanId?: string): string { + // The trace is read where it was found: with the datasource and the table of the search query. + const { datasource, table } = (searchQuery?.spec.plugin.spec ?? {}) as Partial; + const data: ClickHouseExplorerQueryParams = { + tab: 'traces', + traceQueries: [ + { + kind: 'TraceQuery', + spec: { + plugin: { + kind: TRACE_QUERY_KIND, + spec: { ...(datasource !== undefined && { datasource }), ...(table && { table }), query: '${traceId}' }, + }, + }, + }, + ], + ...(spanId !== undefined && { spanId }), + }; + const params = new URLSearchParams({ + explorer: CLICKHOUSE_EXPLORER_KEY, + data: JSON.stringify(data), + tz: timeZone, + }); + // The panels replace the ${...} variables of a link: keep them readable in the encoded URL. + return `/explore?${params}`.replace(/%24%7B(\w+)%7D/g, '${$1}'); +} + +/** linkToTrace returns the link template opening a trace in the explorer. Panels replace `${traceId}`. */ +export function linkToTrace(searchQuery: QueryDefinition | undefined, timeZone: string): string { + return buildTraceLink(searchQuery, timeZone); +} + +/** linkToSpan returns the link template opening a span of a trace. Panels replace `${traceId}` and `${spanId}`. */ +export function linkToSpan(searchQuery: QueryDefinition | undefined, timeZone: string): string { + return buildTraceLink(searchQuery, timeZone, '${spanId}'); +} diff --git a/clickhouse/src/index.ts b/clickhouse/src/index.ts index 215d904df..82aefc815 100644 --- a/clickhouse/src/index.ts +++ b/clickhouse/src/index.ts @@ -14,3 +14,6 @@ export { getPluginModule } from './getPluginModule'; export * from './queries'; export * from './datasources'; +export * from './variables'; +export * from './annotations'; +export * from './explore'; diff --git a/clickhouse/src/model/click-house-client.test.ts b/clickhouse/src/model/click-house-client.test.ts index 65ac2de3a..693419939 100644 --- a/clickhouse/src/model/click-house-client.test.ts +++ b/clickhouse/src/model/click-house-client.test.ts @@ -11,50 +11,336 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { formatClickHouseDateTime, query, replaceTimeRangePlaceholders } from './click-house-client'; +import { ClickHouseError, createClickHouseClient, MAX_ROWS, READ_ONLY_TTL_MS } from './click-house-client'; -describe('ClickHouse client', () => { - afterEach(() => { - vi.restoreAllMocks(); +const FORMAT = 'JSONCompactEachRowWithNamesAndTypes'; + +function result(lines: unknown[][], headers: Record = {}): Response { + return new Response(lines.map((line) => JSON.stringify(line)).join('\n') + '\n', { + status: 200, + headers: { 'X-ClickHouse-Format': FORMAT, ...headers }, }); +} + +function failure(message: string, status = 500): Response { + return new Response(message, { status }); +} + +type FetchMock = ReturnType>; + +let datasources = 0; - it('should replace time range placeholders', () => { - expect( - replaceTimeRangePlaceholders( - "SELECT * FROM logs WHERE timestamp BETWEEN '{start}' AND '{end}'", - '2025-01-01 00:00:00', - '2025-01-02 00:00:00', +// The clients of a datasource share what they learn about its settings: each test queries its own datasource. +function datasourceUrl(): string { + datasources += 1; + return `http://clickhouse-${datasources}:8123`; +} + +function refusedSetting(setting: string): Response { + return failure(`Code: 164. DB::Exception: Cannot modify '${setting}' setting in readonly mode. (READONLY)`); +} + +function calledUrl(fetchMock: FetchMock, call = 0): URL { + return new URL(String(fetchMock.mock.calls[call]?.[0])); +} + +describe('createClickHouseClient', () => { + it('reads the columns, their types and the rows of a result', async () => { + const fetchMock = vi.fn(async () => + result( + [ + ['time', 'value'], + ["DateTime('UTC')", 'UInt64'], + ['2026-01-01T00:00:00Z', '42'], + ], + { + 'X-ClickHouse-Timezone': 'Europe/Paris', + 'X-ClickHouse-Summary': '{"read_rows":"10","read_bytes":"80","elapsed_ns":"2500000"}', + }, ), - ).toEqual("SELECT * FROM logs WHERE timestamp BETWEEN '2025-01-01 00:00:00' AND '2025-01-02 00:00:00'"); + ); + const client = createClickHouseClient({ datasourceUrl: '/proxy/globaldatasources/ch', fetch: fetchMock }); + + await expect(client.query({ query: 'SELECT 1' })).resolves.toEqual({ + columns: [ + { name: 'time', type: "DateTime('UTC')" }, + { name: 'value', type: 'UInt64' }, + ], + rows: [['2026-01-01T00:00:00Z', '42']], + timeZone: 'Europe/Paris', + truncated: false, + statistics: { rowsRead: 10, bytesRead: 80, elapsedMs: 2.5 }, + }); + // A relative datasource URL is the one of the Perses proxy, on the origin of the page. + expect(calledUrl(fetchMock).origin).toBe(window.location.origin); + expect(calledUrl(fetchMock).pathname).toBe('/proxy/globaldatasources/ch'); + }); + + it('sends queries with POST, as read-only and with the settings making results unambiguous', async () => { + const fetchMock = vi.fn(async () => result([['a'], ['UInt8']])); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), database: 'otel', fetch: fetchMock }); + + await client.query({ query: 'SELECT 1 AS a' }); + + const init = fetchMock.mock.calls[0]?.[1]; + expect(init?.method).toBe('POST'); + expect(init?.body).toBe('SELECT 1 AS a'); + expect(Object.fromEntries(calledUrl(fetchMock).searchParams)).toMatchObject({ + default_format: FORMAT, + database: 'otel', + readonly: '2', + date_time_output_format: 'iso', + output_format_json_quote_64bit_integers: '1', + max_result_rows: String(MAX_ROWS + 1), + result_overflow_mode: 'break', + wait_end_of_query: '1', + }); + expect(calledUrl(fetchMock).searchParams.has('query')).toBe(false); }); - it('should format time range dates for ClickHouse SQL literals', () => { - expect(formatClickHouseDateTime(new Date('2025-01-01T00:00:00.000Z'))).toBe('2025-01-01 00:00:00'); + it('sends queries in the URL with GET, which ClickHouse runs read-only', async () => { + const fetchMock = vi.fn(async () => result([['a'], ['UInt8']])); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), method: 'GET', fetch: fetchMock }); + + await client.query({ query: 'SELECT 1 AS a' }); + + const init = fetchMock.mock.calls[0]?.[1]; + expect(init?.method).toBe('GET'); + expect(init?.body).toBeUndefined(); + expect(calledUrl(fetchMock).searchParams.get('query')).toBe('SELECT 1 AS a'); + expect(calledUrl(fetchMock).searchParams.has('readonly')).toBe(false); }); - it('should send interpolated query to ClickHouse', async () => { - const fetchMock = vi.fn<(url: string, init?: RequestInit) => Promise>>(async () => ({ - ok: true, - json: vi.fn(async () => ({ data: [] })), - })); - global.fetch = fetchMock as unknown as typeof fetch; + it('stops sending settings to a user that is not allowed to change any', async () => { + const url = datasourceUrl(); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(refusedSetting('date_time_output_format')) + // ClickHouse runs the queries of this user as read-only by itself: they need no guard. + .mockResolvedValueOnce(result([["getSetting('readonly')"], ['UInt64'], [1]])) + .mockImplementation(async () => result([['a'], ['UInt8'], [1]])); + + const client = createClickHouseClient({ datasourceUrl: url, fetch: fetchMock }); + await expect(client.query({ query: 'SELECT 1 AS a' })).resolves.toMatchObject({ rows: [[1]] }); + // A client is created for each query: the next ones of the datasource go without settings at once. + await createClickHouseClient({ datasourceUrl: url, fetch: fetchMock }).query({ query: 'SELECT 1 AS a' }); - await query( - { - query: "SELECT * FROM logs WHERE timestamp BETWEEN '{start}' AND '{end}'", - start: '2025-01-01 00:00:00', - end: '2025-01-02 00:00:00', - }, - { - datasourceUrl: 'http://clickhouse.example.com', - }, + expect(fetchMock).toHaveBeenCalledTimes(4); + for (const call of [2, 3]) { + const params = calledUrl(fetchMock, call).searchParams; + expect(params.has('readonly')).toBe(false); + expect(params.has('date_time_output_format')).toBe(false); + expect(params.get('default_format')).toBe(FORMAT); + } + }); + + it('keeps the guard of a query whose error only reads like a refused setting', async () => { + const statement = + "SELECT throwIf(1, 'Code: 164. DB::Exception: Cannot modify ''readonly'' setting in readonly mode')"; + const fetchMock = vi.fn(async (_url, init) => + init?.body === statement + ? failure( + "Code: 395. DB::Exception: Code: 164. DB::Exception: Cannot modify 'readonly' setting in readonly mode: while executing 'FUNCTION throwIf'. (FUNCTION_THROW_IF_VALUE_IS_NON_ZERO)", + ) + : result([['a'], ['UInt8'], [1]]), + ); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + await expect(client.query({ query: statement })).rejects.toMatchObject({ code: 395 }); + await client.query({ query: 'SELECT 1' }); + + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(calledUrl(fetchMock, 1).searchParams.get('readonly')).toBe('2'); + }); + + it('keeps every setting when ClickHouse does not confirm that the user is read-only', async () => { + const fetchMock = vi.fn(async (_url, init) => + init?.body === "SELECT getSetting('readonly')" + ? result([["getSetting('readonly')"], ['UInt64'], ['0']]) + : refusedSetting('date_time_output_format'), ); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + await expect(client.query({ query: 'SELECT 1' })).rejects.toMatchObject({ code: 164 }); + await expect(client.query({ query: 'SELECT 2' })).rejects.toMatchObject({ code: 164 }); + const guards = fetchMock.mock.calls + .filter(([, init]) => init?.body !== "SELECT getSetting('readonly')") + .map(([url]) => new URL(String(url)).searchParams.get('readonly')); + expect(guards).toEqual(['2', '2']); + }); + + it('sends the guard again to other credentials, and once the read-only probe is stale', async () => { + const url = datasourceUrl(); + const readOnlyUser = { Authorization: 'Basic cmVhZGVy' }; + const fetchMock = vi.fn(async (_url, init) => { + const params = new URL(String(_url)).searchParams; + const isReadOnlyUser = JSON.stringify(init?.headers) === JSON.stringify(readOnlyUser); + if (init?.body === "SELECT getSetting('readonly')") { + return result([["getSetting('readonly')"], ['UInt64'], [isReadOnlyUser ? '2' : '0']]); + } + return isReadOnlyUser && params.has('readonly') ? refusedSetting('readonly') : result([['a'], ['UInt8'], [1]]); + }); + const now = vi.spyOn(Date, 'now').mockReturnValue(0); + const query = (headers?: Record): Promise => + createClickHouseClient({ datasourceUrl: url, fetch: fetchMock }).query({ query: 'SELECT 1' }, headers); + const sentGuards = (): Array => + fetchMock.mock.calls + .filter(([, init]) => init?.body === 'SELECT 1') + .map(([input]) => new URL(String(input)).searchParams.get('readonly')); + + try { + await query(readOnlyUser); + await query(readOnlyUser); + await query(); + now.mockReturnValue(READ_ONLY_TTL_MS); + await query(readOnlyUser); + } finally { + now.mockRestore(); + } + + expect(sentGuards()).toEqual(['2', null, null, '2', '2', null]); + }); + + it('never sends without its read-only guard a query that tries to lift it', async () => { + const statement = 'INSERT INTO t SETTINGS readonly = 0 VALUES (1)'; + const fetchMock = vi.fn(async (_url, init) => + init?.body === statement + ? refusedSetting('readonly') + : // ClickHouse lets this user write: the guard was refused because of the query. + result([["getSetting('readonly')"], ['UInt64'], ['0']]), + ); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + await expect(client.query({ query: statement })).rejects.toMatchObject({ code: 164 }); + await client.query({ query: 'SELECT 1' }); + + const guards = fetchMock.mock.calls + .filter(([, init]) => init?.body !== "SELECT getSetting('readonly')") + .map(([url, init]) => [init?.body, new URL(String(url)).searchParams.get('readonly')]); + expect(guards).toEqual([ + [statement, '2'], + ['SELECT 1', '2'], + ]); + }); + + it('drops the row limit when a settings profile forbids it, and cuts the result itself', async () => { + const rows = Array.from({ length: MAX_ROWS + 5 }, (_unused, index) => [index]); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(failure('Code: 452. DB::Exception: Setting max_result_rows should not be changed.')) + .mockImplementation(async () => result([['n'], ['UInt32'], ...rows])); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + const response = await client.query({ query: 'SELECT number AS n FROM numbers(200000)' }); + + expect(response.rows).toHaveLength(MAX_ROWS); + expect(response.truncated).toBe(true); + const params = calledUrl(fetchMock, 1).searchParams; + expect(params.has('max_result_rows')).toBe(false); + // Without a row limit, the overflow mode would have nothing to apply to, and the result nothing to bound it. + expect(params.has('result_overflow_mode')).toBe(false); + expect(params.has('wait_end_of_query')).toBe(false); + expect(params.get('date_time_output_format')).toBe('iso'); + }); + + it('stops buffering the results when a settings profile forbids it', async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(failure('Code: 452. DB::Exception: Setting wait_end_of_query should not be changed.')) + .mockImplementation(async () => result([['a'], ['UInt8'], [1]])); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + await expect(client.query({ query: 'SELECT 1 AS a' })).resolves.toMatchObject({ rows: [[1]] }); + const params = calledUrl(fetchMock, 1).searchParams; + expect(params.has('wait_end_of_query')).toBe(false); + expect(params.get('max_result_rows')).toBe(String(MAX_ROWS + 1)); + expect(params.get('readonly')).toBe('2'); + }); + + it.each([ + [MAX_ROWS, false], + [MAX_ROWS + 1, true], + ])('tells whether a result of %i rows cut by ClickHouse is truncated', async (count, truncated) => { + const rows = Array.from({ length: count }, (_unused, index) => [index]); + const fetchMock = vi.fn(async () => result([['n'], ['UInt32'], ...rows])); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + const response = await client.query({ query: 'SELECT number AS n FROM numbers(200000)' }); + + expect(response.rows).toHaveLength(MAX_ROWS); + expect(response.truncated).toBe(truncated); + }); + + it('does not download the rest of a result that ClickHouse did not cut', async () => { + const lines = [['n'], ['UInt32'], ...Array.from({ length: 3 * MAX_ROWS }, (_unused, index) => [index])]; + const bytes = new TextEncoder().encode(lines.map((line) => JSON.stringify(line)).join('\n') + '\n'); + const chunkSize = 64 * 1024; + let read = 0; + let cancelled = false; + const fetchMock = vi.fn( + async () => + new Response( + new ReadableStream({ + pull(controller): void { + controller.enqueue(bytes.subarray(read, read + chunkSize)); + read += chunkSize; + if (read >= bytes.length) controller.close(); + }, + cancel(): void { + cancelled = true; + }, + }), + { status: 200, headers: { 'X-ClickHouse-Format': FORMAT } }, + ), + ); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + const response = await client.query({ query: 'SELECT number AS n FROM numbers(300000)' }); + + expect(response.rows).toHaveLength(MAX_ROWS); + expect(response.rows.at(-1)).toEqual([MAX_ROWS - 1]); + expect(response.truncated).toBe(true); + expect(cancelled).toBe(true); + expect(read).toBeLessThan(bytes.length / 2); + }); + + it('reports the error of ClickHouse with its code, without the version of the server', async () => { + const fetchMock = vi.fn(async () => + failure( + "Code: 60. DB::Exception: Unknown table expression identifier 'nope'. (UNKNOWN_TABLE) (version 26.9.1.1 (official build))\n", + 404, + ), + ); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + const error = await client.query({ query: 'SELECT * FROM nope' }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ClickHouseError); + expect(error).toMatchObject({ + code: 60, + message: + "ClickHouse query failed: Code: 60. DB::Exception: Unknown table expression identifier 'nope'. (UNKNOWN_TABLE)", + }); + // A failed query is not sent again. expect(fetchMock).toHaveBeenCalledTimes(1); - const [calledUrl] = fetchMock.mock.calls[0]!; - const url = new URL(calledUrl); - expect(url.searchParams.get('query')).toBe( - "SELECT * FROM logs WHERE timestamp BETWEEN '2025-01-01 00:00:00' AND '2025-01-02 00:00:00' FORMAT JSON", + }); + + it('keeps the error of ClickHouse when the fetch of Perses throws it', async () => { + const fetchMock = vi.fn(async () => { + throw new Error('Code: 62. DB::Exception: Syntax error: failed at position 1 (SELEC). (SYNTAX_ERROR)'); + }); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + await expect(client.query({ query: 'SELEC 1' })).rejects.toMatchObject({ code: 62 }); + }); + + it('asks to remove a FORMAT clause, which changes the format of the result', async () => { + const fetchMock = vi.fn( + async () => new Response('{"data": []}', { status: 200, headers: { 'X-ClickHouse-Format': 'JSON' } }), ); + const client = createClickHouseClient({ datasourceUrl: datasourceUrl(), fetch: fetchMock }); + + await expect(client.query({ query: 'SELECT 1 FORMAT JSON' })).rejects.toThrow(/Remove the FORMAT clause/); }); }); diff --git a/clickhouse/src/model/click-house-client.ts b/clickhouse/src/model/click-house-client.ts index 334dbcdab..4414cd56e 100644 --- a/clickhouse/src/model/click-house-client.ts +++ b/clickhouse/src/model/click-house-client.ts @@ -13,93 +13,393 @@ import type { FetchFn, RequestHeaders } from '@perses-dev/client'; +import type { ClickHouseColumn } from './click-house-types'; +import { buildUrl } from './url'; + +/** + * Maximum number of rows read from a result. ClickHouse stops the query once it has produced them, when it accepts + * the settings asking for it. The rest of a longer result is not downloaded. + */ +export const MAX_ROWS = 100_000; +// The names and the types of the columns come before the rows. +const HEADER_LINES = 2; + +/** + * Format requested from ClickHouse: the column names, their types, then one compact JSON array per row. + * Unlike `JSON`, its responses are not `application/json`, so the message of a failed query stays readable + * for the Perses fetch, which tries to decode every JSON error body. + */ +export const RESPONSE_FORMAT = 'JSONCompactEachRowWithNamesAndTypes'; + +// Errors of ClickHouse refusing a setting, matched on the first exception of a message only: the text of a query, +// e.g. the message of a `throwIf`, comes after it. +const READONLY_SETTING_ERROR = /^Code: 164\. DB::Exception: Cannot modify '(\w+)' setting in readonly mode/; +const SETTING_CONSTRAINT_ERROR = /^Code: 452\. DB::Exception: Setting (\w+) /; +const EXCEPTION = /Code: (\d+)\. DB::Exception: [^\n]*/; +const SERVER_VERSION = /\s*\(version [^)]*\(official build\)\)\s*$/; +const MAX_ERROR_LENGTH = 1000; + export interface ClickHouseQueryParams { + /** SQL statement to run, without a FORMAT clause. */ query: string; - start?: string; - end?: string; + /** Database the unqualified table names are read from. Defaults to the one of the datasource. */ database?: string; + signal?: AbortSignal; } -export interface ClickHouseQueryOptions { - datasourceUrl: string; - headers?: RequestHeaders; - fetch?: FetchFn; +export interface ClickHouseStatistics { + rowsRead?: number; + bytesRead?: number; + elapsedMs?: number; } export interface ClickHouseQueryResponse { - status: 'success' | 'error'; - data: unknown; + columns: ClickHouseColumn[]; + /** One array per row, with the values in the order of the columns. */ + rows: unknown[][]; + /** Time zone of the server: the zone of the date/times that do not carry one. */ + timeZone?: string; + /** True when the result was cut at MAX_ROWS. */ + truncated: boolean; + statistics?: ClickHouseStatistics; +} + +export interface ClickHouseClientOptions { + datasourceUrl: string; + /** Database the unqualified table names are read from. */ + database?: string; + headers?: RequestHeaders; + fetch?: FetchFn; + /** HTTP method of the queries. ClickHouse only runs read queries sent with GET, but limits their size. */ + method?: 'GET' | 'POST'; + /** Asks ClickHouse for CORS headers. Needed when the browser calls it directly, without the Perses proxy. */ + cors?: boolean; } export interface ClickHouseClient { - query: (params: { start: string; end: string; query: string }) => Promise; + query: (params: ClickHouseQueryParams, headers?: RequestHeaders) => Promise; + /** Reports whether ClickHouse answers. It never throws. */ + healthCheck: () => Promise; } -export function replaceTimeRangePlaceholders(query: string, start?: string, end?: string): string { - return query.replaceAll('{start}', start ?? '{start}').replaceAll('{end}', end ?? '{end}'); +/** Error returned by ClickHouse, with its error code when the message carries one. */ +export class ClickHouseError extends Error { + readonly code?: number; + + constructor(message: string, options?: { code?: number; cause?: unknown }) { + super(message, options?.cause === undefined ? undefined : { cause: options.cause }); + this.name = 'ClickHouseError'; + this.code = options?.code; + } } -export function formatClickHouseDateTime(date: Date): string { - return date - .toISOString() - .replace('T', ' ') - .replace(/\.\d{3}Z$/, ''); +type Setting = readonly [name: string, value: string]; + +const ROW_LIMIT = 'max_result_rows'; +// Buffers a bounded result, so that a query failing halfway answers with an error status instead of a cut result. +const WAIT_END_OF_QUERY = 'wait_end_of_query'; + +// Settings sent along with a query. A user restricted with `readonly = 1` can not change any, and a settings profile +// can forbid some: the client then stops sending the ones ClickHouse rejects. +const QUERY_SETTINGS: readonly Setting[] = [ + ['date_time_output_format', 'iso'], + ['output_format_json_quote_64bit_integers', '1'], + // One row more than the client reads: a result cut by ClickHouse always tells that it was cut. + [ROW_LIMIT, String(MAX_ROWS + 1)], + ['result_overflow_mode', 'break'], + [WAIT_END_OF_QUERY, '1'], + ['cancel_http_readonly_queries_on_client_close', '1'], + ['enable_http_compression', '1'], +]; +// Without `result_overflow_mode = break`, a result over `max_result_rows` is an error instead of being cut. Without a +// row limit, ClickHouse would buffer all of an unbounded result: it is cut by not reading its end instead. +const ROW_LIMIT_SETTINGS = [ROW_LIMIT, 'result_overflow_mode']; +// Setting keeping a query sent with POST from writing: it only lets it read data and change settings. +const GUARD = 'readonly'; +const READ_ONLY_PROBE = "SELECT getSetting('readonly')"; +/** + * How long the answer of ClickHouse to the read-only probe is trusted. The user behind a datasource can change, e.g. + * when the secret of its proxy is updated: the guard is sent again from time to time, to learn it. + */ +export const READ_ONLY_TTL_MS = 5 * 60 * 1000; + +/** What the queries of a datasource taught about the settings its ClickHouse user may change. */ +interface SettingsState { + /** Settings ClickHouse refused to change, because of a settings profile. */ + rejected: Set; + /** + * Read-only level of the user, when ClickHouse confirmed that it runs the queries of the user as read-only by + * itself, and when it did. Only then do queries go without the guard (`readonly >= 1`), and without any setting + * (`readonly = 1`). + */ + readOnly?: { level: number; confirmedAt: number }; + /** Pending read-only probe, shared by the queries waiting for its answer. */ + readOnlyProbe?: Promise; } -export async function query( - params: ClickHouseQueryParams, - queryOptions: ClickHouseQueryOptions, -): Promise { - const { datasourceUrl, headers, fetch: customFetch } = queryOptions; +// A client is created for each query: what the first ones learn is kept for the next ones of the same datasource and +// credentials, which would otherwise all be refused once before being sent again. +const settingsStates = new Map(); - const url = urlBuilder(datasourceUrl); - if (!params.query) { - throw new Error('No query provided in params'); +function getSettingsState(key: string): SettingsState { + let state = settingsStates.get(key); + if (!state) { + state = { rejected: new Set() }; + settingsStates.set(key, state); } + return state; +} - let finalQuery = replaceTimeRangePlaceholders(params.query.trim(), params.start, params.end); - if (!finalQuery.toUpperCase().includes('FORMAT')) { - finalQuery += ' FORMAT JSON'; - } +// Read-only level ClickHouse enforces by itself on the queries of the user, as long as it is trusted. +function readOnlyLevel(state: SettingsState): number { + const { readOnly } = state; + if (readOnly === undefined || Date.now() - readOnly.confirmedAt >= READ_ONLY_TTL_MS) return 0; + return readOnly.level; +} + +function errorText(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function toClickHouseError(message: string, cause?: unknown): ClickHouseError { + const exception = EXCEPTION.exec(message); + const text = (exception?.[0] ?? message).replace(SERVER_VERSION, '').trim(); + const shortened = text.length > MAX_ERROR_LENGTH ? `${text.slice(0, MAX_ERROR_LENGTH)}…` : text; + return new ClickHouseError(`ClickHouse query failed: ${shortened || 'unknown error'}`, { + code: exception ? Number(exception[1]) : undefined, + cause, + }); +} - url.searchParams.set('query', finalQuery); - url.searchParams.set('database', params.database || 'default'); +function parseStatistics(summary: string | null): ClickHouseStatistics | undefined { + if (!summary) return undefined; + try { + const values: Record = JSON.parse(summary); + const read = (key: string): number | undefined => { + const value = Number(values[key]); + return Number.isFinite(value) ? value : undefined; + }; + const elapsedNs = read('elapsed_ns'); + return { + rowsRead: read('read_rows'), + bytesRead: read('read_bytes'), + elapsedMs: elapsedNs === undefined ? undefined : elapsedNs / 1_000_000, + }; + } catch { + return undefined; + } +} - const init = { - method: 'GET', - headers: { - ...headers, - }, +// Reads the first lines of a response. The rest of a longer one is not downloaded: a result is only bounded by +// ClickHouse when it accepts the row limit of the client. +async function readLines(response: Response, maxLines: number): Promise<{ text: string; truncated: boolean }> { + const reader = response.body?.getReader(); + if (!reader) return { text: await response.text(), truncated: false }; + const decoder = new TextDecoder(); + let text = ''; + let lines = 0; + let end = 0; + // The chunks of a stream are read one after the other. + const readChunk = async (): Promise<{ text: string; truncated: boolean }> => { + const { done, value } = await reader.read(); + if (done) return { text: text + decoder.decode(), truncated: false }; + const chunk = decoder.decode(value, { stream: true }); + for ( + let newline = chunk.indexOf('\n'); + newline !== -1 && lines <= maxLines; + newline = chunk.indexOf('\n', newline + 1) + ) { + lines++; + if (lines === maxLines) end = text.length + newline; + } + text += chunk; + if (lines <= maxLines) return readChunk(); + // Closing the response stops ClickHouse from sending the rest. + await reader.cancel().catch(() => undefined); + return { text: text.slice(0, end), truncated: true }; }; + return readChunk(); +} +function parseBody(body: string): { columns: ClickHouseColumn[]; rows: unknown[][] } { + let lines: unknown; try { - const doFetch = customFetch ?? fetch; - const response = await doFetch(url.toString(), init); + // One JSON array per line: a line break never appears inside a value, where it is escaped. + lines = JSON.parse(`[${body.trimEnd().replaceAll('\n', ',')}]`); + } catch (error) { + if (EXCEPTION.test(body)) throw toClickHouseError(body, error); + throw new ClickHouseError( + `ClickHouse did not answer in the ${RESPONSE_FORMAT} format. Remove the FORMAT clause of the query, if any.`, + { cause: error }, + ); + } + if (!Array.isArray(lines) || !lines.every(Array.isArray)) { + throw new ClickHouseError(`ClickHouse did not answer in the ${RESPONSE_FORMAT} format.`); + } + const [names = [], types = [], ...rows] = lines as unknown[][]; + return { + columns: names.map((name, index) => ({ name: String(name), type: String(types[index] ?? '') })), + rows, + }; +} +/** + * createClickHouseClient returns a client of the ClickHouse HTTP interface. + * + * Queries are sent with `readonly = 2` (POST) or as GET requests, which ClickHouse runs read-only, so that a query + * can not write. A few settings make the results unambiguous and bounded: ISO date/times, quoted 64-bit integers, a + * row limit. When the ClickHouse user is not allowed to change settings, the client stops sending them and reads + * the results as they come: date/times are then in the time zone of the server, which the response tells. + */ +export function createClickHouseClient(options: ClickHouseClientOptions): ClickHouseClient { + const { datasourceUrl, database, headers: defaultHeaders, fetch: customFetch, method = 'POST', cors } = options; + const settings: Setting[] = [ + // A GET request is read-only by itself. A POST one is not: forbid everything but reads and settings. + ...(method === 'POST' ? ([[GUARD, '2']] as const) : []), + ...QUERY_SETTINGS, + ...(cors ? ([['add_http_cors_header', '1']] as const) : []), + ]; + // What ClickHouse taught about the user sending the queries: the one of their headers. + function stateOf(headers: RequestHeaders | undefined): SettingsState { + return getSettingsState(`${method} ${datasourceUrl} ${JSON.stringify(headers ?? {})}`); + } + + // The settings to send with a query, given what ClickHouse refused so far. + function allowedSettings(state: SettingsState): Setting[] { + const level = readOnlyLevel(state); + // A user that can not change any setting (`readonly = 1`). + if (level === 1) return []; + return settings.filter(([name]) => !state.rejected.has(name) && !(name === GUARD && level >= 1)); + } + + async function send( + params: ClickHouseQueryParams, + headers: RequestHeaders | undefined, + sent: Setting[], + ): Promise { + const url = buildUrl(datasourceUrl); + const search = url.searchParams; + search.set('default_format', RESPONSE_FORMAT); + const queryDatabase = params.database ?? database; + if (queryDatabase) search.set('database', queryDatabase); + for (const [name, value] of sent) search.set(name, value); + if (method === 'GET') search.set('query', params.query); + + const response = await (customFetch ?? fetch)(url.toString(), { + method, + headers, + body: method === 'POST' ? params.query : undefined, + signal: params.signal, + }); if (!response.ok) { - const errorText = await response.text(); - console.error('ClickHouse error response:', errorText); - return { - status: 'error', - data: [], - }; + // Only reached with a fetch that does not throw on error statuses, unlike the Perses one. + throw new Error((await response.text()) || `${response.status} ${response.statusText}`); } + return response; + } - const body = await response.json(); + // Asks ClickHouse the read-only level it runs the queries of the user with by itself. Only a read-only user can + // send queries without the guard: it is also refused to a query that tries to lift it, or to a query whose error + // reads like a refused setting, which must not be sent again without it. + function probeReadOnly(state: SettingsState, headers: RequestHeaders | undefined): Promise { + // Asked once for all the queries waiting for the answer, and without their signals: aborting one of them must + // not fail the other ones. + state.readOnlyProbe ??= send({ query: READ_ONLY_PROBE }, headers, []) + .then(async (response) => { + const level = Number(parseBody(await response.text()).rows[0]?.[0]); + if (!Number.isInteger(level) || level < 1) return 0; + state.readOnly = { level, confirmedAt: Date.now() }; + return level; + }) + .catch(() => 0) + .finally(() => { + state.readOnlyProbe = undefined; + }); + return state.readOnlyProbe; + } + // Stops sending the setting ClickHouse refused to a query, if its error is about one of the settings sent with + // it. It returns false when sending the query again would not help. + async function dropRefusedSetting( + state: SettingsState, + message: string, + sent: Setting[], + headers: RequestHeaders | undefined, + ): Promise { + const wasSent = (name: string | undefined): name is string => + name !== undefined && sent.some(([setting]) => setting === name); + + const exception = EXCEPTION.exec(message)?.[0] ?? ''; + const readOnly = READONLY_SETTING_ERROR.exec(exception)?.[1]; + const constrained = SETTING_CONSTRAINT_ERROR.exec(exception)?.[1]; + const refused = wasSent(readOnly) ? readOnly : constrained; + if (!wasSent(refused)) return false; + + if (refused === GUARD || refused === readOnly) { + // The query is sent with fewer settings only when ClickHouse confirms that it keeps it from writing. + const level = await probeReadOnly(state, headers); + // A setting other than the guard is only refused to a user that can not change any (`readonly = 1`). + return refused === GUARD ? level >= 1 : level === 1; + } + for (const name of ROW_LIMIT_SETTINGS.includes(refused) ? [...ROW_LIMIT_SETTINGS, WAIT_END_OF_QUERY] : [refused]) { + state.rejected.add(name); + } + return true; + } + + // Sends the query again each time ClickHouse refuses a setting. Settings are checked before the query runs, so a + // refused request did nothing, and each attempt sends at least one setting less: the retries are bounded. + async function sendWithAllowedSettings( + params: ClickHouseQueryParams, + headers: RequestHeaders | undefined, + ): Promise { + const state = stateOf(headers); + const sent = allowedSettings(state); + try { + return await send(params, headers, sent); + } catch (error) { + if (params.signal?.aborted) throw error; + const message = errorText(error); + if (await dropRefusedSetting(state, message, sent, headers)) { + // Each attempt must send fewer settings, or the query would be refused forever. + if (allowedSettings(state).length < sent.length) return sendWithAllowedSettings(params, headers); + } + throw toClickHouseError(message, error); + } + } + + async function query(params: ClickHouseQueryParams, headers?: RequestHeaders): Promise { + if (!params.query.trim()) { + throw new Error('No query provided in params'); + } + const response = await sendWithAllowedSettings(params, headers ?? defaultHeaders); + const format = response.headers.get('X-ClickHouse-Format'); + if (format && format !== RESPONSE_FORMAT) { + await response.body?.cancel().catch(() => undefined); + throw new ClickHouseError( + `ClickHouse answered in the ${format} format. Remove the FORMAT clause of the query: results are read as ${RESPONSE_FORMAT}.`, + ); + } + const { text, truncated } = await readLines(response, HEADER_LINES + MAX_ROWS); return { - status: 'success', - data: body.data || body, + ...parseBody(text), + timeZone: response.headers.get('X-ClickHouse-Timezone') ?? undefined, + truncated, + statistics: parseStatistics(response.headers.get('X-ClickHouse-Summary')), }; - } catch (e) { - throw new Error(`ClickHouse query failed: ${e}`, { cause: e }); } -} -function urlBuilder(datasourceUrl: string): URL { - if (datasourceUrl.startsWith('http://') || datasourceUrl.startsWith('https://')) { - return new URL(datasourceUrl); + async function healthCheck(): Promise { + try { + const response = await (customFetch ?? fetch)(buildUrl(datasourceUrl, '/ping').toString(), { + method: 'GET', + headers: defaultHeaders, + }); + return response.ok; + } catch { + return false; + } } - // if relative path (e.g. proxy url), resolve against window.location.origin - return new URL(datasourceUrl, window.location.origin); + + return { query, healthCheck }; } diff --git a/clickhouse/src/model/click-house-selectors.ts b/clickhouse/src/model/click-house-selectors.ts new file mode 100644 index 000000000..ce013fcf6 --- /dev/null +++ b/clickhouse/src/model/click-house-selectors.ts @@ -0,0 +1,34 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { DatasourceSelectValue } from '@perses-dev/plugin-system'; +import { isVariableDatasource } from '@perses-dev/plugin-system'; +import type { DatasourceSelector } from '@perses-dev/spec'; + +export const CLICKHOUSE_DATASOURCE_KIND = 'ClickHouseDatasource' as const; + +export interface ClickHouseDatasourceSelector extends DatasourceSelector { + kind: typeof CLICKHOUSE_DATASOURCE_KIND; +} + +/** Selects the default ClickHouse datasource. */ +export const DEFAULT_CLICKHOUSE: ClickHouseDatasourceSelector = { kind: CLICKHOUSE_DATASOURCE_KIND }; + +/** Datasource of a ClickHouse query: a ClickHouse datasource, or a variable holding the name of one. */ +export type ClickHouseDatasourceSelectValue = DatasourceSelectValue; + +export function isClickHouseDatasourceSelectValue( + value: DatasourceSelectValue, +): value is ClickHouseDatasourceSelectValue { + return isVariableDatasource(value) || value.kind === CLICKHOUSE_DATASOURCE_KIND; +} diff --git a/clickhouse/src/model/click-house-types.ts b/clickhouse/src/model/click-house-types.ts new file mode 100644 index 000000000..78d002d55 --- /dev/null +++ b/clickhouse/src/model/click-house-types.ts @@ -0,0 +1,78 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** A column of a ClickHouse result: its name and its ClickHouse type, e.g. `LowCardinality(String)`. */ +export interface ClickHouseColumn { + name: string; + type: string; +} + +const WRAPPER_TYPE = /^(?:Nullable|LowCardinality)\((.*)\)$/s; +const TIME_TYPE = /^(?:Date|Date32|DateTime|DateTime64)(?:\(.*\))?$/s; +const NUMERIC_TYPE = + /^(?:U?Int(?:8|16|32|64|128|256)|Float(?:32|64)|BFloat16|Decimal(?:32|64|128|256)?(?:\(.*\))?|Bool)$/; +const TIME_ZONE = /'([^']+)'\)$/; + +/** unwrapType removes the `Nullable` and `LowCardinality` wrappers, which do not change how a value is read. */ +export function unwrapType(type: string): string { + let current = type.trim(); + for (let match = WRAPPER_TYPE.exec(current); match; match = WRAPPER_TYPE.exec(current)) { + current = (match[1] ?? '').trim(); + } + return current; +} + +/** isTimeType reports whether the values of the type are dates or date/times. */ +export function isTimeType(type: string): boolean { + return TIME_TYPE.test(unwrapType(type)); +} + +/** isNumericType reports whether the values of the type are numbers. Booleans count: they plot as 0 and 1. */ +export function isNumericType(type: string): boolean { + return NUMERIC_TYPE.test(unwrapType(type)); +} + +/** isArrayType reports whether the values of the type are arrays. */ +export function isArrayType(type: string): boolean { + return unwrapType(type).startsWith('Array('); +} + +/** getTypeTimeZone returns the time zone declared by a `DateTime('Zone')` or `DateTime64(3, 'Zone')` type. */ +export function getTypeTimeZone(type: string): string | undefined { + const unwrapped = unwrapType(type); + return TIME_TYPE.test(unwrapped) ? TIME_ZONE.exec(unwrapped)?.[1] : undefined; +} + +/** + * findColumn returns the index of the first column named like one of the candidates, compared case-insensitively, + * or -1. Candidates are tried in order: the first one has priority whatever the order of the columns. + */ +export function findColumn(columns: ClickHouseColumn[], candidates: readonly string[]): number { + for (const candidate of candidates) { + const index = columns.findIndex((column) => column.name.toLowerCase() === candidate); + if (index !== -1) return index; + } + return -1; +} + +/** Names of the column holding the timestamp of a row, by priority. */ +export const TIME_COLUMNS = ['time', 'timestamp', 'timeunix'] as const; + +/** + * findTimeColumn returns the index of the column holding the timestamp of the rows: a column named `time`, + * `timestamp` or `TimeUnix`, else the first date/time column. It returns -1 when there is none. + */ +export function findTimeColumn(columns: ClickHouseColumn[]): number { + const named = findColumn(columns, TIME_COLUMNS); + return named !== -1 ? named : columns.findIndex((column) => isTimeType(column.type)); +} diff --git a/clickhouse/src/model/click-stack-client.test.ts b/clickhouse/src/model/click-stack-client.test.ts new file mode 100644 index 000000000..2ec75c93f --- /dev/null +++ b/clickhouse/src/model/click-stack-client.test.ts @@ -0,0 +1,108 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { createClickStackClient, MAX_ALERTS } from './click-stack-client'; + +function page(alerts: unknown[], total = alerts.length): Response { + return new Response(JSON.stringify({ data: alerts, meta: { total, limit: 1000, offset: 0 } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); +} + +function makeAlerts(count: number, offset = 0): Array<{ id: string }> { + return Array.from({ length: count }, (_unused, index) => ({ id: String(offset + index) })); +} + +function calledUrl(fetchMock: ReturnType>, call = 0): URL { + return new URL(String(fetchMock.mock.calls[call]?.[0])); +} + +describe('createClickStackClient', () => { + it('lists the alerts matching the filters, repeating the ones with several values', async () => { + const fetchMock = vi.fn(async () => page([{ id: 'a' }, { name: 'not an alert' }])); + const client = createClickStackClient({ + datasourceUrl: '/proxy/globaldatasources/clickstack', + headers: { 'X-Team': 'ops' }, + fetch: fetchMock, + }); + + await expect( + client.getAlerts({ states: ['ALERT', 'PENDING'], sources: ['tile'], tags: ['team:a', 'prod'], search: 'cart' }), + ).resolves.toEqual({ alerts: [{ id: 'a' }], total: 2 }); + + const url = calledUrl(fetchMock); + expect(url.origin).toBe(window.location.origin); + expect(url.pathname).toBe('/proxy/globaldatasources/clickstack/api/v2/alerts'); + expect(url.search).toBe( + '?state=ALERT&state=PENDING&source=tile&tag=team%3Aa&tag=prod&search=cart&limit=1000&offset=0', + ); + expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ method: 'GET', headers: { 'X-Team': 'ops' } }); + }); + + it('reads the following pages when the first one does not hold every alert', async () => { + const fetchMock = vi.fn(async (input) => { + const offset = Number(new URL(String(input)).searchParams.get('offset')); + return page(makeAlerts(Math.min(1000, 2500 - offset), offset), 2500); + }); + const client = createClickStackClient({ datasourceUrl: 'http://clickstack:8000', fetch: fetchMock }); + + const response = await client.getAlerts(); + + expect(response.total).toBe(2500); + expect(response.alerts.map((alert) => alert.id)).toEqual(makeAlerts(2500).map((alert) => alert.id)); + expect(fetchMock.mock.calls.map((_call, index) => calledUrl(fetchMock, index).searchParams.get('offset'))).toEqual([ + '0', + '1000', + '2000', + ]); + }); + + it('stops at the maximum number of alerts', async () => { + const fetchMock = vi.fn(async (input) => + page(makeAlerts(1000, Number(new URL(String(input)).searchParams.get('offset'))), 20_000), + ); + const client = createClickStackClient({ datasourceUrl: 'http://clickstack:8000', fetch: fetchMock }); + + const response = await client.getAlerts(); + + expect(response.alerts).toHaveLength(MAX_ALERTS); + expect(response.total).toBe(20_000); + expect(fetchMock).toHaveBeenCalledTimes(MAX_ALERTS / 1000); + }); + + it('tells that the API key is rejected', async () => { + const fetchMock = vi.fn(async () => new Response('Unauthorized', { status: 401 })); + const client = createClickStackClient({ datasourceUrl: 'http://clickstack:8000', fetch: fetchMock }); + + await expect(client.getAlerts()).rejects.toThrow(/ClickStack rejected the API key \(401\)/); + }); + + it('reports the message of a failed request', async () => { + const fetchMock = vi.fn( + async () => new Response('{"message":"Query validation failed: state.0: Invalid enum value"}', { status: 400 }), + ); + const client = createClickStackClient({ datasourceUrl: 'http://clickstack:8000', fetch: fetchMock }); + + await expect(client.getAlerts({ states: ['NOPE'] })).rejects.toThrow( + 'ClickStack request failed (400): Query validation failed: state.0: Invalid enum value', + ); + }); + + it('rejects an answer that is not a list of alerts', async () => { + const fetchMock = vi.fn(async () => new Response('{"version":"v2"}', { status: 200 })); + const client = createClickStackClient({ datasourceUrl: 'http://clickstack:8000', fetch: fetchMock }); + + await expect(client.getAlerts()).rejects.toThrow(/did not answer with a list of alerts/); + }); +}); diff --git a/clickhouse/src/model/click-stack-client.ts b/clickhouse/src/model/click-stack-client.ts new file mode 100644 index 000000000..b25c4f484 --- /dev/null +++ b/clickhouse/src/model/click-stack-client.ts @@ -0,0 +1,189 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { FetchFn, RequestHeaders } from '@perses-dev/client'; + +import { buildUrl } from './url'; + +/** Path of the alerts of the ClickStack API. */ +export const ALERTS_PATH = '/api/v2/alerts'; +/** Path answering to any authenticated request: used to test the connection and the API key. */ +export const API_ROOT_PATH = '/api/v2'; +/** Maximum number of alerts read from ClickStack. */ +export const MAX_ALERTS = 5000; + +// Number of alerts per request: the most the API returns. +const PAGE_SIZE = 1000; +const MAX_ERROR_LENGTH = 300; + +/** States of a ClickStack alert. ClickStack only ever sets the first three. */ +export const CLICKSTACK_ALERT_STATES = ['ALERT', 'PENDING', 'OK', 'INSUFFICIENT_DATA', 'DISABLED'] as const; +export type ClickStackAlertState = (typeof CLICKSTACK_ALERT_STATES)[number]; + +/** What a ClickStack alert watches: a saved search, a tile of a dashboard, or its own chart. */ +export const CLICKSTACK_ALERT_SOURCES = ['saved_search', 'tile', 'inline'] as const; +export type ClickStackAlertSource = (typeof CLICKSTACK_ALERT_SOURCES)[number]; + +/** Alert, as returned by the ClickStack API. Only the fields the plugin reads are described. */ +export interface ClickStackAlert { + id: string; + /** Name of the alert: the one it was given, or else the name of the saved search or dashboard tile it watches. */ + displayName?: string | null; + /** Title of the notifications of the alert. It can be a template. */ + name?: string | null; + message?: string | null; + note?: string | null; + tags?: string[] | null; + source?: string | null; + savedSearchId?: string | null; + dashboardId?: string | null; + tileId?: string | null; + groupBy?: string | null; + threshold?: number | null; + thresholdMax?: number | null; + thresholdType?: string | null; + interval?: string | null; + numConsecutiveWindows?: number | null; + state?: string | null; + silenced?: { by?: string | null; at?: string | null; until?: string | null } | null; + executionErrors?: Array<{ timestamp?: string; type?: string; message?: string }> | null; + createdAt?: string | null; + updatedAt?: string | null; +} + +export interface ClickStackAlertsParams { + /** Only the alerts in one of these states. */ + states?: readonly string[]; + /** Only the alerts watching one of these kinds of sources. */ + sources?: readonly string[]; + /** Only the alerts with one of these tags. */ + tags?: readonly string[]; + /** Only the alerts whose name contains this text. */ + search?: string; + signal?: AbortSignal; +} + +export interface ClickStackAlertsResponse { + alerts: ClickStackAlert[]; + /** Number of alerts matching the request. It is higher than the number of alerts when they were cut. */ + total: number; +} + +export interface ClickStackClientOptions { + datasourceUrl: string; + headers?: RequestHeaders; + fetch?: FetchFn; +} + +export interface ClickStackClient { + getAlerts: (params?: ClickStackAlertsParams, headers?: RequestHeaders) => Promise; +} + +/** buildAlertsSearchParams returns the query string of an alerts request. Filters with several values are repeated. */ +export function buildAlertsSearchParams(params: ClickStackAlertsParams = {}): URLSearchParams { + const search = new URLSearchParams(); + for (const state of params.states ?? []) search.append('state', state); + for (const source of params.sources ?? []) search.append('source', source); + for (const tag of params.tags ?? []) search.append('tag', tag); + if (params.search) search.set('search', params.search); + return search; +} + +function isAlert(value: unknown): value is ClickStackAlert { + return typeof value === 'object' && value !== null && typeof (value as { id?: unknown }).id === 'string'; +} + +// Reads a page of alerts: `{data, meta}` for ClickStack, `{result}` for the managed service of ClickHouse Cloud. +function parsePage(body: unknown): { alerts: ClickStackAlert[]; total: number } { + const envelope = typeof body === 'object' && body !== null ? (body as Record) : {}; + const items = Array.isArray(body) ? body : (envelope.data ?? envelope.result); + if (!Array.isArray(items)) { + throw new Error('ClickStack did not answer with a list of alerts. Check the URL of the datasource.'); + } + const alerts = items.filter(isAlert); + const meta = envelope.meta; + const total = typeof meta === 'object' && meta !== null ? Number((meta as { total?: unknown }).total) : NaN; + return { alerts, total: Number.isFinite(total) ? total : alerts.length }; +} + +async function toError(response: Response): Promise { + if (response.status === 401 || response.status === 403) { + return new Error( + `ClickStack rejected the API key (${response.status}). Check the secret of the datasource: it must hold a ClickStack API key as a bearer token.`, + ); + } + let detail = ''; + try { + const text = await response.text(); + try { + const body: unknown = JSON.parse(text); + const message = typeof body === 'object' && body !== null ? (body as { message?: unknown }).message : undefined; + detail = typeof message === 'string' ? message : text; + } catch { + detail = text; + } + } catch { + // No body to read: the status alone is reported. + } + const shortened = detail.length > MAX_ERROR_LENGTH ? `${detail.slice(0, MAX_ERROR_LENGTH)}…` : detail; + return new Error(`ClickStack request failed (${response.status}): ${shortened.trim() || response.statusText}`); +} + +/** createClickStackClient returns a client of the API of ClickStack (HyperDX). */ +export function createClickStackClient(options: ClickStackClientOptions): ClickStackClient { + const { datasourceUrl, headers: defaultHeaders, fetch: customFetch } = options; + + async function getPage( + params: ClickStackAlertsParams, + offset: number, + headers: RequestHeaders | undefined, + ): Promise<{ alerts: ClickStackAlert[]; total: number }> { + const url = buildUrl(datasourceUrl, ALERTS_PATH); + const search = buildAlertsSearchParams(params); + search.set('limit', String(PAGE_SIZE)); + search.set('offset', String(offset)); + url.search = search.toString(); + + let response: Response; + try { + response = await (customFetch ?? fetch)(url.toString(), { method: 'GET', headers, signal: params.signal }); + } catch (error) { + // The Perses fetch throws on error statuses, with the status of the response. + const status = (error as { status?: unknown } | null)?.status; + if (status === 401 || status === 403) throw await toError(new Response(null, { status })); + throw error; + } + if (!response.ok) throw await toError(response); + return parsePage(await response.json()); + } + + async function getAlerts( + params: ClickStackAlertsParams = {}, + headers?: RequestHeaders, + ): Promise { + const requestHeaders = headers ?? defaultHeaders; + const first = await getPage(params, 0, requestHeaders); + const wanted = Math.min(first.total, MAX_ALERTS); + if (first.alerts.length >= wanted || first.alerts.length < PAGE_SIZE) { + return { alerts: first.alerts.slice(0, MAX_ALERTS), total: first.total }; + } + // The first page tells how many alerts there are: the other pages are read at once. + const offsets: number[] = []; + for (let offset = PAGE_SIZE; offset < wanted; offset += PAGE_SIZE) offsets.push(offset); + const pages = await Promise.all(offsets.map((offset) => getPage(params, offset, requestHeaders))); + const alerts = [first, ...pages].flatMap((page) => page.alerts); + return { alerts: alerts.slice(0, MAX_ALERTS), total: first.total }; + } + + return { getAlerts }; +} diff --git a/clickhouse/src/model/click-stack-selectors.ts b/clickhouse/src/model/click-stack-selectors.ts new file mode 100644 index 000000000..d52548881 --- /dev/null +++ b/clickhouse/src/model/click-stack-selectors.ts @@ -0,0 +1,34 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { DatasourceSelectValue } from '@perses-dev/plugin-system'; +import { isVariableDatasource } from '@perses-dev/plugin-system'; +import type { DatasourceSelector } from '@perses-dev/spec'; + +export const CLICKSTACK_DATASOURCE_KIND = 'ClickStackDatasource' as const; + +export interface ClickStackDatasourceSelector extends DatasourceSelector { + kind: typeof CLICKSTACK_DATASOURCE_KIND; +} + +/** Selects the default ClickStack datasource. */ +export const DEFAULT_CLICKSTACK: ClickStackDatasourceSelector = { kind: CLICKSTACK_DATASOURCE_KIND }; + +/** Datasource of a ClickStack query: a ClickStack datasource, or a variable holding the name of one. */ +export type ClickStackDatasourceSelectValue = DatasourceSelectValue; + +export function isClickStackDatasourceSelectValue( + value: DatasourceSelectValue, +): value is ClickStackDatasourceSelectValue { + return isVariableDatasource(value) || value.kind === CLICKSTACK_DATASOURCE_KIND; +} diff --git a/clickhouse/src/model/datasource-client.ts b/clickhouse/src/model/datasource-client.ts new file mode 100644 index 000000000..633d91b4d --- /dev/null +++ b/clickhouse/src/model/datasource-client.ts @@ -0,0 +1,39 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { DatasourceSelectValue, DatasourceStore, VariableStateMap } from '@perses-dev/plugin-system'; +import { datasourceSelectValueToSelector, isVariableDatasource } from '@perses-dev/plugin-system'; +import type { DatasourceSelector } from '@perses-dev/spec'; + +/** + * getDatasourceClient returns the client of the datasource of a query: the selected datasource, the one named by a + * variable, or the default datasource of the kind. + */ +export async function getDatasourceClient( + datasource: DatasourceSelectValue | undefined, + kind: string, + defaultSelector: DatasourceSelector, + context: { datasourceStore: DatasourceStore; variableState: VariableStateMap }, +): Promise { + const { datasourceStore, variableState } = context; + if (!isVariableDatasource(datasource)) { + return datasourceStore.getDatasourceClient(datasource ?? defaultSelector); + } + // Only a datasource variable needs the list of the datasources to be resolved. + const selector = datasourceSelectValueToSelector( + datasource, + variableState, + await datasourceStore.listDatasourceSelectItems(kind), + ); + return datasourceStore.getDatasourceClient(selector ?? defaultSelector); +} diff --git a/clickhouse/src/model/execute-query.ts b/clickhouse/src/model/execute-query.ts new file mode 100644 index 000000000..c7c12fed8 --- /dev/null +++ b/clickhouse/src/model/execute-query.ts @@ -0,0 +1,168 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { DatasourceStore, VariableStateMap } from '@perses-dev/plugin-system'; +import { isVariableDatasource, parseVariables } from '@perses-dev/plugin-system'; +import type { AbsoluteTimeRange, Notice } from '@perses-dev/spec'; + +import type { ClickHouseClient, ClickHouseQueryResponse } from './click-house-client'; +import { MAX_ROWS } from './click-house-client'; +import type { ClickHouseDatasourceSelectValue } from './click-house-selectors'; +import { CLICKHOUSE_DATASOURCE_KIND, DEFAULT_CLICKHOUSE } from './click-house-selectors'; +import { getDatasourceClient } from './datasource-client'; +import { interpolateVariables } from './interpolation'; +import { expandMacros, formatClickHouseDateTime, parseQueryVariables, replaceTimeRangePlaceholders } from './macros'; +import { stripFormat } from './sql'; + +const SECOND = 1000; +const MINUTE = 60 * SECOND; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +// Round intervals, so that the buckets of a query start at round times and do not move with the width of a panel. +const INTERVALS = [ + SECOND, + 2 * SECOND, + 5 * SECOND, + 10 * SECOND, + 15 * SECOND, + 30 * SECOND, + MINUTE, + 2 * MINUTE, + 5 * MINUTE, + 10 * MINUTE, + 15 * MINUTE, + 30 * MINUTE, + HOUR, + 2 * HOUR, + 3 * HOUR, + 6 * HOUR, + 12 * HOUR, + DAY, + 2 * DAY, + 7 * DAY, + 30 * DAY, +]; +// Number of data points aimed for when the panel does not suggest a step. +const DEFAULT_POINTS = 300; + +/** Fields shared by the specs of every ClickHouse query. */ +export interface ClickHouseQuerySpec { + datasource?: ClickHouseDatasourceSelectValue; + query: string; +} + +/** What a ClickHouse query needs from the context of the plugin running it. */ +export interface ClickHouseQueryContext { + datasourceStore: DatasourceStore; + variableState: VariableStateMap; + /** Time range of the query. Queries using time macros or placeholders fail without it. */ + timeRange?: AbsoluteTimeRange; + /** Interval between two data points suggested by the panel, in milliseconds. */ + suggestedStepMs?: number; + /** Lower bound of the interval of the query, in milliseconds. */ + minStepMs?: number; +} + +export interface ExecutedQuery extends ClickHouseQueryResponse { + /** The statement sent to ClickHouse, once the macros, placeholders and variables are replaced. */ + executedQueryString: string; + /** Value of the interval macros, in milliseconds. */ + intervalMs: number; +} + +/** + * getIntervalMs returns the interval of the `$__interval_s` family of macros: the first round interval that is at + * least the step suggested by the panel, or that splits the time range in a few hundred buckets. It is never shorter + * than the min step of the query, rounded up to the second as the shortest interval is one second. + */ +export function getIntervalMs( + timeRange: AbsoluteTimeRange | undefined, + suggestedStepMs: number | undefined, + minStepMs = 0, +): number { + const rangeMs = timeRange ? timeRange.end.getTime() - timeRange.start.getTime() : 0; + // A panel suggests a step of 0 until its width is known. + const target = suggestedStepMs || rangeMs / DEFAULT_POINTS; + const interval = INTERVALS.find((candidate) => candidate >= target) ?? Math.ceil(target / DAY) * DAY; + return Math.max(interval, Math.ceil(minStepMs / SECOND) * SECOND); +} + +/** + * prepareQuery replaces the macros, the time range placeholders and the dashboard variables of a query. A final + * `FORMAT` clause is dropped: the results are read in the format of the client. + */ +export function prepareQuery(sql: string, context: ClickHouseQueryContext): { sql: string; intervalMs: number } { + const { timeRange, variableState } = context; + const statement = stripFormat(sql); + const intervalMs = getIntervalMs(timeRange, context.suggestedStepMs, context.minStepMs); + let prepared = expandMacros(statement, { timeRange, intervalMs, variableState }); + if (timeRange) { + prepared = replaceTimeRangePlaceholders( + prepared, + formatClickHouseDateTime(timeRange.start), + formatClickHouseDateTime(timeRange.end), + ); + } + return { sql: interpolateVariables(prepared, variableState), intervalMs }; +} + +/** queryDependencies lists the dashboard variables a query depends on: the ones of its statements and datasource. */ +export function queryDependencies( + datasource: ClickHouseDatasourceSelectValue | undefined, + ...statements: Array +): { variables: string[] } { + const variables = new Set(isVariableDatasource(datasource) ? parseVariables(datasource) : []); + for (const statement of statements) { + for (const name of statement ? parseQueryVariables(statement) : []) { + variables.add(name); + } + } + return { variables: [...variables] }; +} + +/** getClickHouseClient returns the client of the datasource of a query, resolving a datasource variable. */ +export function getClickHouseClient( + datasource: ClickHouseDatasourceSelectValue | undefined, + context: Pick, +): Promise { + return getDatasourceClient(datasource, CLICKHOUSE_DATASOURCE_KIND, DEFAULT_CLICKHOUSE, context); +} + +/** runStatement sends an already prepared statement to the datasource of a query. */ +export async function runStatement( + datasource: ClickHouseDatasourceSelectValue | undefined, + sql: string, + context: Pick, + signal?: AbortSignal, +): Promise { + const client = await getClickHouseClient(datasource, context); + return client.query({ query: sql, signal }); +} + +/** executeQuery prepares a query, as written by the user, and runs it on its datasource. */ +export async function executeQuery( + spec: ClickHouseQuerySpec, + context: ClickHouseQueryContext, + signal?: AbortSignal, +): Promise { + const { sql, intervalMs } = prepareQuery(spec.query, context); + const response = await runStatement(spec.datasource, sql, context, signal); + return { ...response, executedQueryString: sql, intervalMs }; +} + +/** truncationNotices warns that a result was cut. */ +export function truncationNotices(response: Pick): Notice[] { + return response.truncated + ? [{ type: 'warning', message: `Results were truncated to the first ${MAX_ROWS} rows.` }] + : []; +} diff --git a/clickhouse/src/model/interpolation.test.ts b/clickhouse/src/model/interpolation.test.ts new file mode 100644 index 000000000..2323513ab --- /dev/null +++ b/clickhouse/src/model/interpolation.test.ts @@ -0,0 +1,59 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { interpolateVariables } from './interpolation'; + +describe('interpolateVariables', () => { + it('quotes the values of the sqlstring format as ClickHouse string literals', () => { + const variableState = { + one: { value: "it's", loading: false }, + many: { value: ['a', 'b\\'], loading: false }, + }; + + expect(interpolateVariables('x = ${one:sqlstring} AND y IN (${many:sqlstring})', variableState)).toBe( + "x = 'it\\'s' AND y IN ('a','b\\\\')", + ); + }); + + it('keeps IN valid when nothing is selected', () => { + expect(interpolateVariables('y IN (${many:sqlstring})', { many: { value: [], loading: false } })).toBe( + 'y IN (NULL)', + ); + }); + + it('does not interpolate the value of a variable again', () => { + const variableState = { + a: { value: '$b', loading: false }, + b: { value: 'injected', loading: false }, + }; + + expect(interpolateVariables('SELECT ${a:sqlstring}, $b', variableState)).toBe("SELECT '$b', injected"); + }); + + it('leaves the other formats to Perses and unknown variables as they are', () => { + const variableState = { table: { value: 'otel_logs', loading: false } }; + + expect(interpolateVariables('SELECT * FROM $table WHERE x = ${unknown:sqlstring}', variableState)).toBe( + 'SELECT * FROM otel_logs WHERE x = ${unknown:sqlstring}', + ); + }); + + it('leaves the variables of the comments alone, so that a value can not end a comment', () => { + const variableState = { service: { value: 'x\nDROP TABLE t */ OR 1', loading: false } }; + const sql = 'SELECT 1 -- AND s = ${service:sqlstring}\n/* $service */ WHERE s = ${service:sqlstring}'; + + expect(interpolateVariables(sql, variableState)).toBe( + "SELECT 1 -- AND s = ${service:sqlstring}\n/* $service */ WHERE s = 'x\nDROP TABLE t */ OR 1'", + ); + }); +}); diff --git a/clickhouse/src/model/interpolation.ts b/clickhouse/src/model/interpolation.ts new file mode 100644 index 000000000..b1211a474 --- /dev/null +++ b/clickhouse/src/model/interpolation.ts @@ -0,0 +1,47 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { VariableStateMap } from '@perses-dev/plugin-system'; +import { replaceVariables } from '@perses-dev/plugin-system'; + +import { commentRanges, isInRanges, quoteString } from './sql'; + +// Same references as the Perses variables: `$name`, `${name}`, `${name.path}` and `${name:format}`. +const VARIABLE_REFERENCE = /\$\w+|\$\{\w+(?:\.[^:}]+)?(?::[^}]+)?\}/g; +const SQL_STRING_REFERENCE = /^\$\{(\w+):sqlstring\}$/i; + +/** + * interpolateVariables replaces the dashboard variables of a query. + * + * The `sqlstring` format is the one to use for string literals, e.g. `ServiceName IN (${service:sqlstring})`. It is + * rewritten here because ClickHouse reads backslashes as escape characters, which the generic format does not escape: + * a value ending with a backslash would otherwise break out of its literal. + * + * References are replaced in a single pass, so that a `$name` sequence inside a value is never interpolated again. + * The ones in comments are left as is: a value with a line break or a `*` + `/` sequence would end the comment, and + * a commented out filter would run, whatever its format. + */ +export function interpolateVariables(sql: string, variableState: VariableStateMap): string { + const comments = commentRanges(sql); + return sql.replace(VARIABLE_REFERENCE, (reference: string, offset: number) => { + if (isInRanges(offset, comments)) return reference; + const name = SQL_STRING_REFERENCE.exec(reference)?.[1]; + if (name === undefined) return replaceVariables(reference, variableState); + const state = variableState[name]; + if (state === undefined || state.value === undefined) return reference; + const values = Array.isArray(state.value) ? state.value : [state.value]; + // An empty selection matches nothing while keeping `IN (...)` valid. + if (values.length === 0) return 'NULL'; + return values.map((value) => (value === null ? 'NULL' : quoteString(value))).join(','); + }); +} diff --git a/clickhouse/src/model/macros.test.ts b/clickhouse/src/model/macros.test.ts new file mode 100644 index 000000000..a290a90fd --- /dev/null +++ b/clickhouse/src/model/macros.test.ts @@ -0,0 +1,114 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { expandMacros, parseQueryVariables } from './macros'; + +const timeRange = { start: new Date('2026-01-01T00:00:00.500Z'), end: new Date('2026-01-01T01:00:00.500Z') }; +const context = { timeRange, intervalMs: 60_000, variableState: {} }; + +describe('expandMacros', () => { + it('filters on the time range, rounded outwards to the second', () => { + expect(expandMacros('SELECT 1 WHERE $__timeFilter(Timestamp) AND x', context)).toBe( + 'SELECT 1 WHERE (Timestamp >= toDateTime(1767225600) AND Timestamp <= toDateTime(1767229201)) AND x', + ); + }); + + it('filters with millisecond precision', () => { + expect(expandMacros('$__timeFilter_ms(ts)', context)).toBe( + '(ts >= fromUnixTimestamp64Milli(1767225600500) AND ts <= fromUnixTimestamp64Milli(1767229200500))', + ); + }); + + it('filters on a date column and a time column', () => { + // A day more on each side keeps the rows of a date column computed in another time zone than UTC. + expect(expandMacros('$__dateTimeFilter(d, t)', context)).toBe( + "(d >= toDate('2025-12-31') AND d <= toDate('2026-01-02') AND t >= toDateTime(1767225600) AND t <= toDateTime(1767229201))", + ); + expect(expandMacros('$__dateFilter(d)', context)).toBe("(d >= toDate('2026-01-01') AND d <= toDate('2026-01-01'))"); + }); + + it('buckets on the interval and exposes it', () => { + expect(expandMacros('SELECT $__timeInterval(Timestamp) AS time, count() / $__interval_s', context)).toBe( + 'SELECT toStartOfInterval(toDateTime(Timestamp), INTERVAL 60 second) AS time, count() / 60', + ); + expect(expandMacros('$__interval_ms', context)).toBe('60000'); + }); + + it('reads arguments holding parentheses, commas and strings', () => { + expect(expandMacros("$__timeInterval(if(a = ')', toDateTime(b, 'UTC'), c))", context)).toBe( + "toStartOfInterval(toDateTime(if(a = ')', toDateTime(b, 'UTC'), c)), INTERVAL 60 second)", + ); + }); + + it('drops a condition when "All" is selected', () => { + const sql = 'WHERE $__conditionalAll(service IN (${service:sqlstring}), $service)'; + const selected = { service: { value: ['a', 'b'], loading: false } }; + const all = { service: { value: ['a', 'b'], loading: false, displayValue: 'All' } }; + + expect(expandMacros(sql, { ...context, variableState: selected })).toBe('WHERE service IN (${service:sqlstring})'); + expect(expandMacros(sql, { ...context, variableState: all })).toBe('WHERE 1=1'); + }); + + it('does not mistake a macro for the variable it starts like', () => { + // $__fromTime starts like the $__from variable of Perses. + expect(expandMacros('$__fromTime AND $__toTime_ms', context)).toBe( + 'toDateTime(1767225600) AND fromUnixTimestamp64Milli(1767229200500)', + ); + }); + + it('replaces the macros in the arguments of a macro', () => { + expect( + expandMacros('$__conditionalAll($__timeInterval(t) > $__fromTime, $service)', { + ...context, + variableState: { service: { value: 'a', loading: false } }, + }), + ).toBe('toStartOfInterval(toDateTime(t), INTERVAL 60 second) > toDateTime(1767225600)'); + }); + + it('leaves the comments of a query alone', () => { + const sql = 'SELECT 1 -- $__timeFilter is not used /* yet */\n/* nor $__timeInterval */ # or $__dateFilter'; + + expect(expandMacros(sql, context)).toBe(sql); + // A comment mark inside a string is not one. + expect(expandMacros("SELECT '--', $__interval_s", context)).toBe("SELECT '--', 60"); + }); + + it('leaves the macros taking arguments in strings alone, and replaces the values', () => { + expect(expandMacros("WHERE Body LIKE '%$__timeFilter%' AND x = '$__interval_s'", context)).toBe( + "WHERE Body LIKE '%$__timeFilter%' AND x = '60'", + ); + }); + + it('rejects a macro without its arguments', () => { + expect(() => expandMacros('WHERE $__timeFilter', context)).toThrow('The $__timeFilter macro expects 1 argument'); + expect(() => expandMacros('$__dateTimeFilter(d)', context)).toThrow('expects 2 arguments'); + }); + + it('rejects a time macro when the query has no time range', () => { + expect(() => expandMacros('$__timeFilter(t)', { ...context, timeRange: undefined })).toThrow(/needs a time range/); + // The interval macros do not need it. + expect(expandMacros('$__interval_s', { ...context, timeRange: undefined })).toBe('60'); + }); +}); + +describe('parseQueryVariables', () => { + it('lists the dashboard variables, not the macros', () => { + expect( + parseQueryVariables('WHERE $__timeFilter(t) AND a = $foo AND b IN (${bar:sqlstring}) AND $__interval_s > 1'), + ).toEqual(['foo', 'bar']); + }); + + it('leaves out the variables of the comments, which are not replaced', () => { + expect(parseQueryVariables('SELECT 1 -- AND a = $foo\nWHERE b = $bar /* $baz */')).toEqual(['bar']); + }); +}); diff --git a/clickhouse/src/model/macros.ts b/clickhouse/src/model/macros.ts new file mode 100644 index 000000000..d1b34fcc1 --- /dev/null +++ b/clickhouse/src/model/macros.ts @@ -0,0 +1,230 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { VariableStateMap } from '@perses-dev/plugin-system'; +import { parseVariables } from '@perses-dev/plugin-system'; +import type { AbsoluteTimeRange } from '@perses-dev/spec'; + +import { blankComments, commentRanges, isInRanges, quotedRanges } from './sql'; + +/** + * Macros of the ClickHouse queries. Their names and expansions follow the ones of the Grafana ClickHouse datasource, + * so that queries written for it can be reused. The longest names come first: `$__timeFilter` is a prefix of + * `$__timeFilter_ms`. + */ +export const MACRO_NAMES = [ + '__timeFilter_ms', + '__timeFilter', + '__dateTimeFilter', + '__dateFilter', + '__timeInterval_ms', + '__timeInterval', + '__fromTime_ms', + '__fromTime', + '__toTime_ms', + '__toTime', + '__interval_ms', + '__interval_s', + '__conditionalAll', +] as const; + +type MacroName = (typeof MACRO_NAMES)[number]; + +const MACRO_NAME_SET: ReadonlySet = new Set(MACRO_NAMES); +const MACRO = new RegExp(String.raw`\$(${MACRO_NAMES.join('|')})\b`, 'g'); +const ARGUMENT_COUNT: Partial> = { + __timeFilter_ms: 1, + __timeFilter: 1, + __dateTimeFilter: 2, + __dateFilter: 1, + __timeInterval_ms: 1, + __timeInterval: 1, + __conditionalAll: 2, +}; + +export interface MacroContext { + /** Time range of the query. Macros reading it throw when it is not set. */ + timeRange?: AbsoluteTimeRange; + /** Interval between two data points, in milliseconds. */ + intervalMs: number; + variableState: VariableStateMap; +} + +/** isMacroName reports whether a `$name` reference is a macro rather than a dashboard variable. */ +export function isMacroName(name: string): boolean { + return MACRO_NAME_SET.has(name); +} + +/** + * parseQueryVariables lists the dashboard variables referenced by a query, leaving the macros out, and the comments, + * where variables are not replaced. + */ +export function parseQueryVariables(sql: string): string[] { + return parseVariables(blankComments(sql)).filter((name) => !isMacroName(name)); +} + +/** + * formatClickHouseDateTime writes a date as `YYYY-MM-DD hh:mm:ss` in UTC, the value of the `{start}` and `{end}` + * placeholders. + */ +export function formatClickHouseDateTime(date: Date): string { + return date + .toISOString() + .replace('T', ' ') + .replace(/\.\d{3}Z$/, ''); +} + +/** replaceTimeRangePlaceholders replaces the `{start}` and `{end}` placeholders of a query. */ +export function replaceTimeRangePlaceholders(sql: string, start?: string, end?: string): string { + return sql.replaceAll('{start}', start ?? '{start}').replaceAll('{end}', end ?? '{end}'); +} + +// Reads the arguments of a macro call whose opening parenthesis is at `open`. Commas inside nested parentheses or +// quotes do not split arguments. +function readArguments(sql: string, open: number): { args: string[]; end: number } | undefined { + const args: string[] = []; + let depth = 0; + let argumentStart = open + 1; + for (let index = open; index < sql.length; index++) { + const char = sql[index]; + if (char === "'" || char === '"' || char === '`') { + index++; + while (index < sql.length && sql[index] !== char) { + index += sql[index] === '\\' ? 2 : 1; + } + } else if (char === '(' || char === '[') { + depth++; + } else if (char === ')' || char === ']') { + depth--; + if (depth === 0) { + args.push(sql.slice(argumentStart, index).trim()); + return { args, end: index + 1 }; + } + } else if (char === ',' && depth === 1) { + args.push(sql.slice(argumentStart, index).trim()); + argumentStart = index + 1; + } + } + return undefined; +} + +function isAllSelected(name: string | undefined, variableState: VariableStateMap): boolean { + const state = name === undefined ? undefined : variableState[name]; + if (!state) return false; + // Perses resolves the "All" value to its custom value, or to every option with "All" as display value. + return state.customAllValue !== undefined || state.displayValue === 'All'; +} + +// Writes the UTC date of a time, moved by a number of days, as a ClickHouse date. +function dateLiteral(date: Date, days: number): string { + return `toDate('${new Date(date.getTime() + days * 24 * 60 * 60 * 1000).toISOString().slice(0, 10)}')`; +} + +function requireTimeRange(name: MacroName, timeRange: AbsoluteTimeRange | undefined): AbsoluteTimeRange { + if (!timeRange) { + throw new Error(`The $${name} macro needs a time range, which is not available for this query`); + } + return timeRange; +} + +function expandMacro(name: MacroName, args: string[], context: MacroContext): string { + const { intervalMs, variableState } = context; + switch (name) { + case '__interval_s': + return String(Math.max(1, Math.round(intervalMs / 1000))); + case '__interval_ms': + return String(Math.max(1, Math.round(intervalMs))); + case '__timeInterval': + return `toStartOfInterval(toDateTime(${args[0]}), INTERVAL ${Math.max(1, Math.round(intervalMs / 1000))} second)`; + case '__timeInterval_ms': + return `toStartOfInterval(toDateTime64(${args[0]}, 3), INTERVAL ${Math.max(1, Math.round(intervalMs))} millisecond)`; + case '__conditionalAll': + return isAllSelected(parseVariables(args[1] ?? '')[0], variableState) ? '1=1' : (args[0] ?? ''); + default: + break; + } + + const { start, end } = requireTimeRange(name, context.timeRange); + const fromSeconds = `toDateTime(${Math.floor(start.getTime() / 1000)})`; + const toSeconds = `toDateTime(${Math.ceil(end.getTime() / 1000)})`; + const fromMillis = `fromUnixTimestamp64Milli(${start.getTime()})`; + const toMillis = `fromUnixTimestamp64Milli(${end.getTime()})`; + const dateFilter = (column: string | undefined, marginDays = 0): string => + `${column} >= ${dateLiteral(start, -marginDays)} AND ${column} <= ${dateLiteral(end, marginDays)}`; + const timeFilter = (column: string | undefined): string => + `${column} >= ${fromSeconds} AND ${column} <= ${toSeconds}`; + switch (name) { + case '__timeFilter': + return `(${timeFilter(args[0])})`; + case '__timeFilter_ms': + return `(${args[0]} >= ${fromMillis} AND ${args[0]} <= ${toMillis})`; + case '__dateFilter': + return `(${dateFilter(args[0])})`; + case '__dateTimeFilter': + // The dates are in UTC, while the date column may be computed in another time zone, e.g. `toDate(Timestamp)` in + // the one of the server. A day more on each side keeps the rows of the time range: the time filter cuts them. + return `(${dateFilter(args[0], 1)} AND ${timeFilter(args[1])})`; + case '__fromTime': + return fromSeconds; + case '__toTime': + return toSeconds; + case '__fromTime_ms': + return fromMillis; + default: + return toMillis; + } +} + +// Yields the references to macros of a query. The ones in its comments are left out: a comment mentioning a macro +// must not make the query fail. So are the macros taking arguments in its strings, e.g. `LIKE '%$__timeFilter%'`: +// they write expressions, which have no place in a string. The other ones are values, replaced in strings too, like +// the dashboard variables. +function* macroReferences(sql: string): Generator<{ name: MacroName; start: number; end: number }> { + const comments = commentRanges(sql); + const quoted = quotedRanges(sql); + for (const match of sql.matchAll(MACRO)) { + const start = match.index; + const name = match[1] as MacroName; + if (isInRanges(start, comments)) continue; + if (ARGUMENT_COUNT[name] !== undefined && isInRanges(start, quoted)) continue; + yield { name, start, end: start + match[0].length }; + } +} + +/** + * expandMacros replaces the `$__macro` and `$__macro(arguments)` references of a query. It must run before the + * dashboard variables are replaced: `$__fromTime` would otherwise be read as the `$__from` variable. + */ +export function expandMacros(sql: string, context: MacroContext): string { + let result = ''; + let position = 0; + for (const reference of macroReferences(sql)) { + // Already replaced, as part of an argument of the previous macro. + if (reference.start < position) continue; + const { name } = reference; + const expected = ARGUMENT_COUNT[name]; + let args: string[] = []; + let { end } = reference; + if (expected !== undefined) { + const call = sql[end] === '(' ? readArguments(sql, end) : undefined; + if (!call || call.args.length !== expected || call.args.some((argument) => argument === '')) { + throw new Error(`The $${name} macro expects ${expected} argument${expected > 1 ? 's' : ''}`); + } + args = call.args.map((argument) => expandMacros(argument, context)); + end = call.end; + } + result += sql.slice(position, reference.start) + expandMacro(name, args, context); + position = end; + } + return result + sql.slice(position); +} diff --git a/clickhouse/src/model/sql.test.ts b/clickhouse/src/model/sql.test.ts new file mode 100644 index 000000000..becf9d65e --- /dev/null +++ b/clickhouse/src/model/sql.test.ts @@ -0,0 +1,110 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { asSubquery, quoteString, quoteTableName, selectedColumns, stripFormat, stripOrderAndLimit } from './sql'; + +describe('quoteString', () => { + it('escapes the characters ending a ClickHouse string literal', () => { + expect(quoteString("a'b\\")).toBe("'a\\'b\\\\'"); + }); +}); + +describe('quoteTableName', () => { + it('quotes a table and its database', () => { + expect(quoteTableName('otel_traces')).toBe('`otel_traces`'); + expect(quoteTableName('otel.otel_traces')).toBe('`otel`.`otel_traces`'); + }); + + it('rejects anything that is not a table name', () => { + expect(() => quoteTableName('otel_traces WHERE 1 = 1')).toThrow(/Invalid ClickHouse table name/); + expect(() => quoteTableName('a.b.c')).toThrow(); + }); +}); + +describe('asSubquery', () => { + it('keeps a trailing line comment from commenting out the closing parenthesis', () => { + expect(asSubquery('SELECT 1 -- one\n;')).toBe('(\nSELECT 1 -- one\n)'); + }); +}); + +describe('stripOrderAndLimit', () => { + it('removes the final ORDER BY, LIMIT and FORMAT clauses', () => { + expect(stripOrderAndLimit('SELECT a FROM t WHERE b ORDER BY a DESC LIMIT 10 OFFSET 5;')).toBe( + 'SELECT a FROM t WHERE b', + ); + expect(stripOrderAndLimit('SELECT a FROM t LIMIT 10 FORMAT JSON')).toBe('SELECT a FROM t'); + }); + + it('keeps the settings of the statement', () => { + expect(stripOrderAndLimit('SELECT a FROM t ORDER BY a LIMIT 10 SETTINGS max_threads = 2')).toBe( + 'SELECT a FROM t\nSETTINGS max_threads = 2', + ); + }); + + it('leaves the clauses of subqueries, window functions, strings and comments alone', () => { + const sql = [ + "SELECT a, 'ORDER BY x LIMIT 1' AS text, row_number() OVER (PARTITION BY b ORDER BY c) AS n", + 'FROM (SELECT * FROM t ORDER BY a LIMIT 5) -- ORDER BY comment', + 'GROUP BY a', + ].join('\n'); + + expect(stripOrderAndLimit(`${sql}\nORDER BY a`)).toBe(sql); + }); + + it('gives up on statements that can not be cut safely', () => { + expect(stripOrderAndLimit('SELECT a FROM t UNION ALL SELECT a FROM u LIMIT 10')).toBeUndefined(); + expect(stripOrderAndLimit('SELECT a FROM t EXCEPT (SELECT a FROM u) LIMIT 10')).toBeUndefined(); + // LIMIT BY selects rows: removing it would count other rows. + expect(stripOrderAndLimit('SELECT a FROM t ORDER BY b LIMIT 1 BY a')).toBeUndefined(); + }); +}); + +describe('stripFormat', () => { + it('removes the final FORMAT clause of a statement, which queries used to end with', () => { + expect(stripFormat('SELECT a FROM t ORDER BY a FORMAT JSON;')).toBe('SELECT a FROM t ORDER BY a'); + expect(stripFormat("SELECT formatDateTime(t, '%F') AS format FROM (SELECT 1 FORMAT) -- FORMAT JSON")).toBe( + "SELECT formatDateTime(t, '%F') AS format FROM (SELECT 1 FORMAT) -- FORMAT JSON", + ); + }); + + it('removes a FORMAT clause followed by a comment', () => { + expect(stripFormat('SELECT 1 FORMAT JSON -- legacy')).toBe('SELECT 1'); + expect(stripFormat('SELECT 1 FORMAT JSON; /* legacy */')).toBe('SELECT 1'); + expect(stripOrderAndLimit('SELECT a FROM t LIMIT 10 FORMAT JSON -- legacy')).toBe('SELECT a FROM t'); + }); +}); + +describe('selectedColumns', () => { + it('lists the aliases and the plain columns', () => { + expect( + selectedColumns('SELECT DISTINCT t.Timestamp, toString(a, b) AS `my body`, Level FROM (SELECT x FROM y) AS t'), + ).toEqual({ names: ['Timestamp', 'my body', 'Level'], hasWildcard: false, excluded: [] }); + }); + + it('tells that a wildcard selects columns it can not name, and the ones it leaves out', () => { + expect(selectedColumns('SELECT *, a AS b FROM t')).toEqual({ names: ['b'], hasWildcard: true, excluded: [] }); + expect(selectedColumns('SELECT * EXCEPT (Body, `Trace Id`), t.* EXCEPT SpanId FROM t')).toEqual({ + names: [], + hasWildcard: true, + excluded: ['Body', 'Trace Id', 'SpanId'], + }); + }); + + it('leaves the comments of the list of columns out', () => { + expect(selectedColumns('SELECT Timestamp -- event time, or not\n, Body /* the message, */ FROM t')).toEqual({ + names: ['Timestamp', 'Body'], + hasWildcard: false, + excluded: [], + }); + }); +}); diff --git a/clickhouse/src/model/sql.ts b/clickhouse/src/model/sql.ts new file mode 100644 index 000000000..f5d583f87 --- /dev/null +++ b/clickhouse/src/model/sql.ts @@ -0,0 +1,291 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const TABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/; + +/** quoteString writes a value as a ClickHouse string literal. Backslashes are escape characters in ClickHouse. */ +export function quoteString(value: string): string { + return `'${value.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`; +} + +/** quoteIdentifier writes a column or table name as a quoted ClickHouse identifier. */ +export function quoteIdentifier(identifier: string): string { + return `\`${identifier.replaceAll('\\', '\\\\').replaceAll('`', '\\`')}\``; +} + +/** isTableName reports whether the text is a plain table name, optionally qualified by its database. */ +export function isTableName(table: string): boolean { + return TABLE_NAME.test(table); +} + +/** + * quoteTableName writes a table name, optionally qualified by its database, as quoted identifiers. + * It throws when the name is not a plain `table` or `database.table`, so that it can not carry SQL. + */ +export function quoteTableName(table: string): string { + if (!isTableName(table)) { + throw new Error(`Invalid ClickHouse table name "${table}": expected "table" or "database.table"`); + } + return table.split('.').map(quoteIdentifier).join('.'); +} + +/** + * asSubquery wraps a statement so that it can be read with `FROM`. The line breaks keep a trailing line comment of + * the statement from commenting out the closing parenthesis. + */ +export function asSubquery(sql: string): string { + return `(\n${sql.trim().replace(/(?:\s*;)+$/, '')}\n)`; +} + +interface Token { + kind: 'word' | 'comment' | 'quoted'; + /** A word in upper case, or a comment, string or quoted identifier as written. */ + text: string; + start: number; + depth: number; +} + +const WORD_START = /[A-Za-z_]/; +const WORD_PART = /\w/; +const SETTINGS_CLAUSE = /^SETTINGS\s+\w+\s*=/i; +const FORMAT_CLAUSE = /^FORMAT\s+\w+(?:\s*;)*\s*$/i; +const FINAL_SEMICOLONS = /(?:\s*;)+$/; +// What follows the `EXCEPT` of a set operation. After a wildcard, `EXCEPT` names the columns it leaves out. +const SET_OPERATION_OPERANDS = new Set(['SELECT', 'WITH', 'FROM', 'ALL', 'DISTINCT']); + +// Yields the bare words, the comments, and the strings and quoted identifiers of a statement. Words come with their +// nesting depth. +function* scanTokens(sql: string): Generator { + let depth = 0; + let index = 0; + while (index < sql.length) { + const char = sql[index] ?? ''; + const next = sql[index + 1] ?? ''; + const start = index; + if (char === "'" || char === '"' || char === '`') { + index++; + while (index < sql.length && sql[index] !== char) { + index += sql[index] === '\\' ? 2 : 1; + } + index = Math.min(index + 1, sql.length); + yield { kind: 'quoted', text: sql.slice(start, index), start, depth }; + } else if ((char === '-' && next === '-') || char === '#') { + const end = sql.indexOf('\n', index); + index = end === -1 ? sql.length : end + 1; + yield { kind: 'comment', text: sql.slice(start, index), start, depth }; + } else if (char === '/' && next === '*') { + const end = sql.indexOf('*/', index + 2); + index = end === -1 ? sql.length : end + 2; + yield { kind: 'comment', text: sql.slice(start, index), start, depth }; + } else if (char === '(' || char === '[' || char === '{') { + depth++; + index++; + } else if (char === ')' || char === ']' || char === '}') { + depth--; + index++; + } else if (WORD_START.test(char)) { + while (index < sql.length && WORD_PART.test(sql[index] ?? '')) index++; + yield { kind: 'word', text: sql.slice(start, index).toUpperCase(), start, depth }; + } else { + index++; + } + } +} + +function scanWords(sql: string): Token[] { + return [...scanTokens(sql)].filter((token) => token.kind === 'word'); +} + +function tokenRanges(sql: string, kind: Token['kind']): Array<[start: number, end: number]> { + const ranges: Array<[number, number]> = []; + for (const token of scanTokens(sql)) { + if (token.kind === kind) ranges.push([token.start, token.start + token.text.length]); + } + return ranges; +} + +/** commentRanges returns where the comments of a statement are, as `[start, end[` positions. */ +export function commentRanges(sql: string): Array<[start: number, end: number]> { + return tokenRanges(sql, 'comment'); +} + +/** quotedRanges returns where the strings and quoted identifiers of a statement are, as `[start, end[` positions. */ +export function quotedRanges(sql: string): Array<[start: number, end: number]> { + return tokenRanges(sql, 'quoted'); +} + +/** isInRanges reports whether a position is in one of the `[start, end[` ranges. */ +export function isInRanges(position: number, ranges: Array<[start: number, end: number]>): boolean { + return ranges.some(([start, end]) => position >= start && position < end); +} + +/** + * blankComments replaces the comments of a statement with spaces, keeping its line breaks: the positions in the + * statement stay the same. + */ +export function blankComments(sql: string): string { + let blanked = ''; + let position = 0; + for (const [start, end] of commentRanges(sql)) { + blanked += sql.slice(position, start) + sql.slice(start, end).replace(/[^\n]/g, ' '); + position = end; + } + return blanked + sql.slice(position); +} + +/** + * stripFormat removes the final `FORMAT` clause of a statement, and its final semicolons. The plugins choose the + * format of the results themselves, and used to let queries name it. + */ +export function stripFormat(sql: string): string { + const statement = sql.trim().replace(FINAL_SEMICOLONS, ''); + // A comment may follow the clause. + const bare = blankComments(statement); + for (const word of scanWords(statement)) { + if (word.depth === 0 && word.text === 'FORMAT' && FORMAT_CLAUSE.test(bare.slice(word.start))) { + return statement.slice(0, word.start).trimEnd(); + } + } + return statement; +} + +/** + * stripOrderAndLimit removes the final `ORDER BY`, `LIMIT` and `FORMAT` clauses of a `SELECT` statement, so that the + * statement can be aggregated over all its rows in a subquery. A `SETTINGS` clause is kept. It returns undefined + * when the statement can not be rewritten safely: a set operation (`UNION`...), or a `LIMIT ... BY` clause, which + * changes which rows are selected. + */ +export function stripOrderAndLimit(sql: string): string | undefined { + const statement = sql.trim().replace(FINAL_SEMICOLONS, ''); + let orderBy: number | undefined; + let limit: number | undefined; + let settings: number | undefined; + let format: number | undefined; + let previous: Token | undefined; + const bare = blankComments(statement); + const words = scanWords(statement); + for (let index = 0; index < words.length; index++) { + const word = words[index]; + if (!word) continue; + if (word.depth !== 0) { + previous = undefined; + continue; + } + if (word.text === 'UNION' || word.text === 'INTERSECT') return undefined; + if (word.text === 'EXCEPT' && SET_OPERATION_OPERANDS.has(words[index + 1]?.text ?? '')) return undefined; + if (word.text === 'BY') { + if (previous?.text === 'ORDER') { + orderBy = previous.start; + } else if (limit !== undefined) { + // `LIMIT n BY columns` comes after ORDER BY: it is the only BY that can follow a LIMIT. + return undefined; + } + } else if (word.text === 'LIMIT') { + limit = word.start; + } else if (word.text === 'SETTINGS' && SETTINGS_CLAUSE.test(bare.slice(word.start))) { + settings ??= word.start; + } else if (word.text === 'FORMAT' && FORMAT_CLAUSE.test(bare.slice(word.start))) { + format = word.start; + } + previous = word; + } + const tail = Math.min(settings ?? statement.length, format ?? statement.length); + const body = statement.slice(0, Math.min(orderBy ?? tail, limit ?? tail, tail)).trimEnd(); + if (settings === undefined) return body; + const settingsClause = statement.slice(settings, format !== undefined && format > settings ? format : undefined); + return `${body}\n${settingsClause.trim()}`; +} + +const COLUMN_ALIAS = /\sAS\s+(`[^`]+`|"[^"]+"|\w+)\s*$/i; +const COLUMN_NAME = /^(?:\w+\.)*(`[^`]+`|"[^"]+"|\w+)$/; + +// Splits a list on its commas, leaving alone the ones inside parentheses, strings and quoted identifiers. +function splitList(list: string): string[] { + const items: string[] = []; + let depth = 0; + let itemStart = 0; + for (let index = 0; index < list.length; index++) { + const char = list[index]; + if (char === "'" || char === '"' || char === '`') { + index++; + while (index < list.length && list[index] !== char) { + index += list[index] === '\\' ? 2 : 1; + } + } else if (char === '(' || char === '[' || char === '{') { + depth++; + } else if (char === ')' || char === ']' || char === '}') { + depth--; + } else if (char === ',' && depth === 0) { + items.push(list.slice(itemStart, index)); + itemStart = index + 1; + } + } + items.push(list.slice(itemStart)); + return items.map((item) => item.trim()).filter((item) => item !== ''); +} + +// `*`, `table.*` and `COLUMNS('regexp')`, with their modifiers. +const WILDCARD = /^(?:(?:\w+\.)*\*(?:\s|$)|COLUMNS\s*\()/i; +const EXCEPT_MODIFIER = /\bEXCEPT\s+(?:STRICT\s+)?(?:\(([^)]*)\)|(`[^`]+`|"[^"]+"|\w+))/gi; + +export interface SelectedColumns { + /** Names of the aliases and of the plain columns of the statement. */ + names: string[]; + /** True when the statement also returns columns selected with `*`, whose names are unknown. */ + hasWildcard: boolean; + /** Names of the columns its wildcards leave out, with `* EXCEPT (...)`. */ + excluded: string[]; +} + +function unquote(name: string): string { + return name.trim().replace(/^[`"]|[`"]$/g, ''); +} + +/** + * selectedColumns lists the names of the columns returned by a `SELECT` statement, as far as they can be told from + * its text. It returns undefined when the list of the selected columns is not found. + */ +export function selectedColumns(sql: string): SelectedColumns | undefined { + let select: number | undefined; + let from: number | undefined; + for (const word of scanWords(sql)) { + if (word.depth !== 0) continue; + if (word.text === 'SELECT' && select === undefined) { + select = word.start + word.text.length; + } else if (word.text === 'FROM' && select !== undefined) { + from = word.start; + break; + } + } + if (select === undefined) return undefined; + const names: string[] = []; + const excluded: string[] = []; + let hasWildcard = false; + // Comments may hold commas, and follow the names of the columns. + for (const item of splitList( + blankComments(sql) + .slice(select, from) + .replace(/^\s*DISTINCT\s+/i, ''), + )) { + if (WILDCARD.test(item)) { + hasWildcard = true; + for (const [, list, single] of item.matchAll(EXCEPT_MODIFIER)) { + excluded.push(...(list ?? single ?? '').split(',').map(unquote)); + } + continue; + } + const name = (COLUMN_ALIAS.exec(item) ?? COLUMN_NAME.exec(item))?.[1]; + if (name !== undefined) names.push(unquote(name)); + } + return { names, hasWildcard, excluded }; +} diff --git a/clickhouse/src/model/url.ts b/clickhouse/src/model/url.ts new file mode 100644 index 000000000..6d7218f65 --- /dev/null +++ b/clickhouse/src/model/url.ts @@ -0,0 +1,24 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * buildUrl returns the URL of a path of a datasource. A relative datasource URL is the one of the Perses proxy: it + * is resolved against the origin of the page. + */ +export function buildUrl(datasourceUrl: string, path = ''): URL { + const url = new URL(datasourceUrl, window.location.origin); + if (path) { + url.pathname = `${url.pathname.replace(/\/+$/, '')}${path}`; + } + return url; +} diff --git a/clickhouse/src/model/values.test.ts b/clickhouse/src/model/values.test.ts new file mode 100644 index 000000000..ac213dc02 --- /dev/null +++ b/clickhouse/src/model/values.test.ts @@ -0,0 +1,80 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { addLabels, toNumber, toUnixMs, toUnixNano } from './values'; + +describe('toUnixMs', () => { + it('reads ISO date/times and dates', () => { + expect(toUnixMs('2026-01-01T10:00:00.123456789Z')).toBe(Date.UTC(2026, 0, 1, 10, 0, 0, 123)); + expect(toUnixMs('2026-01-01')).toBe(Date.UTC(2026, 0, 1)); + }); + + it('reads a date/time without a zone in the time zone of the column or server', () => { + // Winter: UTC+1. Summer: UTC+2. + expect(toUnixMs('2026-01-01 10:00:00', 'Europe/Paris')).toBe(Date.UTC(2026, 0, 1, 9)); + expect(toUnixMs('2026-07-01 10:00:00.250', 'Europe/Paris')).toBe(Date.UTC(2026, 6, 1, 8, 0, 0, 250)); + // Right after the switch to summer time, at 01:00 UTC. + expect(toUnixMs('2026-03-29 03:30:00', 'Europe/Paris')).toBe(Date.UTC(2026, 2, 29, 1, 30)); + expect(toUnixMs('2026-01-01 10:00:00')).toBe(Date.UTC(2026, 0, 1, 10)); + }); + + it('tells the unit of an epoch number from its magnitude', () => { + const expected = Date.UTC(2026, 0, 1); + expect(toUnixMs(expected / 1000)).toBe(expected); + expect(toUnixMs(expected)).toBe(expected); + expect(toUnixMs(String(expected * 1000))).toBe(expected); + expect(toUnixMs(`${expected}000000`)).toBe(expected); + }); + + it('is NaN for what is not a timestamp', () => { + expect(toUnixMs('yesterday')).toBeNaN(); + expect(toUnixMs(null)).toBeNaN(); + expect(toUnixMs('')).toBeNaN(); + }); +}); + +describe('toUnixNano', () => { + it('keeps the nanoseconds, which a number can not hold', () => { + expect(toUnixNano('2026-01-01T10:00:00.123456789Z')).toBe(1767261600123456789n); + expect(toUnixNano('1767261600123456789')).toBe(1767261600123456789n); + }); +}); + +describe('toNumber', () => { + it('reads quoted 64-bit integers and booleans, and nothing else', () => { + expect(toNumber('42')).toBe(42); + expect(toNumber(true)).toBe(1); + expect(toNumber('')).toBeNull(); + expect(toNumber('abc')).toBeNull(); + expect(toNumber(null)).toBeNull(); + expect(toNumber(NaN)).toBeNull(); + }); +}); + +describe('addLabels', () => { + it('adds one label per key of a map and leaves null values out', () => { + const labels: Record = {}; + + addLabels(labels, 'ServiceName', 'api'); + addLabels(labels, 'Attributes', { 'http.method': 'GET', nested: { code: 200 } }); + addLabels(labels, 'Missing', null); + addLabels(labels, 'List', ['a', 'b']); + + expect(labels).toEqual({ + ServiceName: 'api', + 'Attributes.http.method': 'GET', + 'Attributes.nested.code': '200', + List: '["a","b"]', + }); + }); +}); diff --git a/clickhouse/src/model/values.ts b/clickhouse/src/model/values.ts new file mode 100644 index 000000000..375f58d07 --- /dev/null +++ b/clickhouse/src/model/values.ts @@ -0,0 +1,174 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const NANOS_PER_MILLI = 1_000_000n; + +// `2026-11-26`, `2026-11-26 11:59:14.380493800` (ClickHouse default) or `2026-11-26T11:59:14.380493800Z` (ISO). +const DATE_TIME = + /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?)?(?:\s*(Z|[+-]\d{2}:?\d{2}))?$/; +const UNSIGNED_INTEGER = /^\d+$/; +const DECIMAL_NUMBER = /^-?\d+(?:\.\d+)?$/; + +const zoneFormatters = new Map(); + +function zoneFormatter(timeZone: string): Intl.DateTimeFormat | null { + let formatter = zoneFormatters.get(timeZone); + if (formatter === undefined) { + try { + formatter = new Intl.DateTimeFormat('en-US', { + timeZone, + hourCycle: 'h23', + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + }); + } catch { + formatter = null; + } + zoneFormatters.set(timeZone, formatter); + } + return formatter; +} + +// Offset of the zone, in milliseconds, at the given instant. +function zoneOffset(formatter: Intl.DateTimeFormat, instant: number): number { + const parts: Record = {}; + for (const { type, value } of formatter.formatToParts(instant)) { + parts[type] = Number(value); + } + const wall = Date.UTC( + parts.year ?? 0, + (parts.month ?? 1) - 1, + parts.day ?? 1, + parts.hour ?? 0, + parts.minute ?? 0, + parts.second ?? 0, + ); + return wall - (instant - (((instant % 1000) + 1000) % 1000)); +} + +// Converts a wall-clock time, encoded as if it were UTC, to the instant it designates in an IANA time zone. +function wallTimeToInstant(wallAsUtc: number, timeZone: string): number { + const formatter = zoneFormatter(timeZone); + if (!formatter) return wallAsUtc; + const firstGuess = wallAsUtc - zoneOffset(formatter, wallAsUtc); + return wallAsUtc - zoneOffset(formatter, firstGuess); +} + +interface ParsedDateTime { + /** Whole seconds since the Unix epoch, in milliseconds. */ + secondsMs: number; + /** Fraction of the second, as up to 9 digits. */ + fraction: string; +} + +function parseDateTime(value: string, timeZone: string | undefined): ParsedDateTime | undefined { + const match = DATE_TIME.exec(value.trim()); + if (!match) return undefined; + const [, year, month, day, hour = '00', minute = '00', second = '00', fraction = '', offset] = match; + const wall = Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second)); + if (!Number.isFinite(wall)) return undefined; + if (offset === undefined) { + // Without a zone the value is a wall-clock time of the column or server time zone. + const utc = timeZone === undefined || timeZone === 'UTC' ? wall : wallTimeToInstant(wall, timeZone); + return { secondsMs: utc, fraction }; + } + if (offset === 'Z') return { secondsMs: wall, fraction }; + const sign = offset.startsWith('-') ? -1 : 1; + const digits = offset.slice(1).replace(':', ''); + const offsetMs = sign * (Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2, 4))) * 60_000; + return { secondsMs: wall - offsetMs, fraction }; +} + +// A bare number is an epoch timestamp whose unit is told apart by its magnitude: the four units are at least three +// orders of magnitude apart for any date between 1973 and 5138. +function epochToNano(value: number): bigint | undefined { + if (!Number.isFinite(value)) return undefined; + const magnitude = Math.abs(value); + if (magnitude < 1e11) return BigInt(Math.round(value * 1e3)) * NANOS_PER_MILLI; + if (magnitude < 1e14) return BigInt(Math.round(value)) * NANOS_PER_MILLI; + if (magnitude < 1e17) return BigInt(Math.round(value)) * 1000n; + return BigInt(Math.round(value)); +} + +/** + * toUnixNano reads a ClickHouse date, date/time or epoch number as nanoseconds since the Unix epoch. + * It returns undefined when the value is not a timestamp. `timeZone` applies to values without a zone. + */ +export function toUnixNano(value: unknown, timeZone?: string): bigint | undefined { + if (typeof value === 'number') return epochToNano(value); + if (typeof value !== 'string' || value === '') return undefined; + if (UNSIGNED_INTEGER.test(value)) { + // Quoted 64-bit integers keep their precision: do not go through a double. + const integer = BigInt(value); + if (integer >= 100_000_000_000_000_000n) return integer; + return epochToNano(Number(value)); + } + if (DECIMAL_NUMBER.test(value)) return epochToNano(Number(value)); + const parsed = parseDateTime(value, timeZone); + if (!parsed) return undefined; + return BigInt(parsed.secondsMs) * NANOS_PER_MILLI + BigInt(parsed.fraction.padEnd(9, '0')); +} + +/** + * toUnixMs reads a ClickHouse date, date/time or epoch number as milliseconds since the Unix epoch. + * It returns NaN when the value is not a timestamp. `timeZone` applies to values without a zone. + */ +export function toUnixMs(value: unknown, timeZone?: string): number { + if (typeof value === 'string' && value !== '' && !DECIMAL_NUMBER.test(value)) { + const parsed = parseDateTime(value, timeZone); + if (!parsed) return NaN; + return parsed.secondsMs + Math.floor(Number(parsed.fraction.padEnd(3, '0').slice(0, 3))); + } + const nanos = toUnixNano(value, timeZone); + return nanos === undefined ? NaN : Number(nanos / NANOS_PER_MILLI); +} + +/** toNumber reads a ClickHouse number, including quoted 64-bit integers and booleans, or null when it is not one. */ +export function toNumber(value: unknown): number | null { + if (typeof value === 'number') return Number.isFinite(value) ? value : null; + if (typeof value === 'boolean') return value ? 1 : 0; + if (typeof value !== 'string' || value.trim() === '') return null; + const result = Number(value); + return Number.isFinite(result) ? result : null; +} + +/** isRecord reports whether the value is a JSON object, as ClickHouse returns for `Map`, `Tuple` and `JSON` values. */ +export function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** toText renders a ClickHouse value as text: strings as they are, null as an empty string, the rest as JSON. */ +export function toText(value: unknown): string { + if (value === null || value === undefined) return ''; + if (typeof value === 'string') return value; + return typeof value === 'object' ? JSON.stringify(value) : String(value); +} + +/** + * addLabels flattens a value into labels: an object adds one label per leaf, named `.`, and any other + * value adds a single label. Null values are left out. + */ +export function addLabels(labels: Record, name: string, value: unknown): void { + if (value === null || value === undefined) return; + if (isRecord(value)) { + for (const key of Object.keys(value)) { + addLabels(labels, `${name}.${key}`, value[key]); + } + return; + } + labels[name] = toText(value); +} diff --git a/clickhouse/src/queries/click-house-log-query/ClickHouseLogQuery.tsx b/clickhouse/src/queries/click-house-log-query/ClickHouseLogQuery.tsx index b5ee6ad4f..08c4179c9 100644 --- a/clickhouse/src/queries/click-house-log-query/ClickHouseLogQuery.tsx +++ b/clickhouse/src/queries/click-house-log-query/ClickHouseLogQuery.tsx @@ -12,23 +12,29 @@ // limitations under the License. import type { LogQueryPlugin } from '@perses-dev/plugin-system'; -import { parseVariables } from '@perses-dev/plugin-system'; +import { queryDependencies } from '../../model/execute-query'; import type { ClickHouseLogQuerySpec } from './click-house-log-query-types'; import { ClickHouseLogQueryEditor } from './ClickHouseLogQueryEditor'; import { getClickHouseLogData } from './get-click-house-log-data'; +import { buildVolumeQuery } from './volume-query'; export const ClickHouseLogQuery: LogQueryPlugin = { getLogData: getClickHouseLogData, OptionsEditorComponent: ClickHouseLogQueryEditor, createInitialOptions: () => ({ query: '' }), - dependsOn: (spec) => { - const queryVariables = parseVariables(spec.query); - const allVariables = [...new Set(queryVariables)]; + dependsOn: (spec) => queryDependencies(spec.datasource, spec.query), + createVolumeQuery: (spec) => { + const query = spec.query?.trim() ? buildVolumeQuery(spec.query) : undefined; + if (query === undefined) return null; return { - variables: allVariables, + kind: 'TimeSeriesQuery', + spec: { + plugin: { + kind: 'ClickHouseTimeSeriesQuery', + spec: { datasource: spec.datasource, query, seriesNameFormat: '{{level}}' }, + }, + }, }; }, - // TODO: Implement proper SQL parsing for volume queries - createVolumeQuery: () => null, }; diff --git a/clickhouse/src/queries/click-house-log-query/ClickHouseLogQueryEditor.tsx b/clickhouse/src/queries/click-house-log-query/ClickHouseLogQueryEditor.tsx index 936003d15..f4106e228 100644 --- a/clickhouse/src/queries/click-house-log-query/ClickHouseLogQueryEditor.tsx +++ b/clickhouse/src/queries/click-house-log-query/ClickHouseLogQueryEditor.tsx @@ -12,89 +12,33 @@ // limitations under the License. import { Stack } from '@mui/material'; -import { createModEnterHandler } from '@perses-dev/dashboards'; -import type { DatasourceSelectProps, OptionsEditorProps } from '@perses-dev/plugin-system'; -import { DatasourceSelect, isVariableDatasource } from '@perses-dev/plugin-system'; -import { produce } from 'immer'; +import type { OptionsEditorProps } from '@perses-dev/plugin-system'; import type { ReactElement } from 'react'; -import { useCallback } from 'react'; -import { ClickQLEditor } from '../../components'; -import { queryExample } from '../../components/constants'; -import { DATASOURCE_KIND, DEFAULT_DATASOURCE } from '../constants'; -import { useQueryState } from '../query-editor-model'; +import { ClickHouseDatasourceSelect, QueryExamples, SQLField } from '../../components'; +import { LOG_EXAMPLES } from '../../components/query-examples'; import type { ClickHouseLogQuerySpec } from './click-house-log-query-types'; -type ClickHouseQueryEditorProps = OptionsEditorProps; +type ClickHouseLogQueryEditorProps = OptionsEditorProps; -export function ClickHouseLogQueryEditor(props: ClickHouseQueryEditorProps): ReactElement { - const { onChange, value } = props; - const { datasource } = value; - const selectedDatasource = datasource ?? DEFAULT_DATASOURCE; - const { query, handleQueryChange, handleQueryBlur } = useQueryState(props); - - const handleDatasourceChange: DatasourceSelectProps['onChange'] = (newDatasourceSelection) => { - if (!isVariableDatasource(newDatasourceSelection) && newDatasourceSelection.kind === DATASOURCE_KIND) { - onChange( - produce(value, (draft) => { - draft.datasource = newDatasourceSelection; - }), - ); - return; - } - throw new Error('Got unexpected non ClickHouse datasource selection'); - }; - - // Immediate query execution on Enter or blur - const handleQueryExecute = (query: string): void => { - onChange( - produce(value, (draft) => { - draft.query = query; - }), - ); - }; - - const handleClickHouseQueryChange = useCallback( - (e: string) => { - handleQueryChange(e); - }, - [handleQueryChange], - ); - - const examplesStyle: React.CSSProperties = { - fontSize: '11px', - color: '#777', - backgroundColor: '#f5f5f5', - padding: '8px', - borderRadius: '4px', - fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace', - whiteSpace: 'pre-wrap', - lineHeight: '1.3', - }; +export function ClickHouseLogQueryEditor(props: ClickHouseLogQueryEditorProps): ReactElement { + const { onChange, value, isReadonly } = props; return ( - onChange({ ...value, datasource })} + isReadonly={isReadonly} /> - handleQueryExecute(query))} + onChange({ ...value, query })} placeholder="Enter ClickHouse SQL query" + isReadonly={isReadonly} /> - -
- - Query Examples - -
{queryExample}
-
+
); } diff --git a/clickhouse/src/queries/click-house-log-query/click-house-log-query-types.test.ts b/clickhouse/src/queries/click-house-log-query/click-house-log-query-types.test.ts index 33b08dbfb..733ca22b0 100644 --- a/clickhouse/src/queries/click-house-log-query/click-house-log-query-types.test.ts +++ b/clickhouse/src/queries/click-house-log-query/click-house-log-query-types.test.ts @@ -12,52 +12,27 @@ // limitations under the License. import type { LogQueryContext } from '@perses-dev/plugin-system'; -import type { Mock } from 'vitest'; -import type { ClickHouseDatasourceSpec } from '../../datasources/click-house-datasource'; -import { ClickHouseDatasource } from '../../datasources/click-house-datasource'; -import type { ClickHouseQueryResponse } from '../../model/click-house-client'; +import type { StubClient } from '../../test/stubs'; +import { stubClient, stubDatasourceStore, stubResponse } from '../../test/stubs'; import { ClickHouseLogQuery } from './ClickHouseLogQuery'; -const datasource: ClickHouseDatasourceSpec = { - directUrl: '/test', -}; - -const clickhouseStubClient = ClickHouseDatasource.createClient(datasource, {}); - -// Mock query -clickhouseStubClient.query = vi.fn(async () => { - const stubResponse: ClickHouseQueryResponse = { - status: 'success', - data: [], - }; - return stubResponse as ClickHouseQueryResponse; -}); - -const getDatasourceClient: Mock = vi.fn(() => { - return clickhouseStubClient; -}); - -const createStubContext = (): LogQueryContext => { - const stubLogContext: LogQueryContext = { - datasourceStore: { - getDatasource: vi.fn(), - getDatasourceClient: getDatasourceClient, - listDatasourceSelectItems: vi.fn(), - getLocalDatasources: vi.fn(), - setLocalDatasources: vi.fn(), - getSavedDatasources: vi.fn(), - setSavedDatasources: vi.fn(), - }, +function createContext(client: StubClient): LogQueryContext { + return { + datasourceStore: stubDatasourceStore(client), timeRange: { - end: new Date('2025-01-02T00:00:00.000Z'), start: new Date('2025-01-01T00:00:00.000Z'), + end: new Date('2025-01-02T00:00:00.000Z'), }, variableState: {}, refreshKey: '', }; - return stubLogContext; -}; +} + +const NO_LOGS = stubResponse([ + ['Timestamp', 'DateTime64(9)'], + ['Body', 'String'], +]); describe('ClickHouseLogQuery', () => { it('should properly resolve variable dependencies', () => { @@ -66,7 +41,7 @@ describe('ClickHouseLogQuery', () => { { query: '"SELECT * FROM otel_logs WHERE foo="$foo" AND bar="$bar"', }, - createStubContext(), + createContext(stubClient(() => NO_LOGS)), ); expect(variables).toEqual(['foo', 'bar']); }); @@ -77,21 +52,108 @@ describe('ClickHouseLogQuery', () => { }); it('should run query with interpolated time range', async () => { + const client = stubClient(() => NO_LOGS); + const response = await ClickHouseLogQuery.getLogData( { query: "SELECT * FROM application_logs WHERE timestamp >= '{start}' AND timestamp <= '{end}'", }, - createStubContext(), + createContext(client), ); - expect(clickhouseStubClient.query).toHaveBeenCalledWith({ - start: '2025-01-01 00:00:00', - end: '2025-01-02 00:00:00', - query: - "SELECT * FROM application_logs WHERE timestamp >= '2025-01-01 00:00:00' AND timestamp <= '2025-01-02 00:00:00'", - }); - expect(response.metadata?.executedQueryString).toBe( - "SELECT * FROM application_logs WHERE timestamp >= '2025-01-01 00:00:00' AND timestamp <= '2025-01-02 00:00:00'", + const executed = + "SELECT * FROM application_logs WHERE timestamp >= '2025-01-01 00:00:00' AND timestamp <= '2025-01-02 00:00:00'"; + expect(client.statements()).toEqual([executed]); + expect(response.metadata?.executedQueryString).toBe(executed); + }); + + it('should read the rows of the OpenTelemetry logs table as logs', async () => { + const client = stubClient(() => + stubResponse( + [ + ['Timestamp', 'DateTime64(9)'], + ['TraceId', 'String'], + ['SeverityText', 'LowCardinality(String)'], + ['SeverityNumber', 'UInt8'], + ['ServiceName', 'LowCardinality(String)'], + ['Body', 'String'], + ['LogAttributes', 'Map(LowCardinality(String), String)'], + ], + [ + ['2025-01-01T10:00:00.250000000Z', 'abc', 'ERROR', 17, 'checkout', 'payment failed', { 'app.user': '42' }], + // An event: no line, no severity text. + ['2025-01-01T10:00:01Z', '', '', 9, 'db', '', { 'event.name': 'query' }], + ], + { statistics: { rowsRead: 100, bytesRead: 2048, elapsedMs: 3 } }, + ), ); + + const response = await ClickHouseLogQuery.getLogData({ query: 'SELECT * FROM otel_logs' }, createContext(client)); + + expect(response.logs).toEqual({ + totalCount: 2, + entries: [ + { + // In seconds. + timestamp: Date.UTC(2025, 0, 1, 10) / 1000 + 0.25, + line: 'payment failed', + labels: { + TraceId: 'abc', + SeverityText: 'ERROR', + SeverityNumber: '17', + ServiceName: 'checkout', + 'LogAttributes.app.user': '42', + level: 'ERROR', + }, + }, + { + timestamp: Date.UTC(2025, 0, 1, 10, 0, 1) / 1000, + // Without a line, a log is described by its labels. + line: ' query db 9 info', + // Empty values are left out, and the level comes from the severity number. + labels: { SeverityNumber: '9', ServiceName: 'db', 'LogAttributes.event.name': 'query', level: 'info' }, + }, + ], + metadata: { stats: { linesExamined: 100, bytesExamined: 2048, executionTimeMs: 3 } }, + }); + }); + + it('should warn when the logs have no time column', async () => { + const client = stubClient(() => stubResponse([['Body', 'String']], [['hello']])); + + const response = await ClickHouseLogQuery.getLogData({ query: 'SELECT Body FROM t' }, createContext(client)); + + expect(response.logs?.entries).toEqual([]); + expect(response.logs?.metadata?.notices?.[0]?.message).toMatch(/returns no time column/); + }); + + it('should create the volume query of a log query', () => { + const context = createContext(stubClient(() => NO_LOGS)); + const datasource = { kind: 'ClickHouseDatasource', name: 'logs' } as const; + + expect( + ClickHouseLogQuery.createVolumeQuery?.( + { datasource, query: 'SELECT Timestamp, Body FROM otel_logs ORDER BY Timestamp DESC LIMIT 100' }, + context, + ), + ).toEqual({ + kind: 'TimeSeriesQuery', + spec: { + plugin: { + kind: 'ClickHouseTimeSeriesQuery', + spec: { + datasource, + query: [ + 'SELECT $__timeInterval(`Timestamp`) AS time, count() AS logs', + 'FROM (\nSELECT Timestamp, Body FROM otel_logs\n)', + 'GROUP BY time', + 'ORDER BY time', + ].join('\n'), + seriesNameFormat: '{{level}}', + }, + }, + }, + }); + expect(ClickHouseLogQuery.createVolumeQuery?.({ query: '' }, context)).toBeNull(); }); }); diff --git a/clickhouse/src/queries/click-house-log-query/click-house-log-query-types.ts b/clickhouse/src/queries/click-house-log-query/click-house-log-query-types.ts index a7cc7aec3..e9c65cf15 100644 --- a/clickhouse/src/queries/click-house-log-query/click-house-log-query-types.ts +++ b/clickhouse/src/queries/click-house-log-query/click-house-log-query-types.ts @@ -11,9 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -import type { DatasourceSelector } from '@perses-dev/spec'; +import type { ClickHouseQuerySpec } from '../../model/execute-query'; -export interface ClickHouseLogQuerySpec { - query: string; - datasource?: DatasourceSelector; -} +export type ClickHouseLogQuerySpec = ClickHouseQuerySpec; diff --git a/clickhouse/src/queries/click-house-log-query/get-click-house-log-data.ts b/clickhouse/src/queries/click-house-log-query/get-click-house-log-data.ts index ea81c40bf..40aa27734 100644 --- a/clickhouse/src/queries/click-house-log-query/get-click-house-log-data.ts +++ b/clickhouse/src/queries/click-house-log-query/get-click-house-log-data.ts @@ -12,94 +12,35 @@ // limitations under the License. import type { LogQueryPlugin } from '@perses-dev/plugin-system'; -import { replaceVariables } from '@perses-dev/plugin-system'; -import type { LogData, LogEntry } from '@perses-dev/spec'; -import type { ClickHouseClient, ClickHouseQueryResponse } from '../../model/click-house-client'; -import { formatClickHouseDateTime, replaceTimeRangePlaceholders } from '../../model/click-house-client'; -import { DEFAULT_DATASOURCE } from '../constants'; +import { executeQuery, truncationNotices } from '../../model/execute-query'; import type { ClickHouseLogQuerySpec } from './click-house-log-query-types'; - -function flattenObject( - obj: Record, - parentKey = '', - result: Record = {}, -): Record { - for (const [key, value] of Object.entries(obj)) { - const newKey = parentKey ? `${parentKey}.${key}` : key; - if (value && typeof value === 'object' && !Array.isArray(value)) { - flattenObject(value as Record, newKey, result); - } else { - result[newKey] = value; - } +import { buildLogs } from './logs'; + +export const getClickHouseLogData: LogQueryPlugin['getLogData'] = async ( + spec, + context, + abortSignal, +) => { + const { timeRange } = context; + if (!spec.query?.trim()) { + return { logs: { entries: [], totalCount: 0 }, timeRange }; } - return result; -} - -function convertStreamsToLogs(streams: LogEntry[]): LogData { - const entries: LogEntry[] = streams.map((entry) => { - const flattened = flattenObject(entry as unknown as Record); - - if (!flattened['Timestamp'] && flattened['log_time']) { - flattened['Timestamp'] = flattened['log_time']; - } - - const sortedEntry: Record = {}; - Object.keys(flattened) - .toSorted((a, b) => a.localeCompare(b)) - .forEach((key) => { - sortedEntry[key] = flattened[key]; - }); - - const line = Object.entries(sortedEntry) - .filter(([key]) => key !== 'Timestamp') - .map(([key, value]) => `<${key}> ${value === '' || value === null || value === undefined ? '--' : value}`) - .join(' '); - - return { - timestamp: sortedEntry?.['Timestamp'] as unknown as number, - labels: sortedEntry as Record, - line, - } as LogEntry; - }); - - return { - entries, - totalCount: entries.length, - }; -} - -export const getClickHouseLogData: LogQueryPlugin['getLogData'] = async (spec, context) => { - if (spec.query === undefined || spec.query === null || spec.query === '') { - return { - logs: { entries: [], totalCount: 0 }, - timeRange: { start: context.timeRange.start, end: context.timeRange.end }, - }; + const result = await executeQuery( + spec, + { datasourceStore: context.datasourceStore, variableState: context.variableState, timeRange }, + abortSignal, + ); + const { logs, notices } = buildLogs(result); + const allNotices = [...truncationNotices(result), ...notices]; + if (allNotices.length > 0) { + logs.metadata = { ...logs.metadata, notices: allNotices }; } - const query = replaceVariables(spec.query, context.variableState); - - const client = (await context.datasourceStore.getDatasourceClient( - spec.datasource ?? DEFAULT_DATASOURCE, - )) as ClickHouseClient; - - const { start, end } = context.timeRange; - const startTime = formatClickHouseDateTime(start); - const endTime = formatClickHouseDateTime(end); - const executedQueryString = replaceTimeRangePlaceholders(query, startTime, endTime); - - const response: ClickHouseQueryResponse = await client.query({ - start: startTime, - end: endTime, - query: executedQueryString, - }); - return { - timeRange: { start, end }, - logs: convertStreamsToLogs(response.data as LogEntry[]), - metadata: { - executedQueryString, - }, + timeRange, + logs, + metadata: { executedQueryString: result.executedQueryString }, }; }; diff --git a/clickhouse/src/queries/click-house-log-query/logs.ts b/clickhouse/src/queries/click-house-log-query/logs.ts new file mode 100644 index 000000000..1304b9e70 --- /dev/null +++ b/clickhouse/src/queries/click-house-log-query/logs.ts @@ -0,0 +1,134 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { Labels, LogData, LogEntry, Notice } from '@perses-dev/spec'; + +import type { ClickHouseQueryResponse } from '../../model/click-house-client'; +import type { ClickHouseColumn } from '../../model/click-house-types'; +import { findColumn, getTypeTimeZone, isTimeType } from '../../model/click-house-types'; +import { addLabels, toNumber, toText, toUnixMs } from '../../model/values'; + +/** Names of the column holding the timestamp of a log, by priority, compared case-insensitively. */ +export const LOG_TIME_COLUMNS = ['timestamp', 'log_time', 'time'] as const; +/** Names of the column holding the line of a log, by priority, compared case-insensitively. */ +export const LOG_BODY_COLUMNS = ['body', 'message', 'msg', 'line', 'log'] as const; +/** Names of the column holding the level of a log, by priority, compared case-insensitively. */ +export const LOG_LEVEL_COLUMNS = ['level', 'severitytext', 'severity_text', 'severity'] as const; + +const LEVEL_LABEL = 'level'; +// Lowest severity number of each level, in the OpenTelemetry log data model. +const SEVERITY_LEVELS: ReadonlyArray = [ + [21, 'fatal'], + [17, 'error'], + [13, 'warn'], + [9, 'info'], + [5, 'debug'], + [1, 'trace'], +]; + +/** findLogTimeColumn returns the index of the column holding the timestamp of the logs, or -1. */ +export function findLogTimeColumn(columns: ClickHouseColumn[]): number { + const named = findColumn(columns, LOG_TIME_COLUMNS); + return named !== -1 ? named : columns.findIndex((column) => isTimeType(column.type)); +} + +function severityLevel(severityNumber: unknown): string | undefined { + const severity = toNumber(severityNumber); + if (severity === null) return undefined; + return SEVERITY_LEVELS.find(([lowest]) => severity >= lowest)?.[1]; +} + +export interface BuiltLogs { + logs: LogData; + notices: Notice[]; +} + +/** + * buildLogs converts a result into logs. Each row is a log: its time column is its timestamp, its `Body` + * (or `message`, `line`...) column is its line, and its other columns are its labels. Objects, such as the + * attribute maps of OpenTelemetry, add one label per key, named `.`. A log without a line is + * described by its labels. + * + * The `level` label drives the color of a log: it is taken from the `SeverityText` or `SeverityNumber` column when + * the result has no `level` column. + */ +export function buildLogs(response: ClickHouseQueryResponse): BuiltLogs { + const { columns, rows, statistics } = response; + const time = findLogTimeColumn(columns); + const notices: Notice[] = []; + if (rows.length > 0 && time === -1) { + notices.push({ + type: 'warning', + message: `The query returns no time column: name it ${LOG_TIME_COLUMNS.map((name) => `"${name}"`).join(', ')}, or select a date/time column.`, + }); + return { logs: { entries: [], totalCount: 0 }, notices }; + } + + const timeZone = getTypeTimeZone(columns[time]?.type ?? '') ?? response.timeZone; + const body = findColumn(columns, LOG_BODY_COLUMNS); + const level = findColumn(columns, LOG_LEVEL_COLUMNS); + const severityNumber = findColumn(columns, ['severitynumber']); + const entries: LogEntry[] = []; + let skipped = 0; + + for (const row of rows) { + const timestampMs = toUnixMs(row[time], timeZone); + if (Number.isNaN(timestampMs)) { + skipped++; + continue; + } + const labels: Labels = {}; + for (let index = 0; index < columns.length; index++) { + if (index !== time && index !== body) addLabels(labels, columns[index]?.name ?? '', row[index]); + } + // Empty values, numerous in the OpenTelemetry tables, only add noise to the details of a log. + for (const name of Object.keys(labels)) { + if (labels[name] === '') delete labels[name]; + } + if (labels[LEVEL_LABEL] === undefined) { + const text = level === -1 ? '' : toText(row[level]); + const derived = text || severityLevel(row[severityNumber]); + if (derived) labels[LEVEL_LABEL] = derived; + } + const text = body === -1 ? '' : toText(row[body]); + // A log without a line, such as an OpenTelemetry event, is described by its labels. + const line = + text !== '' + ? text + : Object.keys(labels) + .toSorted() + .map((name) => `<${name}> ${labels[name]}`) + .join(' '); + entries.push({ timestamp: timestampMs / 1000, line, labels }); + } + + if (skipped > 0) { + notices.push({ + type: 'warning', + message: `${skipped} rows were skipped because their "${columns[time]?.name}" column is not a date/time.`, + }); + } + + const logs: LogData = { entries, totalCount: entries.length }; + if (response.truncated) logs.hasMore = true; + if (statistics) { + logs.metadata = { + stats: { + bytesExamined: statistics.bytesRead, + linesExamined: statistics.rowsRead, + executionTimeMs: statistics.elapsedMs, + }, + }; + } + return { logs, notices }; +} diff --git a/clickhouse/src/queries/click-house-log-query/volume-query.test.ts b/clickhouse/src/queries/click-house-log-query/volume-query.test.ts new file mode 100644 index 000000000..9e43faf6d --- /dev/null +++ b/clickhouse/src/queries/click-house-log-query/volume-query.test.ts @@ -0,0 +1,52 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { buildVolumeQuery } from './volume-query'; + +describe('buildVolumeQuery', () => { + it('counts all the logs of the query over time, split by level', () => { + expect( + buildVolumeQuery( + 'SELECT log_time, message, Severity FROM app.logs WHERE $__timeFilter(log_time) ORDER BY log_time DESC LIMIT 500', + ), + ).toBe( + [ + "SELECT $__timeInterval(`log_time`) AS time, if(lower(ifNull(toString(`Severity`), '')) = '', 'unknown', lower(ifNull(toString(`Severity`), ''))) AS level, count() AS logs", + 'FROM (\nSELECT log_time, message, Severity FROM app.logs WHERE $__timeFilter(log_time)\n)', + 'GROUP BY time, level', + 'ORDER BY time', + ].join('\n'), + ); + }); + + it('assumes the columns of the OpenTelemetry logs table behind a wildcard', () => { + expect(buildVolumeQuery('SELECT * FROM otel_logs LIMIT 10')).toContain( + "$__timeInterval(`Timestamp`) AS time, if(lower(ifNull(toString(`SeverityText`), ''))", + ); + // Unless the wildcard leaves them out. + expect(buildVolumeQuery('SELECT * EXCEPT (SeverityText, ResourceAttributes) FROM otel_logs LIMIT 10')).toBe( + [ + 'SELECT $__timeInterval(`Timestamp`) AS time, count() AS logs', + 'FROM (\nSELECT * EXCEPT (SeverityText, ResourceAttributes) FROM otel_logs\n)', + 'GROUP BY time', + 'ORDER BY time', + ].join('\n'), + ); + expect(buildVolumeQuery('SELECT * EXCEPT Timestamp FROM otel_logs')).toBeUndefined(); + }); + + it('gives up when the time column of the logs is unknown or the query can not be cut', () => { + expect(buildVolumeQuery('SELECT message FROM logs')).toBeUndefined(); + expect(buildVolumeQuery('SELECT Timestamp FROM a UNION ALL SELECT Timestamp FROM b')).toBeUndefined(); + }); +}); diff --git a/clickhouse/src/queries/click-house-log-query/volume-query.ts b/clickhouse/src/queries/click-house-log-query/volume-query.ts new file mode 100644 index 000000000..a8e0aac42 --- /dev/null +++ b/clickhouse/src/queries/click-house-log-query/volume-query.ts @@ -0,0 +1,65 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { asSubquery, quoteIdentifier, selectedColumns, stripOrderAndLimit } from '../../model/sql'; +import { LOG_LEVEL_COLUMNS, LOG_TIME_COLUMNS } from './logs'; + +// Columns of the logs table of the OpenTelemetry Collector, assumed to be the ones a `SELECT *` returns. +const OTEL_TIME_COLUMN = 'Timestamp'; +const OTEL_LEVEL_COLUMN = 'SeverityText'; + +function pickColumn(names: string[], candidates: readonly string[]): string | undefined { + for (const candidate of candidates) { + const name = names.find((column) => column.toLowerCase() === candidate); + if (name !== undefined) return name; + } + return undefined; +} + +/** + * buildVolumeQuery derives, from a log query, the time series query counting its logs over time, split by level + * when the logs have one. The log query is counted without its `ORDER BY` and `LIMIT` clauses: the volume is the one + * of all the matching logs, not only of the ones displayed. + * + * It returns undefined when the log query can not be rewritten: its time column is not found, or it can not be + * stripped from its limit. + */ +export function buildVolumeQuery(logQuery: string): string | undefined { + const statement = stripOrderAndLimit(logQuery); + const selected = statement === undefined ? undefined : selectedColumns(statement); + if (statement === undefined || selected === undefined) return undefined; + + // A column of the OpenTelemetry logs table a wildcard is assumed to return, unless it leaves it out. + const behindWildcard = (column: string): string | undefined => + selected.hasWildcard && !selected.excluded.some((name) => name.toLowerCase() === column.toLowerCase()) + ? column + : undefined; + const time = pickColumn(selected.names, LOG_TIME_COLUMNS) ?? behindWildcard(OTEL_TIME_COLUMN); + if (time === undefined) return undefined; + const level = pickColumn(selected.names, LOG_LEVEL_COLUMNS) ?? behindWildcard(OTEL_LEVEL_COLUMN); + + const columns = [`$__timeInterval(${quoteIdentifier(time)}) AS time`]; + if (level !== undefined) { + // Lower case, so that the logs of services writing their levels differently, e.g. ERROR and error, add up. A + // missing level of a Nullable column is an unknown one too. + const text = `lower(ifNull(toString(${quoteIdentifier(level)}), ''))`; + columns.push(`if(${text} = '', 'unknown', ${text}) AS level`); + } + columns.push('count() AS logs'); + return [ + `SELECT ${columns.join(', ')}`, + `FROM ${asSubquery(statement)}`, + `GROUP BY ${level === undefined ? 'time' : 'time, level'}`, + 'ORDER BY time', + ].join('\n'); +} diff --git a/clickhouse/src/queries/click-house-profile-query/ClickHouseProfileQuery.tsx b/clickhouse/src/queries/click-house-profile-query/ClickHouseProfileQuery.tsx new file mode 100644 index 000000000..ecadbc2d0 --- /dev/null +++ b/clickhouse/src/queries/click-house-profile-query/ClickHouseProfileQuery.tsx @@ -0,0 +1,24 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { ProfileQueryPlugin } from '@perses-dev/plugin-system'; + +import type { ClickHouseProfileQuerySpec } from './click-house-profile-query-types'; +import { ClickHouseProfileQueryEditor } from './ClickHouseProfileQueryEditor'; +import { getProfileData } from './get-click-house-profile-data'; + +export const ClickHouseProfileQuery: ProfileQueryPlugin = { + getProfileData, + OptionsEditorComponent: ClickHouseProfileQueryEditor, + createInitialOptions: () => ({ query: '' }), +}; diff --git a/clickhouse/src/queries/click-house-profile-query/ClickHouseProfileQueryEditor.tsx b/clickhouse/src/queries/click-house-profile-query/ClickHouseProfileQueryEditor.tsx new file mode 100644 index 000000000..fa27072f1 --- /dev/null +++ b/clickhouse/src/queries/click-house-profile-query/ClickHouseProfileQueryEditor.tsx @@ -0,0 +1,50 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { Alert, Stack } from '@mui/material'; +import type { OptionsEditorProps } from '@perses-dev/plugin-system'; +import { isVariableDatasource } from '@perses-dev/plugin-system'; +import type { ReactElement } from 'react'; + +import { ClickHouseDatasourceSelect, QueryExamples, SQLField } from '../../components'; +import { PROFILE_EXAMPLES } from '../../components/query-examples'; +import type { ClickHouseProfileQuerySpec } from './click-house-profile-query-types'; + +type ClickHouseProfileQueryEditorProps = OptionsEditorProps; + +export function ClickHouseProfileQueryEditor(props: ClickHouseProfileQueryEditorProps): ReactElement { + const { onChange, value, isReadonly } = props; + + return ( + + onChange({ ...value, datasource })} + isReadonly={isReadonly} + /> + {isVariableDatasource(value.datasource) && ( + + Dashboard variables are not available to profile queries: select a datasource instead of a variable. + + )} + onChange({ ...value, query })} + placeholder="Enter a ClickHouse SQL query returning the samples of the profile" + isReadonly={isReadonly} + /> + + + ); +} diff --git a/clickhouse/src/queries/click-house-profile-query/click-house-profile-query-types.ts b/clickhouse/src/queries/click-house-profile-query/click-house-profile-query-types.ts new file mode 100644 index 000000000..1169ed718 --- /dev/null +++ b/clickhouse/src/queries/click-house-profile-query/click-house-profile-query-types.ts @@ -0,0 +1,16 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { ClickHouseQuerySpec } from '../../model/execute-query'; + +export type ClickHouseProfileQuerySpec = ClickHouseQuerySpec; diff --git a/clickhouse/src/queries/click-house-profile-query/click-house-profile-query.test.ts b/clickhouse/src/queries/click-house-profile-query/click-house-profile-query.test.ts new file mode 100644 index 000000000..2436cd548 --- /dev/null +++ b/clickhouse/src/queries/click-house-profile-query/click-house-profile-query.test.ts @@ -0,0 +1,208 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { ProfileQueryContext } from '@perses-dev/plugin-system'; + +import { ClickHouseError } from '../../model/click-house-client'; +import type { StubClient } from '../../test/stubs'; +import { stubClient, stubDatasourceStore, stubResponse } from '../../test/stubs'; +import { ClickHouseProfileQuery } from './ClickHouseProfileQuery'; +import { buildProfile, buildTimeline } from './profile'; + +function createContext(client: StubClient): ProfileQueryContext { + return { + datasourceStore: stubDatasourceStore(client), + absoluteTimeRange: { + start: new Date('2026-01-01T10:00:00.000Z'), + end: new Date('2026-01-01T10:05:00.000Z'), + }, + }; +} + +const FLAME = stubResponse( + [ + ['stack', 'Array(String)'], + ['samples', 'UInt64'], + ['sum(value)', 'Int64'], + ['any(name)', 'String'], + ['any(unit)', 'String'], + ], + [ + // Frames come from the leaf to the root, as in the OpenTelemetry profiles. + [['c', 'b', 'a'], '2', '10', 'cpu', 'ns'], + [['', 'a'], '1', '5', 'cpu', 'ns'], + ], +); + +const TIMELINE = stubResponse( + [ + ['toUnixTimestamp(toStartOfInterval(toDateTime(time), toIntervalSecond(1)))', 'UInt32'], + ['samples', 'UInt64'], + ['sum(value)', 'Int64'], + ], + [ + [1767261600, '2', '10'], + [1767261602, '1', '5'], + ], +); + +describe('buildProfile', () => { + it('merges the stacks into a flame graph rooted at their outermost frame', () => { + expect(buildProfile(FLAME)).toEqual({ + numTicks: 15, + maxSelf: 10, + name: 'cpu', + units: 'nanoseconds', + stackTrace: { + id: 1, + name: 'total', + level: 0, + start: 0, + end: 15, + total: 15, + self: 0, + children: [ + { + id: 2, + name: 'a', + level: 1, + start: 0, + end: 15, + total: 15, + self: 0, + children: [ + // Frames without a name are kept: they hold a share of the profile. + { id: 3, name: '[unknown]', level: 2, start: 0, end: 5, total: 5, self: 5, children: [] }, + { + id: 4, + name: 'b', + level: 2, + start: 5, + end: 15, + total: 10, + self: 0, + children: [{ id: 5, name: 'c', level: 3, start: 5, end: 15, total: 10, self: 10, children: [] }], + }, + ], + }, + ], + }, + }); + }); + + it('counts the samples when they have no value', () => { + const profile = buildProfile( + stubResponse( + [ + ['stack', 'Array(String)'], + ['samples', 'UInt64'], + ], + [[['a'], '3']], + ), + ); + + expect(profile.numTicks).toBe(3); + expect(profile.units).toBe('count'); + }); + + it('is an empty profile, which the flame chart tells by its root, when there is no sample', () => { + expect(buildProfile(stubResponse([['stack', 'Array(String)']])).stackTrace).toMatchObject({ id: 0, total: 0 }); + }); +}); + +describe('buildTimeline', () => { + const start = Date.UTC(2026, 0, 1, 10); + + it('fills the buckets of the time range, with 0 where there is no sample', () => { + expect(buildTimeline(TIMELINE, start, start + 3000, 1)).toEqual({ + startTime: start / 1000, + durationDelta: 1, + samples: [10, 0, 5, 0], + }); + }); + + it('has no samples when the query returns no time column', () => { + const totals = stubResponse([['samples', 'UInt64']], [['3']]); + + expect(buildTimeline(totals, start, start + 3000, 1).samples).toEqual([]); + }); +}); + +describe('ClickHouseProfileQuery', () => { + it('aggregates the samples of the query by stack and by time bucket', async () => { + const client = stubClient((sql) => (sql.includes('GROUP BY stack') ? FLAME : TIMELINE)); + + const response = await ClickHouseProfileQuery.getProfileData( + { query: 'SELECT Timestamp AS time, FunctionNames AS stack FROM otel_profiles WHERE $__timeFilter(Timestamp)' }, + createContext(client), + ); + + const samples = + 'FROM (\nSELECT Timestamp AS time, FunctionNames AS stack FROM otel_profiles WHERE (Timestamp >= toDateTime(1767261600) AND Timestamp <= toDateTime(1767261900))\n)'; + expect(client.statements()).toEqual([ + [ + "SELECT stack, count() AS samples, COLUMNS('(?i)^value$') APPLY sum, COLUMNS('(?i)^(name|unit)$') APPLY any", + samples, + 'GROUP BY stack', + ].join('\n'), + [ + "SELECT COLUMNS('(?i)^time$') APPLY (t -> toUnixTimestamp(toStartOfInterval(toDateTime(t), INTERVAL 1 second))), count() AS samples, COLUMNS('(?i)^value$') APPLY sum", + samples, + 'GROUP BY ALL', + ].join('\n'), + ]); + expect(response.numTicks).toBe(15); + expect(response.metadata).toMatchObject({ name: 'cpu', units: 'nanoseconds' }); + expect(response.timeline?.samples.slice(0, 3)).toEqual([10, 0, 5]); + }); + + it('warns that dashboard variables are not replaced', async () => { + const client = stubClient((sql) => (sql.includes('GROUP BY stack') ? FLAME : TIMELINE)); + + const response = await ClickHouseProfileQuery.getProfileData( + { query: 'SELECT FunctionNames AS stack FROM otel_profiles WHERE ServiceName = ${service:sqlstring}' }, + createContext(client), + ); + + expect(response.metadata?.notices).toEqual([ + { + type: 'warning', + message: 'Dashboard variables are not available to profile queries: $service is sent as is.', + }, + ]); + }); + + it('refuses a datasource variable, which it can not resolve', async () => { + const client = stubClient((sql) => (sql.includes('GROUP BY stack') ? FLAME : TIMELINE)); + + await expect( + ClickHouseProfileQuery.getProfileData( + { datasource: '$ds', query: 'SELECT FunctionNames AS stack FROM otel_profiles' }, + createContext(client), + ), + ).rejects.toThrow(/select a datasource instead of \$ds/); + expect(client.statements()).toEqual([]); + }); + + it('tells which column a profile query must return', async () => { + const client = stubClient((sql) => { + // Only the flame graph reads the stacks. + if (!sql.includes('GROUP BY stack')) return stubResponse([['samples', 'UInt64']], [['1']]); + throw new ClickHouseError('ClickHouse query failed: Unknown expression identifier `stack`', { code: 47 }); + }); + + await expect( + ClickHouseProfileQuery.getProfileData({ query: 'SELECT 1 AS x' }, createContext(client)), + ).rejects.toThrow(/must return a "stack" column/); + }); +}); diff --git a/clickhouse/src/queries/click-house-profile-query/get-click-house-profile-data.ts b/clickhouse/src/queries/click-house-profile-query/get-click-house-profile-data.ts new file mode 100644 index 000000000..46f0a5474 --- /dev/null +++ b/clickhouse/src/queries/click-house-profile-query/get-click-house-profile-data.ts @@ -0,0 +1,100 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { ProfileQueryPlugin } from '@perses-dev/plugin-system'; +import { isVariableDatasource } from '@perses-dev/plugin-system'; +import type { Notice, ProfileData } from '@perses-dev/spec'; + +import { ClickHouseError } from '../../model/click-house-client'; +import { getIntervalMs, prepareQuery, runStatement, truncationNotices } from '../../model/execute-query'; +import { parseQueryVariables } from '../../model/macros'; +import type { ClickHouseProfileQuerySpec } from './click-house-profile-query-types'; +import { buildProfile, buildTimeline } from './profile'; +import { buildFlameQuery, buildTimelineQuery } from './profile-sql'; + +// Error code of ClickHouse for a column that does not exist. +const UNKNOWN_IDENTIFIER = 47; +// Time range of a profile when the context does not provide one. +const DEFAULT_RANGE_MS = 60 * 60 * 1000; + +function emptyProfile(): ProfileData { + return { + profile: { stackTrace: { id: 0, name: '', level: 0, start: 0, end: 0, total: 0, self: 0, children: [] } }, + numTicks: 0, + maxSelf: 0, + metadata: { spyName: '', sampleRate: 0, units: '', name: '' }, + timeline: { startTime: 0, samples: [], durationDelta: 0 }, + }; +} + +export const getProfileData: ProfileQueryPlugin['getProfileData'] = async ( + spec, + context, + abortSignal, +) => { + if (!spec.query?.trim()) { + return emptyProfile(); + } + // Without the dashboard variables, a datasource variable would be read as the default datasource. + if (isVariableDatasource(spec.datasource)) { + throw new Error( + `Dashboard variables are not available to profile queries: select a datasource instead of ${spec.datasource}.`, + ); + } + + const now = Date.now(); + const timeRange = context.absoluteTimeRange ?? { start: new Date(now - DEFAULT_RANGE_MS), end: new Date(now) }; + // Profile queries are not given the dashboard variables: only the macros are replaced. + const queryContext = { datasourceStore: context.datasourceStore, variableState: {}, timeRange }; + const { sql } = prepareQuery(spec.query, queryContext); + const stepSeconds = getIntervalMs(timeRange, undefined) / 1000; + const flameStatement = buildFlameQuery(sql); + + const [flame, timeline] = await Promise.all([ + runStatement(spec.datasource, flameStatement, queryContext, abortSignal).catch((error: unknown) => { + if (error instanceof ClickHouseError && error.code === UNKNOWN_IDENTIFIER) { + throw new Error( + `${error.message} A profile query must return a "stack" column: the array of the frames of each sample, from the leaf to the root.`, + { cause: error }, + ); + } + throw error; + }), + runStatement(spec.datasource, buildTimelineQuery(sql, stepSeconds), queryContext, abortSignal), + ]); + + const { stackTrace, numTicks, maxSelf, name, units } = buildProfile(flame); + const notices: Notice[] = truncationNotices(flame); + const variables = parseQueryVariables(sql); + if (variables.length > 0) { + notices.push({ + type: 'warning', + message: `Dashboard variables are not available to profile queries: ${variables.map((variable) => `$${variable}`).join(', ')} is sent as is.`, + }); + } + + return { + profile: { stackTrace }, + numTicks, + maxSelf, + timeline: buildTimeline(timeline, timeRange.start.getTime(), timeRange.end.getTime(), stepSeconds), + metadata: { + spyName: '', + sampleRate: 0, + units, + name, + executedQueryString: flameStatement, + ...(notices.length > 0 && { notices }), + }, + }; +}; diff --git a/clickhouse/src/queries/click-house-profile-query/index.ts b/clickhouse/src/queries/click-house-profile-query/index.ts new file mode 100644 index 000000000..7b03720c0 --- /dev/null +++ b/clickhouse/src/queries/click-house-profile-query/index.ts @@ -0,0 +1,17 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export * from './ClickHouseProfileQuery'; +export * from './ClickHouseProfileQueryEditor'; +export * from './get-click-house-profile-data'; +export * from './click-house-profile-query-types'; diff --git a/clickhouse/src/queries/click-house-profile-query/profile-sql.ts b/clickhouse/src/queries/click-house-profile-query/profile-sql.ts new file mode 100644 index 000000000..d6b8a1bf5 --- /dev/null +++ b/clickhouse/src/queries/click-house-profile-query/profile-sql.ts @@ -0,0 +1,43 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { asSubquery } from '../../model/sql'; + +// `COLUMNS('pattern') APPLY function` selects the columns matching the pattern, and nothing when there is none: +// it reads the optional columns of the samples without knowing whether the query returns them. +const SUM_OF_VALUES = "COLUMNS('(?i)^value$') APPLY sum"; + +/** + * buildFlameQuery returns the statement adding up the samples of a profile query by stack. ClickHouse does the + * aggregation, so a profile of millions of samples comes back as one row per distinct stack. + */ +export function buildFlameQuery(profileQuery: string): string { + return [ + `SELECT stack, count() AS samples, ${SUM_OF_VALUES}, COLUMNS('(?i)^(name|unit)$') APPLY any`, + `FROM ${asSubquery(profileQuery)}`, + 'GROUP BY stack', + ].join('\n'); +} + +/** + * buildTimelineQuery returns the statement adding up the samples of a profile query by time bucket. The buckets are + * the first column of its result. Without a `time` column, the result has no bucket: only the total of the samples. + */ +export function buildTimelineQuery(profileQuery: string, stepSeconds: number): string { + const bucket = `t -> toUnixTimestamp(toStartOfInterval(toDateTime(t), INTERVAL ${stepSeconds} second))`; + return [ + `SELECT COLUMNS('(?i)^time$') APPLY (${bucket}), count() AS samples, ${SUM_OF_VALUES}`, + `FROM ${asSubquery(profileQuery)}`, + 'GROUP BY ALL', + ].join('\n'); +} diff --git a/clickhouse/src/queries/click-house-profile-query/profile.ts b/clickhouse/src/queries/click-house-profile-query/profile.ts new file mode 100644 index 000000000..e7b8862c8 --- /dev/null +++ b/clickhouse/src/queries/click-house-profile-query/profile.ts @@ -0,0 +1,173 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { StackTrace, Timeline } from '@perses-dev/spec'; + +import type { ClickHouseQueryResponse } from '../../model/click-house-client'; +import type { ClickHouseColumn } from '../../model/click-house-types'; +import { findColumn } from '../../model/click-house-types'; +import { toNumber, toText } from '../../model/values'; + +const ROOT_FRAME = 'total'; +const UNKNOWN_FRAME = '[unknown]'; +const DEFAULT_UNIT = 'count'; +// Units of the OpenTelemetry profiles, as the flame chart names them. +const UNITS: Record = { + ns: 'nanoseconds', + nanoseconds: 'nanoseconds', + by: 'bytes', + bytes: 'bytes', + '1': 'count', + count: 'count', + '': 'count', +}; + +interface Frame { + name: string; + total: number; + self: number; + children: Map; +} + +function newFrame(name: string): Frame { + return { name, total: 0, self: 0, children: new Map() }; +} + +// The value of the samples: their `sum(value)` column when the query returns values, else their number. +function findValueColumn(columns: ClickHouseColumn[]): number { + const sum = columns.findIndex((column) => column.name.toLowerCase() === 'sum(value)'); + return sum !== -1 ? sum : findColumn(columns, ['samples']); +} + +export interface BuiltProfile { + stackTrace: StackTrace; + /** Total value of the samples. */ + numTicks: number; + /** Highest self value of a frame. */ + maxSelf: number; + name: string; + units: string; +} + +// Lays the frames out: each frame spans its total value, its callees next to each other from its start. +function layout(root: Frame): { stackTrace: StackTrace; maxSelf: number } { + // The flame chart reads an ID of 0 as an empty profile. + let nextId = root.total > 0 ? 1 : 0; + let maxSelf = 0; + const stackTrace: StackTrace = { + id: nextId++, + name: root.name, + level: 0, + start: 0, + end: root.total, + total: root.total, + self: root.self, + children: [], + }; + // Iterative: a recursion as deep as the deepest stack could overflow the call stack. + const pending: Array<{ frame: Frame; node: StackTrace }> = [{ frame: root, node: stackTrace }]; + for (let entry = pending.pop(); entry; entry = pending.pop()) { + const { frame, node } = entry; + maxSelf = Math.max(maxSelf, frame.self); + let start = node.start; + // Sorted by name, so that the same profile always draws the same flame graph. + for (const child of [...frame.children.values()].toSorted((a, b) => (a.name < b.name ? -1 : 1))) { + const childNode: StackTrace = { + id: nextId++, + name: child.name, + level: node.level + 1, + start, + end: start + child.total, + total: child.total, + self: child.self, + children: [], + }; + node.children.push(childNode); + pending.push({ frame: child, node: childNode }); + start += child.total; + } + } + return { stackTrace, maxSelf }; +} + +/** + * buildProfile reads the result of the statement built by `buildFlameQuery`: one row per distinct stack, with the + * frames of the stack from the leaf to the root, as in the OpenTelemetry profiles. + */ +export function buildProfile(response: ClickHouseQueryResponse): BuiltProfile { + const { columns, rows } = response; + const stack = findColumn(columns, ['stack']); + const value = findValueColumn(columns); + const name = findColumn(columns, ['any(name)']); + const unit = findColumn(columns, ['any(unit)']); + const root = newFrame(ROOT_FRAME); + + for (const row of rows) { + const frames: unknown = row[stack]; + const weight = toNumber(row[value]) ?? 0; + if (!Array.isArray(frames) || weight <= 0) continue; + root.total += weight; + let current = root; + for (let index = frames.length - 1; index >= 0; index--) { + const frameName = toText(frames[index]) || UNKNOWN_FRAME; + let child = current.children.get(frameName); + if (!child) { + child = newFrame(frameName); + current.children.set(frameName, child); + } + child.total += weight; + current = child; + } + current.self += weight; + } + + const firstRow = rows[0]; + const rawUnit = firstRow && unit !== -1 ? toText(firstRow[unit]) : ''; + return { + ...layout(root), + numTicks: root.total, + name: firstRow && name !== -1 ? toText(firstRow[name]) : '', + units: UNITS[rawUnit.toLowerCase()] ?? (rawUnit || DEFAULT_UNIT), + }; +} + +/** + * buildTimeline reads the result of the statement built by `buildTimelineQuery` as the value of the samples over + * the time range, one point per time bucket. Buckets without samples are 0. + */ +export function buildTimeline( + response: ClickHouseQueryResponse, + startMs: number, + endMs: number, + stepSeconds: number, +): Timeline { + // Buckets start at multiples of the step, as `toStartOfInterval` aligns them. + const startTime = Math.floor(startMs / 1000 / stepSeconds) * stepSeconds; + const timeline: Timeline = { startTime, samples: [], durationDelta: stepSeconds }; + const { columns } = response; + const value = findValueColumn(columns); + const samples = findColumn(columns, ['samples']); + // The buckets are the column that is not a total: a query without a "time" column has none, and no timeline. + const bucket = columns.findIndex((_column, index) => index !== value && index !== samples); + if (bucket === -1) return timeline; + const count = Math.max(0, Math.floor((endMs / 1000 - startTime) / stepSeconds) + 1); + timeline.samples = Array(count).fill(0); + for (const row of response.rows) { + const time = toNumber(row[bucket]); + const index = time === null ? -1 : Math.round((time - startTime) / stepSeconds); + if (index >= 0 && index < count) { + timeline.samples[index] = toNumber(row[value]) ?? 0; + } + } + return timeline; +} diff --git a/clickhouse/src/queries/click-house-time-series-query/ClickHouseQuery.tsx b/clickhouse/src/queries/click-house-time-series-query/ClickHouseQuery.tsx index 02cf9e428..0a435f05e 100644 --- a/clickhouse/src/queries/click-house-time-series-query/ClickHouseQuery.tsx +++ b/clickhouse/src/queries/click-house-time-series-query/ClickHouseQuery.tsx @@ -12,8 +12,8 @@ // limitations under the License. import type { TimeSeriesQueryPlugin } from '@perses-dev/plugin-system'; -import { parseVariables } from '@perses-dev/plugin-system'; +import { queryDependencies } from '../../model/execute-query'; import type { ClickHouseTimeSeriesQuerySpec } from './click-house-query-types'; import { ClickHouseTimeSeriesQueryEditor } from './ClickHouseQueryEditor'; import { getTimeSeriesData } from './get-click-house-data'; @@ -22,11 +22,6 @@ export const ClickHouseTimeSeriesQuery: TimeSeriesQueryPlugin ({ query: '' }), - dependsOn: (spec) => { - const queryVariables = parseVariables(spec.query); - const allVariables = [...new Set(queryVariables)]; - return { - variables: allVariables, - }; - }, + dependsOn: (spec) => + queryDependencies(spec.datasource, spec.query, spec.exemplarQuery, spec.seriesNameFormat, spec.minStep), }; diff --git a/clickhouse/src/queries/click-house-time-series-query/ClickHouseQueryEditor.tsx b/clickhouse/src/queries/click-house-time-series-query/ClickHouseQueryEditor.tsx index 1ccd43a10..fab966b0b 100644 --- a/clickhouse/src/queries/click-house-time-series-query/ClickHouseQueryEditor.tsx +++ b/clickhouse/src/queries/click-house-time-series-query/ClickHouseQueryEditor.tsx @@ -12,89 +12,62 @@ // limitations under the License. import { Stack } from '@mui/material'; -import { createModEnterHandler } from '@perses-dev/dashboards'; -import type { DatasourceSelectProps, OptionsEditorProps } from '@perses-dev/plugin-system'; -import { DatasourceSelect, isVariableDatasource } from '@perses-dev/plugin-system'; -import { produce } from 'immer'; +import type { OptionsEditorProps } from '@perses-dev/plugin-system'; import type { ReactElement } from 'react'; -import { useCallback } from 'react'; -import { ClickQLEditor } from '../../components'; -import { queryExample } from '../../components/constants'; -import { DATASOURCE_KIND, DEFAULT_DATASOURCE } from '../constants'; -import { useQueryState } from '../query-editor-model'; +import { ClickHouseDatasourceSelect, DraftTextField, QueryExamples, SQLField } from '../../components'; +import { TIME_SERIES_EXAMPLES } from '../../components/query-examples'; import type { ClickHouseTimeSeriesQuerySpec } from './click-house-query-types'; type ClickHouseTimeSeriesQueryEditorProps = OptionsEditorProps; export function ClickHouseTimeSeriesQueryEditor(props: ClickHouseTimeSeriesQueryEditorProps): ReactElement { - const { onChange, value } = props; - const { datasource } = value; - const selectedDatasource = datasource ?? DEFAULT_DATASOURCE; - const { query, handleQueryChange, handleQueryBlur } = useQueryState(props); - - const handleDatasourceChange: DatasourceSelectProps['onChange'] = (newDatasourceSelection) => { - if (!isVariableDatasource(newDatasourceSelection) && newDatasourceSelection.kind === DATASOURCE_KIND) { - onChange( - produce(value, (draft) => { - draft.datasource = newDatasourceSelection; - }), - ); - return; - } - throw new Error('Got unexpected non ClickHouse datasource selection'); - }; - - // Immediate query execution on Enter or blur - const handleQueryExecute = (query: string): void => { - onChange( - produce(value, (draft) => { - draft.query = query; - }), - ); - }; - - const handleClickHouseQueryChange = useCallback( - (e: string) => { - handleQueryChange(e); - }, - [handleQueryChange], - ); - - const examplesStyle: React.CSSProperties = { - fontSize: '11px', - color: '#777', - backgroundColor: '#f5f5f5', - padding: '8px', - borderRadius: '4px', - fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace', - whiteSpace: 'pre-wrap', - lineHeight: '1.3', - }; + const { onChange, value, isReadonly } = props; return ( - onChange({ ...value, datasource })} + isReadonly={isReadonly} /> - handleQueryExecute(query))} + onChange({ ...value, query })} placeholder="Enter ClickHouse SQL query" + isReadonly={isReadonly} /> - -
- - Query Examples - -
{queryExample}
-
+ + onChange({ ...value, seriesNameFormat: seriesNameFormat || undefined })} + placeholder="Example: {{ServiceName}} - {{SpanName}}" + helperText="Text of the legend: each {{label}} is replaced by the value of the label of the series." + isReadonly={isReadonly} + /> + onChange({ ...value, minStep: minStep.trim() || undefined })} + placeholder="Example: 1m" + helperText="Lower bound of the interval of the macros, such as the interval the data is written at." + isReadonly={isReadonly} + fullWidth={false} + sx={{ width: 280, flexShrink: 0 }} + /> + + + onChange({ ...value, exemplarQuery: exemplarQuery.trim() ? exemplarQuery : undefined }) + } + placeholder="Enter a ClickHouse SQL query returning the exemplars of the series" + isReadonly={isReadonly} + /> +
); } diff --git a/clickhouse/src/queries/click-house-time-series-query/click-house-query-types.test.ts b/clickhouse/src/queries/click-house-time-series-query/click-house-query-types.test.ts index 963e0e957..912815f8c 100644 --- a/clickhouse/src/queries/click-house-time-series-query/click-house-query-types.test.ts +++ b/clickhouse/src/queries/click-house-time-series-query/click-house-query-types.test.ts @@ -11,81 +11,50 @@ // See the License for the specific language governing permissions and // limitations under the License. -// TODO: This should be fixed globally in the test setup - -vi.mock('echarts/core'); - import type { TimeSeriesQueryContext } from '@perses-dev/plugin-system'; -import type { DatasourceSpec } from '@perses-dev/spec'; -import type { Mock } from 'vitest'; -import type { ClickHouseDatasourceSpec } from '../../datasources'; -import { ClickHouseDatasource } from '../../datasources'; -import type { ClickHouseQueryResponse } from '../../model/click-house-client'; +import { ClickHouseError } from '../../model/click-house-client'; +import type { StubClient } from '../../test/stubs'; +import { stubClient, stubDatasourceStore, stubResponse } from '../../test/stubs'; import { ClickHouseTimeSeriesQuery } from './ClickHouseQuery'; -const datasource: ClickHouseDatasourceSpec = { - directUrl: '/test', -}; - -const clickhouseStubClient = ClickHouseDatasource.createClient(datasource, {}); - -// Mock query to only return ClickHouse "data" -clickhouseStubClient.query = vi.fn(async () => { - const stubResponse: ClickHouseQueryResponse = { - status: 'success', - data: [ - { time: '2025-09-09 05:18:00', avg_cpu: '2.5', max_memory: 277, service: 'api' }, - { time: '2025-09-09 05:19:00', avg_cpu: '3.5', max_memory: 156102, service: 'api' }, - ], - }; - return stubResponse as ClickHouseQueryResponse; -}); - -const getDatasourceClient: Mock = vi.fn(() => { - return clickhouseStubClient; -}); - -const getDatasource: Mock = vi.fn((): DatasourceSpec => { +function createContext(client: StubClient, overrides: Partial = {}): TimeSeriesQueryContext { return { - default: false, - plugin: { - kind: 'ClickHouseDatasource', - spec: datasource, - }, - }; -}); - -const createStubContext = (): TimeSeriesQueryContext => { - const stubTimeSeriesContext: Partial = { - datasourceStore: { - getDatasource: getDatasource, - getDatasourceClient: getDatasourceClient, - listDatasourceSelectItems: vi.fn(), - getLocalDatasources: vi.fn(), - setLocalDatasources: vi.fn(), - getSavedDatasources: vi.fn(), - setSavedDatasources: vi.fn(), - }, + datasourceStore: stubDatasourceStore(client), timeRange: { - end: new Date('2025-01-02T00:00:00.000Z'), start: new Date('2025-01-01T00:00:00.000Z'), + end: new Date('2025-01-02T00:00:00.000Z'), }, variableState: {}, - }; - return stubTimeSeriesContext as TimeSeriesQueryContext; -}; + ...overrides, + } as TimeSeriesQueryContext; +} + +const SERIES = stubResponse( + [ + ['time', "DateTime('UTC')"], + ['avg_cpu', 'Float64'], + ], + [ + ['2025-01-01T05:18:00Z', 2.5], + ['2025-01-01T05:19:00Z', 3.5], + ], +); describe('ClickHouseTimeSeriesQuery', () => { it('should properly resolve variable dependencies', () => { if (!ClickHouseTimeSeriesQuery.dependsOn) throw new Error('dependsOn is not defined'); const { variables } = ClickHouseTimeSeriesQuery.dependsOn( { - query: '"SELECT * FROM otel_logs WHERE foo="$foo" AND bar="$bar"', + datasource: '$ds', + query: 'SELECT * FROM otel_logs WHERE $__timeFilter(Timestamp) AND foo="$foo" AND bar="$bar"', + exemplarQuery: 'SELECT * FROM otel_traces WHERE service = ${service:sqlstring}', + seriesNameFormat: '{{service}} $env', + minStep: '$resolution', }, - createStubContext(), + createContext(stubClient(() => SERIES)), ); - expect(variables).toEqual(['foo', 'bar']); + expect(variables).toEqual(['ds', 'foo', 'bar', 'service', 'env', 'resolution']); }); it('should create initial options with empty query', () => { @@ -93,92 +62,199 @@ describe('ClickHouseTimeSeriesQuery', () => { expect(initialOptions).toEqual({ query: '' }); }); - it('should run query with interpolated time range and return one series per numeric column', async () => { + it('should run the query with its macros, time range placeholders and variables replaced', async () => { + const client = stubClient(() => SERIES); + const response = await ClickHouseTimeSeriesQuery.getTimeSeriesData( { query: - "SELECT toStartOfMinute(timestamp) as time, avg(cpu_usage) as avg_cpu, max(memory_usage) as max_memory FROM system_metrics WHERE timestamp BETWEEN '{start}' AND '{end}' GROUP BY time ORDER BY time", + "SELECT $__timeInterval(timestamp) AS time, avg(cpu) AS avg_cpu FROM metrics WHERE timestamp BETWEEN '{start}' AND '{end}' AND host IN (${host:sqlstring}) GROUP BY time", + seriesNameFormat: 'CPU of $env', }, - createStubContext(), + createContext(client, { + suggestedStepMs: 50_000, + variableState: { + host: { value: ['a', 'b'], loading: false }, + env: { value: 'prod', loading: false }, + }, + }), ); - expect(clickhouseStubClient.query).toHaveBeenCalledWith({ - start: '2025-01-01 00:00:00', - end: '2025-01-02 00:00:00', - query: - "SELECT toStartOfMinute(timestamp) as time, avg(cpu_usage) as avg_cpu, max(memory_usage) as max_memory FROM system_metrics WHERE timestamp BETWEEN '2025-01-01 00:00:00' AND '2025-01-02 00:00:00' GROUP BY time ORDER BY time", - }); + const executed = + "SELECT toStartOfInterval(toDateTime(timestamp), INTERVAL 60 second) AS time, avg(cpu) AS avg_cpu FROM metrics WHERE timestamp BETWEEN '2025-01-01 00:00:00' AND '2025-01-02 00:00:00' AND host IN ('a','b') GROUP BY time"; + expect(client.statements()).toEqual([executed]); + expect(response.metadata?.executedQueryString).toBe(executed); expect(response.series).toEqual([ { name: 'avg_cpu', + formattedName: 'CPU of prod', + labels: {}, values: [ - [new Date('2025-09-09 05:18:00').getTime(), 2.5], - [new Date('2025-09-09 05:19:00').getTime(), 3.5], + [Date.UTC(2025, 0, 1, 5, 18), 2.5], + [Date.UTC(2025, 0, 1, 5, 19), 3.5], ], }, + ]); + expect(response.stepMs).toBe(60 * 1000); + // The time grid of the points, which charts draw on, starts at the time range. + expect(response.timeRange).toEqual({ + start: new Date('2025-01-01T00:00:00.000Z'), + end: new Date('2025-01-02T00:00:00.000Z'), + }); + }); + + it.each([ + // The panel asks for a point every 5 seconds: the min step, when longer, is the interval of the macros. + { minStep: '1m', interval: 60 }, + { minStep: '$resolution', interval: 120 }, + // The shortest interval is one second: a min step is rounded up to the second. + { minStep: '5500ms', interval: 6 }, + { minStep: '2s', interval: 5 }, + { minStep: '$unset', interval: 5 }, + { minStep: undefined, interval: 5 }, + ])('should not use an interval shorter than the min step $minStep', async ({ minStep, interval }) => { + const client = stubClient(() => SERIES); + + await ClickHouseTimeSeriesQuery.getTimeSeriesData( { - name: 'max_memory', - values: [ - [new Date('2025-09-09 05:18:00').getTime(), 277], - [new Date('2025-09-09 05:19:00').getTime(), 156102], - ], + query: 'SELECT $__timeInterval(t) AS time, count() / $__interval_s AS rate FROM events GROUP BY time', + exemplarQuery: 'SELECT t AS time, $__interval_ms AS value FROM events', + minStep, }, + createContext(client, { + suggestedStepMs: 5_000, + variableState: { + resolution: { value: '2m', loading: false }, + unset: { value: '', loading: false }, + }, + }), + ); + + expect(client.statements()).toEqual([ + `SELECT toStartOfInterval(toDateTime(t), INTERVAL ${interval} second) AS time, count() / ${interval} AS rate FROM events GROUP BY time`, + `SELECT t AS time, ${interval * 1000} AS value FROM events`, ]); - expect(response.stepMs).toBe(60 * 1000); - expect(response.metadata?.executedQueryString).toBe( - "SELECT toStartOfMinute(timestamp) as time, avg(cpu_usage) as avg_cpu, max(memory_usage) as max_memory FROM system_metrics WHERE timestamp BETWEEN '2025-01-01 00:00:00' AND '2025-01-02 00:00:00' GROUP BY time ORDER BY time", + }); + + it('should size the interval on the time range until the panel knows its width', async () => { + const client = stubClient(() => SERIES); + + await ClickHouseTimeSeriesQuery.getTimeSeriesData( + { query: 'SELECT $__interval_s AS value' }, + createContext(client, { suggestedStepMs: 0 }), ); + + // A day in about 300 intervals. + expect(client.statements()).toEqual(['SELECT 300 AS value']); }); - it('should infer daily query step from returned timestamps', async () => { - (clickhouseStubClient.query as Mock).mockResolvedValueOnce({ - status: 'success', - data: [ - { time: '2026-01-01 22:00:00', flights: 80 }, - { time: '2026-01-02 22:00:00', flights: 56 }, - { time: '2026-01-03 22:00:00', flights: 32 }, - ], - }); + it('should ignore the FORMAT clause queries used to end with', async () => { + const client = stubClient(() => SERIES); + + await ClickHouseTimeSeriesQuery.getTimeSeriesData( + { query: 'SELECT time, avg_cpu FROM metrics ORDER BY time FORMAT JSON' }, + createContext(client), + ); + + expect(client.statements()).toEqual(['SELECT time, avg_cpu FROM metrics ORDER BY time']); + }); + + it('should keep the longer interval a panel asks for', async () => { + const client = stubClient(() => SERIES); + + await ClickHouseTimeSeriesQuery.getTimeSeriesData( + { query: 'SELECT $__interval_s AS value', minStep: '1m' }, + createContext(client, { suggestedStepMs: 240_000 }), + ); + + expect(client.statements()).toEqual(['SELECT 300 AS value']); + }); + + it('should reject a min step that is not a duration', async () => { + const client = stubClient(() => SERIES); + const context = createContext(client, { variableState: { resolution: { value: 'fast', loading: false } } }); + + await expect( + ClickHouseTimeSeriesQuery.getTimeSeriesData({ query: 'SELECT 1 AS value', minStep: 'one minute' }, context), + ).rejects.toThrow("Invalid Min Step 'one minute': expected a duration such as 30s or 5m"); + await expect( + ClickHouseTimeSeriesQuery.getTimeSeriesData({ query: 'SELECT 1 AS value', minStep: '$resolution' }, context), + ).rejects.toThrow("Invalid Min Step '$resolution' (resolved to 'fast'): expected a duration such as 30s or 5m"); + expect(client.statements()).toEqual([]); + }); + + it('should attach the exemplars of the exemplar query to the series', async () => { + const client = stubClient((sql) => + sql.includes('otel_traces') + ? stubResponse( + [ + ['time', "DateTime('UTC')"], + ['value', 'Float64'], + ['trace_id', 'String'], + ], + [['2025-01-01T05:18:30Z', 9, 'abc']], + ) + : SERIES, + ); const response = await ClickHouseTimeSeriesQuery.getTimeSeriesData( - { - query: - "SELECT toStartOfDay(timestamp) as time, sum(flights_count) as flights FROM flight WHERE timestamp BETWEEN '{start}' AND '{end}' GROUP BY time ORDER BY time", - }, - createStubContext(), + { query: 'SELECT time, avg_cpu FROM metrics', exemplarQuery: 'SELECT * FROM otel_traces' }, + createContext(client), ); - expect(response.stepMs).toBe(24 * 60 * 60 * 1000); - expect(response.series).toEqual([ + expect(response.exemplars).toEqual([ { - name: 'flights', - values: [ - [new Date('2026-01-01 22:00:00').getTime(), 80], - [new Date('2026-01-02 22:00:00').getTime(), 56], - [new Date('2026-01-03 22:00:00').getTime(), 32], - ], + seriesLabels: {}, + exemplars: [{ timestamp: Date.UTC(2025, 0, 1, 5, 18, 30), value: 9, labels: { trace_id: 'abc' } }], }, ]); }); - it('should keep timezone daily buckets daily across daylight saving time changes', async () => { - (clickhouseStubClient.query as Mock).mockResolvedValueOnce({ - status: 'success', - data: [ - { time: '2026-03-28 22:00:00', flights: 80 }, - { time: '2026-03-29 21:00:00', flights: 56 }, - { time: '2026-03-30 21:00:00', flights: 32 }, - ], + it('should still return the series when their exemplars can not be read', async () => { + const client = stubClient((sql) => { + if (sql.includes('otel_traces')) + throw new ClickHouseError('ClickHouse query failed: Unknown table', { code: 60 }); + return SERIES; }); const response = await ClickHouseTimeSeriesQuery.getTimeSeriesData( + { query: 'SELECT time, avg_cpu FROM metrics', exemplarQuery: 'SELECT * FROM otel_traces' }, + createContext(client), + ); + + expect(response.series).toHaveLength(1); + expect(response.exemplars).toBeUndefined(); + expect(response.metadata?.notices).toEqual([ + { type: 'warning', message: 'Exemplars are not shown. ClickHouse query failed: Unknown table' }, + ]); + }); + + it('should still return the series when the result of their exemplar query is not one of exemplars', async () => { + const client = stubClient((sql) => + sql.includes('otel_traces') ? stubResponse([['trace_id', 'String']], [['abc']]) : SERIES, + ); + + const response = await ClickHouseTimeSeriesQuery.getTimeSeriesData( + { query: 'SELECT time, avg_cpu FROM metrics', exemplarQuery: 'SELECT * FROM otel_traces' }, + createContext(client), + ); + + expect(response.series).toHaveLength(1); + expect(response.exemplars).toBeUndefined(); + expect(response.metadata?.notices).toEqual([ { - query: - "SELECT toStartOfDay(timestamp) as time, sum(flights_count) as flights FROM flight WHERE timestamp BETWEEN '{start}' AND '{end}' GROUP BY time ORDER BY time", + type: 'warning', + message: 'Exemplars are not shown. An exemplar query must return a time column and a numeric "value" column.', }, - createStubContext(), - ); + ]); + }); - expect(response.stepMs).toBe(24 * 60 * 60 * 1000); + it('should not run an empty query', async () => { + const client = stubClient(() => SERIES); + + await expect(ClickHouseTimeSeriesQuery.getTimeSeriesData({ query: ' ' }, createContext(client))).resolves.toEqual({ + series: [], + }); + expect(client.statements()).toEqual([]); }); }); diff --git a/clickhouse/src/queries/click-house-time-series-query/click-house-query-types.ts b/clickhouse/src/queries/click-house-time-series-query/click-house-query-types.ts index 0911df27f..da04f2d32 100644 --- a/clickhouse/src/queries/click-house-time-series-query/click-house-query-types.ts +++ b/clickhouse/src/queries/click-house-time-series-query/click-house-query-types.ts @@ -11,16 +11,23 @@ // See the License for the specific language governing permissions and // limitations under the License. -import type { DatasourceSelector } from '@perses-dev/spec'; +import type { ClickHouseQuerySpec } from '../../model/execute-query'; -export interface ClickHouseTimeSeriesQuerySpec { - query: string; - datasource?: DatasourceSelector; +export interface ClickHouseTimeSeriesQuerySpec extends ClickHouseQuerySpec { + /** + * Format of the names of the series, e.g. `{{ServiceName}} - {{SpanName}}`: each `{{label}}` is replaced by the + * value of the label of the series. + */ + seriesNameFormat?: string; + /** + * Query returning the exemplars of the series. Each row is an exemplar: a time column, a `value` column, the label + * columns of the series it belongs to, and any other column, such as `trace_id`, as a label of the exemplar. + */ + exemplarQuery?: string; + /** + * Lower bound of the interval of the query, which is the value of the `$__interval_s` family of macros: a duration + * such as `1m`, or a variable holding one. Typically the interval the data is written at, when a panel asks for a + * shorter one. + */ + minStep?: string; } - -// TODO: import this type from your datasource or an existing datasource plugin -export type DatasourceQueryResponse = { - status: string; - data: unknown; - warnings?: string[]; -}; diff --git a/clickhouse/src/queries/click-house-time-series-query/get-click-house-data.ts b/clickhouse/src/queries/click-house-time-series-query/get-click-house-data.ts index 3b0387d92..41b13033b 100644 --- a/clickhouse/src/queries/click-house-time-series-query/get-click-house-data.ts +++ b/clickhouse/src/queries/click-house-time-series-query/get-click-house-data.ts @@ -13,124 +13,78 @@ import type { TimeSeriesQueryPlugin } from '@perses-dev/plugin-system'; import { replaceVariables } from '@perses-dev/plugin-system'; -import type { TimeSeries } from '@perses-dev/spec'; +import type { Notice, TimeSeriesData, TimeSeriesExemplars } from '@perses-dev/spec'; -import type { ClickHouseClient, ClickHouseQueryResponse } from '../../model/click-house-client'; -import { formatClickHouseDateTime, replaceTimeRangePlaceholders } from '../../model/click-house-client'; -import type { TimeSeriesEntry } from '../../model/click-house-data-types'; -import { DEFAULT_DATASOURCE } from '../constants'; -import type { ClickHouseTimeSeriesQuerySpec, DatasourceQueryResponse } from './click-house-query-types'; - -const DEFAULT_STEP_MS = 30 * 1000; - -function buildTimeSeries(response?: DatasourceQueryResponse): TimeSeries[] { - const data = response?.data as TimeSeriesEntry[]; - if (!response || !data || data.length === 0) { - return []; - } - - const metricNames = Object.keys(data[0] ?? {}).filter((key) => key !== 'time'); - - return metricNames - .map((metricName) => { - const values: Array<[number, number | null]> = data.map((row: TimeSeriesEntry) => { - const timestamp = new Date(row.time).getTime(); - const value = toTimeSeriesValue(row[metricName]); - return [timestamp, value]; - }); - - return { - name: metricName, - values, - }; - }) - .filter((series) => series.values.some(([, value]) => value !== null)); -} - -function toTimeSeriesValue(value: number | string | null | undefined): number | null { - if (value === null || value === undefined || value === '') { - return null; - } - - const numericValue = Number(value); - return Number.isFinite(numericValue) ? numericValue : null; -} - -function inferStepMs(response?: DatasourceQueryResponse): number { - const data = response?.data as TimeSeriesEntry[]; - if (!response || !data || data.length < 2) { - return DEFAULT_STEP_MS; - } - - const timestamps = data - .map((row: TimeSeriesEntry) => new Date(row.time).getTime()) - .filter(Number.isFinite) - .toSorted((a, b) => a - b); - - if (timestamps.length < 2) { - return DEFAULT_STEP_MS; - } - - const deltas: number[] = []; - for (let i = 1; i < timestamps.length; i++) { - const previous = timestamps[i - 1]; - const current = timestamps[i]; - if (previous === undefined || current === undefined || current <= previous) { - continue; - } - deltas.push(current - previous); - } - - if (deltas.length === 0) { - return DEFAULT_STEP_MS; - } - - const deltaCounts = new Map(); - for (const delta of deltas) { - deltaCounts.set(delta, (deltaCounts.get(delta) ?? 0) + 1); - } - - const inferredStep = Array.from(deltaCounts.entries()).toSorted(([deltaA, countA], [deltaB, countB]) => { - if (countA !== countB) { - return countB - countA; - } - return deltaB - deltaA; - })[0]?.[0]; - - return inferredStep ?? DEFAULT_STEP_MS; -} +import type { ClickHouseQueryContext } from '../../model/execute-query'; +import { executeQuery, truncationNotices } from '../../model/execute-query'; +import type { ClickHouseTimeSeriesQuerySpec } from './click-house-query-types'; +import { getMinStepMs } from './min-step'; +import { buildExemplars, buildTimeSeries } from './time-series'; export const getTimeSeriesData: TimeSeriesQueryPlugin['getTimeSeriesData'] = async ( spec, context, + abortSignal, ) => { - if (spec.query === undefined || spec.query === null || spec.query === '') { + if (!spec.query?.trim()) { return { series: [] }; } - const query = replaceVariables(spec.query, context.variableState); - - const client = (await context.datasourceStore.getDatasourceClient( - spec.datasource ?? DEFAULT_DATASOURCE, - )) as ClickHouseClient; - - const { start, end } = context.timeRange; - const startTime = formatClickHouseDateTime(start); - const endTime = formatClickHouseDateTime(end); - const executedQueryString = replaceTimeRangePlaceholders(query, startTime, endTime); + const { timeRange, variableState } = context; + const queryContext: ClickHouseQueryContext = { + datasourceStore: context.datasourceStore, + variableState, + timeRange, + suggestedStepMs: context.suggestedStepMs, + minStepMs: getMinStepMs(spec.minStep, variableState), + }; - const response: ClickHouseQueryResponse = await client.query({ - start: startTime, - end: endTime, - query: executedQueryString, + // Exemplars are points in time: they have no place in the single value of an instant query. + const exemplarQuery = context.mode === 'instant' ? undefined : spec.exemplarQuery?.trim(); + const [result, exemplarResult] = await Promise.all([ + executeQuery(spec, queryContext, abortSignal), + exemplarQuery + ? // The series are still worth showing when their exemplars can not be read: report the failure as a notice. + executeQuery({ datasource: spec.datasource, query: exemplarQuery }, queryContext, abortSignal).catch( + (error: unknown) => (error instanceof Error ? error : new Error(String(error))), + ) + : undefined, + ]); + + const built = buildTimeSeries(result, { + instant: timeRange.end.getTime(), + rangeStart: timeRange.start.getTime(), + intervalMs: result.intervalMs, + seriesNameFormat: spec.seriesNameFormat ? replaceVariables(spec.seriesNameFormat, variableState) : undefined, }); - return { - series: buildTimeSeries(response), - timeRange: { start, end }, - stepMs: inferStepMs(response), + const notices: Notice[] = [...truncationNotices(result), ...built.notices]; + let exemplars: TimeSeriesExemplars[] = built.exemplars; + if (exemplarResult instanceof Error) { + if (abortSignal?.aborted) throw exemplarResult; + notices.push({ type: 'warning', message: `Exemplars are not shown. ${exemplarResult.message}` }); + } else if (exemplarResult) { + try { + exemplars = [...exemplars, ...buildExemplars(exemplarResult, built.series)]; + notices.push(...truncationNotices(exemplarResult)); + } catch (error) { + notices.push({ + type: 'warning', + message: `Exemplars are not shown. ${error instanceof Error ? error.message : String(error)}`, + }); + } + } + + const data: TimeSeriesData = { + series: built.series, + // The time grid of the series: charts place the points on it. + timeRange: { start: new Date(built.start), end: timeRange.end }, + stepMs: built.stepMs, metadata: { - executedQueryString, + executedQueryString: result.executedQueryString, + ...(notices.length > 0 && { notices }), }, }; + if (exemplars.length > 0) data.exemplars = exemplars; + return data; }; diff --git a/clickhouse/src/queries/click-house-time-series-query/histograms.ts b/clickhouse/src/queries/click-house-time-series-query/histograms.ts new file mode 100644 index 000000000..35e8b7a8c --- /dev/null +++ b/clickhouse/src/queries/click-house-time-series-query/histograms.ts @@ -0,0 +1,174 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { BucketTuple, HistogramValue } from '@perses-dev/spec'; + +import type { ClickHouseColumn } from '../../model/click-house-types'; +import { findColumn } from '../../model/click-house-types'; +import { toNumber } from '../../model/values'; + +// Boundary rules of the buckets, as in the Prometheus API: which of the two bounds belong to the bucket. +const UPPER_INCLUSIVE = 0; +const LOWER_INCLUSIVE = 1; +const BOTH_INCLUSIVE = 3; + +/** + * Columns of an OpenTelemetry histogram, as written by the ClickHouse exporter of the OpenTelemetry Collector: + * `BucketCounts` and `ExplicitBounds` for an explicit bucket histogram, `PositiveBucketCounts` and its companions for + * an exponential one. Indexes are -1 for the columns the result does not have. + */ +export interface HistogramColumns { + count: number; + sum: number; + bucketCounts: number; + explicitBounds: number; + scale: number; + zeroCount: number; + positiveOffset: number; + positiveBucketCounts: number; + negativeOffset: number; + negativeBucketCounts: number; +} + +/** findHistogramColumns returns the histogram columns of a result, or undefined when it holds no histogram. */ +export function findHistogramColumns(columns: ClickHouseColumn[]): HistogramColumns | undefined { + const index = (name: string): number => findColumn(columns, [name]); + const histogram: HistogramColumns = { + count: index('count'), + sum: index('sum'), + bucketCounts: index('bucketcounts'), + explicitBounds: index('explicitbounds'), + scale: index('scale'), + zeroCount: index('zerocount'), + positiveOffset: index('positiveoffset'), + positiveBucketCounts: index('positivebucketcounts'), + negativeOffset: index('negativeoffset'), + negativeBucketCounts: index('negativebucketcounts'), + }; + const isExplicit = histogram.bucketCounts !== -1 && histogram.explicitBounds !== -1; + const isExponential = histogram.positiveBucketCounts !== -1 && histogram.scale !== -1; + return isExplicit || isExponential ? histogram : undefined; +} + +/** histogramColumnIndexes lists the columns that are part of the histogram, and so are neither values nor labels. */ +export function histogramColumnIndexes(histogram: HistogramColumns): Set { + return new Set(Object.values(histogram).filter((index) => index !== -1)); +} + +function toNumbers(value: unknown): number[] | undefined { + if (!Array.isArray(value)) return undefined; + const numbers: number[] = []; + for (const item of value) { + const number = toNumber(item); + if (number === null) return undefined; + numbers.push(number); + } + return numbers; +} + +/** + * explicitBuckets converts the buckets of an explicit bucket histogram. Bucket `i` counts the values in + * `(bounds[i - 1], bounds[i]]`, so the first and the last buckets are unbounded. As a chart can not draw them, they + * are given a bound: 0 for the first one when the bounds are positive, as for a duration or a size, and otherwise the + * width of the neighbouring bucket. Empty buckets are left out. + */ +export function explicitBuckets(bounds: number[], counts: number[]): BucketTuple[] { + if (counts.length !== bounds.length + 1) return []; + const buckets: BucketTuple[] = []; + const first = bounds[0]; + const last = bounds[bounds.length - 1]; + for (let index = 0; index < counts.length; index++) { + const count = counts[index] ?? 0; + if (count <= 0) continue; + let lower = bounds[index - 1]; + let upper = bounds[index]; + if (lower === undefined && upper === undefined) { + // A histogram without bounds has a single bucket holding every value: there is no range to draw. + continue; + } + if (lower === undefined && first !== undefined) { + const width = bounds.length > 1 ? (bounds[1] ?? first) - first : Math.max(Math.abs(first), 1); + lower = first > 0 ? 0 : first - width; + } + if (upper === undefined && last !== undefined) { + const width = bounds.length > 1 ? last - (bounds[bounds.length - 2] ?? last) : Math.max(Math.abs(last), 1); + upper = last + width; + } + buckets.push([UPPER_INCLUSIVE, String(lower), String(upper), String(count)]); + } + return buckets; +} + +/** + * exponentialBuckets converts the buckets of an exponential histogram. With `base = 2^(2^-scale)`, the positive + * bucket at `index` counts the values in `(base^index, base^(index + 1)]`; negative buckets mirror them, and the zero + * bucket counts the values equal to zero. Empty buckets are left out. + */ +export function exponentialBuckets( + scale: number, + zeroCount: number, + positive: { offset: number; counts: number[] }, + negative: { offset: number; counts: number[] }, +): BucketTuple[] { + const factor = 2 ** -scale; + const bound = (index: number): number => 2 ** (index * factor); + const buckets: BucketTuple[] = []; + for (let position = negative.counts.length - 1; position >= 0; position--) { + const count = negative.counts[position] ?? 0; + if (count <= 0) continue; + const index = negative.offset + position; + buckets.push([LOWER_INCLUSIVE, String(-bound(index + 1)), String(-bound(index)), String(count)]); + } + if (zeroCount > 0) { + buckets.push([BOTH_INCLUSIVE, '0', '0', String(zeroCount)]); + } + for (let position = 0; position < positive.counts.length; position++) { + const count = positive.counts[position] ?? 0; + if (count <= 0) continue; + const index = positive.offset + position; + buckets.push([UPPER_INCLUSIVE, String(bound(index)), String(bound(index + 1)), String(count)]); + } + return buckets; +} + +/** readHistogram reads the histogram of a row, or undefined when its columns do not hold a valid one. */ +export function readHistogram(row: unknown[], columns: HistogramColumns): HistogramValue | undefined { + let buckets: BucketTuple[]; + if (columns.bucketCounts !== -1 && columns.explicitBounds !== -1) { + const bounds = toNumbers(row[columns.explicitBounds]); + const counts = toNumbers(row[columns.bucketCounts]); + if (!bounds || !counts) return undefined; + buckets = explicitBuckets(bounds, counts); + } else { + const scale = toNumber(row[columns.scale]); + const positive = toNumbers(row[columns.positiveBucketCounts]); + if (scale === null || !positive) return undefined; + buckets = exponentialBuckets( + scale, + toNumber(row[columns.zeroCount]) ?? 0, + { offset: toNumber(row[columns.positiveOffset]) ?? 0, counts: positive }, + { + offset: toNumber(row[columns.negativeOffset]) ?? 0, + counts: toNumbers(row[columns.negativeBucketCounts]) ?? [], + }, + ); + } + let total = 0; + for (const bucket of buckets) total += Number(bucket[3]); + const sum = toNumber(row[columns.sum]); + return { + count: toNumber(row[columns.count]) ?? total, + sum: sum === null ? 'NaN' : String(sum), + buckets, + }; +} diff --git a/clickhouse/src/queries/click-house-time-series-query/min-step.ts b/clickhouse/src/queries/click-house-time-series-query/min-step.ts new file mode 100644 index 000000000..79cc7123c --- /dev/null +++ b/clickhouse/src/queries/click-house-time-series-query/min-step.ts @@ -0,0 +1,36 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { VariableStateMap } from '@perses-dev/plugin-system'; +import { replaceVariables } from '@perses-dev/plugin-system'; +import { isDurationString, parseDurationString } from '@perses-dev/spec'; +import { milliseconds } from 'date-fns'; + +/** + * getMinStepMs converts the min step of a query, a duration or a variable holding one, to milliseconds. It returns + * undefined when the query has no min step, and throws when the min step is not a duration. + */ +export function getMinStepMs(minStep: string | undefined, variableState: VariableStateMap): number | undefined { + const written = minStep?.trim(); + if (!written) return undefined; + + // A variable without a value sets no min step. + const value = replaceVariables(written, variableState).trim(); + if (value === '') return undefined; + + if (!isDurationString(value)) { + const resolved = value === written ? '' : ` (resolved to '${value}')`; + throw new Error(`Invalid Min Step '${written}'${resolved}: expected a duration such as 30s or 5m`); + } + return milliseconds(parseDurationString(value)); +} diff --git a/clickhouse/src/queries/click-house-time-series-query/time-series.test.ts b/clickhouse/src/queries/click-house-time-series-query/time-series.test.ts new file mode 100644 index 000000000..a68f8b800 --- /dev/null +++ b/clickhouse/src/queries/click-house-time-series-query/time-series.test.ts @@ -0,0 +1,524 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { stubResponse } from '../../test/stubs'; +import { buildExemplars, buildTimeSeries, MAX_SERIES } from './time-series'; + +const TIME: [string, string] = ['time', "DateTime('UTC')"]; +const HOUR = 60 * 60 * 1000; +const rangeStart = Date.UTC(2026, 0, 1, 10); +const options = { instant: rangeStart + HOUR, rangeStart, intervalMs: 15_000 }; + +function at(minutes: number): string { + return new Date(rangeStart + minutes * 60_000).toISOString().replace('.000Z', 'Z'); +} + +function ms(minutes: number): number { + return rangeStart + minutes * 60_000; +} + +function second(seconds: number): string { + return new Date(rangeStart + seconds * 1000).toISOString().replace('.000', ''); +} + +// Step of a series with a point at each of the times, which are in the time zone of Paris. +function stepOf(times: string[]): number { + return buildTimeSeries( + stubResponse( + [ + ['time', "DateTime('Europe/Paris')"], + ['flights', 'UInt32'], + ], + times.map((time) => [time, 1]), + ), + options, + ).stepMs; +} + +describe('buildTimeSeries', () => { + it('returns one series per value of the label columns', () => { + const built = buildTimeSeries( + stubResponse( + [TIME, ['service', 'LowCardinality(String)'], ['region', 'String'], ['requests', 'UInt64']], + [ + [at(0), 'web', 'eu', '5'], + [at(0), 'api', 'eu', '7'], + [at(1), 'api', 'eu', '9'], + ], + ), + options, + ); + + expect(built.series).toEqual([ + { + name: '{service="api", region="eu"}', + labels: { service: 'api', region: 'eu' }, + values: [ + [ms(0), 7], + [ms(1), 9], + ], + }, + { name: '{service="web", region="eu"}', labels: { service: 'web', region: 'eu' }, values: [[ms(0), 5]] }, + ]); + expect(built.stepMs).toBe(60_000); + }); + + it('names the series after their value column when there are several', () => { + const wide = buildTimeSeries( + stubResponse([TIME, ['avg_cpu', 'Float64'], ['max_memory', 'UInt32']], [[at(0), 2.5, 277]]), + options, + ); + const long = buildTimeSeries( + stubResponse([TIME, ['service', 'String'], ['cpu', 'Float64'], ['memory', 'UInt32']], [[at(0), 'api', 2.5, 277]]), + options, + ); + + expect(wide.series.map((series) => series.name)).toEqual(['avg_cpu', 'max_memory']); + expect(long.series.map((series) => series.name)).toEqual(['cpu{service="api"}', 'memory{service="api"}']); + expect(long.series[0]?.labels).toEqual({ __name__: 'cpu', service: 'api' }); + }); + + it('reads a result without a time column as a table: one point per row, in the order of the rows', () => { + const built = buildTimeSeries( + stubResponse( + [ + ['service', 'String'], + ['spans', 'UInt64'], + ], + [ + ['web', '30'], + ['api', '20'], + ['db', '10'], + ], + ), + options, + ); + + expect(built.series.map((series) => [series.name, series.values])).toEqual([ + ['{service="web"}', [[options.instant, 30]]], + ['{service="api"}', [[options.instant, 20]]], + ['{service="db"}', [[options.instant, 10]]], + ]); + // A single step spans the time range: charts do not draw the rows as gaps. + expect(built.stepMs).toBe(HOUR); + }); + + it('keeps every row of a table, even the ones with the same labels', () => { + const built = buildTimeSeries(stubResponse([['n', 'UInt64']], [['1'], ['2'], ['3']]), options); + + expect(built.series.map((series) => [series.name, series.values])).toEqual([ + ['n', [[options.instant, 1]]], + ['n', [[options.instant, 2]]], + ['n', [[options.instant, 3]]], + ]); + expect(built.notices).toEqual([]); + }); + + it('stretches the step of single points so that the grid stays bounded', () => { + const yearAgo = new Date(rangeStart - 365 * 24 * HOUR).toISOString().replace('.000Z', 'Z'); + const built = buildTimeSeries(stubResponse([TIME, ['value', 'Float64']], [[yearAgo, 1]]), { + ...options, + intervalMs: 300_000, + }); + + const slots = (options.instant - built.start) / built.stepMs; + expect(slots).toBeLessThanOrEqual(11_000); + expect(built.series[0]?.values).toHaveLength(1); + }); + + it('formats the name of the series from their labels', () => { + const built = buildTimeSeries( + stubResponse([TIME, ['service', 'String'], ['value', 'Float64']], [[at(0), 'api', 1]]), + { ...options, seriesNameFormat: '{{service}} ({{ missing }})' }, + ); + + expect(built.series[0]?.formattedName).toBe('api ()'); + }); + + it('keeps the name of a series its format gives no name to', () => { + const built = buildTimeSeries(stubResponse([TIME, ['logs', 'UInt64']], [[at(0), '3']]), { + ...options, + seriesNameFormat: '{{level}}', + }); + + expect(built.series[0]).toMatchObject({ name: 'logs' }); + expect(built.series[0]?.formattedName).toBeUndefined(); + }); + + it('flattens maps into labels and ignores the arrays', () => { + const built = buildTimeSeries( + stubResponse( + [TIME, ['Attributes', 'Map(LowCardinality(String), String)'], ['Tags', 'Array(String)'], ['value', 'Float64']], + [[at(0), { state: 'used', 'host.name': 'a' }, ['x'], 1]], + ), + options, + ); + + expect(built.series[0]?.labels).toEqual({ 'Attributes.state': 'used', 'Attributes.host.name': 'a' }); + }); + + it('reads the rows of the metric tables of OpenTelemetry without their bookkeeping columns', () => { + const built = buildTimeSeries( + stubResponse( + [ + ['ServiceName', 'LowCardinality(String)'], + ['MetricName', 'String'], + ['StartTimeUnix', 'DateTime64(9)'], + ['TimeUnix', 'DateTime64(9)'], + ['Value', 'Float64'], + ['Flags', 'UInt32'], + ], + [['api', 'cpu', '2026-01-01T00:00:00Z', at(0), 0.5, 0]], + ), + options, + ); + + expect(built.series).toEqual([ + { + name: '{ServiceName="api", MetricName="cpu"}', + labels: { ServiceName: 'api', MetricName: 'cpu' }, + values: [[ms(0), 0.5]], + }, + ]); + }); + + it('puts the points on a time grid starting at the time range', () => { + const built = buildTimeSeries( + stubResponse( + [TIME, ['value', 'Float64']], + [ + [at(1), 1], + [at(2), 2], + [at(3), 3], + ], + ), + { ...options, rangeStart: rangeStart + 30_000 }, + ); + + expect(built.stepMs).toBe(60_000); + expect(built.start).toBe(ms(0)); + }); + + it('keeps every row of a series with holes at its time', () => { + const response = stubResponse( + [TIME, ['errors', 'UInt64']], + [ + [at(1), '10'], + [at(2), '20'], + [at(7), '30'], + [at(20), '40'], + ], + ); + + const built = buildTimeSeries(response, options); + + // The grid all the rows are on, not the one of their longest hole. + expect(built.stepMs).toBe(60_000); + expect(built.series[0]?.values).toEqual([ + [ms(1), 10], + [ms(2), 20], + [ms(7), 30], + [ms(20), 40], + ]); + expect(built.notices).toEqual([]); + }); + + it('draws rows grouped by a shorter interval than the one they are written at as a line', () => { + // A metric written about every minute, grouped by intervals of 2 seconds. + const seconds = [48, 108, 168, 226, 288, 348, 410, 468]; + const built = buildTimeSeries( + stubResponse( + [TIME, ['value', 'Float64']], + seconds.map((time, index) => [second(time), index]), + ), + { ...options, intervalMs: 2000 }, + ); + + expect(built.stepMs).toBe(60_000); + expect(built.series[0]?.values.map(([timestamp]) => (timestamp - rangeStart) / 1000)).toEqual([ + 48, 108, 168, 228, 288, 348, 408, 468, + ]); + }); + + it('keeps daily rows daily across a daylight saving time change', () => { + expect(stepOf(['2026-01-01 00:00:00', '2026-01-02 00:00:00', '2026-01-03 00:00:00'])).toBe(24 * HOUR); + // The day of the switch to summer time lasts 23 hours, and the one of the switch back 25. + expect(stepOf(['2026-03-28 00:00:00', '2026-03-29 00:00:00', '2026-03-30 00:00:00'])).toBe(24 * HOUR); + expect(stepOf(['2026-10-24 00:00:00', '2026-10-25 00:00:00', '2026-10-26 00:00:00'])).toBe(24 * HOUR); + }); + + it('draws every row of calendar intervals close to its time', () => { + const months = Array.from({ length: 36 }, (_unused, month) => Date.UTC(2023, month, 1)); + const built = buildTimeSeries( + stubResponse( + [ + ['month', 'Date'], + ['revenue', 'UInt32'], + ], + months.map((month, index) => [new Date(month).toISOString().slice(0, 10), index]), + ), + { instant: Date.UTC(2026, 0, 1), rangeStart: Date.UTC(2023, 0, 1), intervalMs: 24 * HOUR }, + ); + + const values = built.series[0]?.values ?? []; + expect(values.map(([, revenue]) => revenue)).toEqual(months.map((_month, index) => index)); + const daysOff = values.map(([timestamp], index) => Math.abs(timestamp - (months[index] ?? 0)) / (24 * HOUR)); + expect(Math.max(...daysOff)).toBeLessThan(4); + // A round step: charts draw the series of several queries on the common divisor of their steps. + expect(built.stepMs).toBe(30.5 * 24 * HOUR); + expect(built.notices).toEqual([]); + }); + + it('keeps the points of series written at about regular intervals in line, whatever their phase', () => { + // Two collectors writing about every minute, half a minute apart. + const first = [0, 61, 120, 181, 240, 299, 360]; + const other = [30, 91, 149, 211, 270, 330, 389]; + const built = buildTimeSeries( + stubResponse( + [TIME, ['host', 'String'], ['load', 'Float64']], + [...first.map((time, index) => [second(time), 'a', index]), ...other.map((time) => [second(time), 'b', 1])], + ), + options, + ); + + expect(built.stepMs).toBe(60_000); + expect(built.series.map((entry) => entry.values.map(([timestamp]) => (timestamp - rangeStart) / 60_000))).toEqual([ + [0, 1, 2, 3, 4, 5, 6], + [1, 2, 3, 4, 5, 6, 7], + ]); + expect(built.notices).toEqual([]); + }); + + it('bounds the time grid of rows at irregular intervals, and warns about the ones it can not draw', () => { + const day = 24 * HOUR; + // Events, to the millisecond: charts would otherwise fill a slot per millisecond of the time range. + const offsets = [0, 1, 2, 5_000, 12_345, 3_600_000, 40_000_000]; + const built = buildTimeSeries( + stubResponse( + [ + ['time', "DateTime64(3, 'UTC')"], + ['duration', 'Float64'], + ], + offsets.map((offset, index) => [new Date(rangeStart + offset).toISOString(), index]), + ), + { instant: rangeStart + day, rangeStart, intervalMs: 300_000 }, + ); + + expect(built.stepMs).toBe(10_000); + expect(built.series[0]?.values).toEqual([ + [rangeStart, 2], + [rangeStart + 10_000, 4], + [rangeStart + 3_600_000, 5], + [rangeStart + 40_000_000, 6], + ]); + expect(built.notices[0]?.message).toMatch(/3 of them are hidden by the next point of their series/); + }); + + it('keeps the gaps of a series and leaves out the series without any value', () => { + const built = buildTimeSeries( + stubResponse( + [TIME, ['a', 'Nullable(Float64)'], ['b', 'Nullable(Float64)']], + [ + [at(0), 1, null], + [at(1), null, null], + ], + ), + options, + ); + + expect(built.series).toEqual([ + { + name: 'a', + labels: { __name__: 'a' }, + values: [ + [ms(0), 1], + [ms(1), null], + ], + }, + ]); + }); + + it('converts the explicit bucket histograms of OpenTelemetry', () => { + const built = buildTimeSeries( + stubResponse( + [ + ['TimeUnix', "DateTime('UTC')"], + ['ServiceName', 'String'], + ['Count', 'UInt64'], + ['Sum', 'Float64'], + ['BucketCounts', 'Array(UInt64)'], + ['ExplicitBounds', 'Array(Float64)'], + ], + [[at(0), 'api', '4', 12.5, ['1', '0', '3'], [2, 4]]], + ), + options, + ); + + expect(built.series).toEqual([ + { + name: '{ServiceName="api"}', + labels: { ServiceName: 'api' }, + // Like a native histogram of Prometheus, the series plots the sum of the observations. + values: [[ms(0), 12.5]], + histograms: [ + [ + ms(0) / 1000, + { + count: 4, + sum: '12.5', + // The unbounded first and last buckets are given bounds, and the empty one is left out. + buckets: [ + [0, '0', '2', '1'], + [0, '4', '6', '3'], + ], + }, + ], + ], + }, + ]); + }); + + it('converts the exponential histograms of OpenTelemetry', () => { + const built = buildTimeSeries( + stubResponse( + [ + ['TimeUnix', "DateTime('UTC')"], + ['Count', 'UInt64'], + ['Sum', 'Float64'], + ['Scale', 'Int32'], + ['ZeroCount', 'UInt64'], + ['PositiveOffset', 'Int32'], + ['PositiveBucketCounts', 'Array(UInt64)'], + ['NegativeOffset', 'Int32'], + ['NegativeBucketCounts', 'Array(UInt64)'], + ], + [[at(0), '5', 9, 0, '1', 0, ['2', '0', '1'], 0, ['1']]], + ), + options, + ); + + expect(built.series[0]?.histograms?.[0]?.[1].buckets).toEqual([ + [1, '-2', '-1', '1'], + [3, '0', '0', '1'], + [0, '1', '2', '2'], + [0, '4', '8', '1'], + ]); + }); + + it('reads the exemplars stored with the data points of OpenTelemetry', () => { + const built = buildTimeSeries( + stubResponse( + [ + ['TimeUnix', "DateTime('UTC')"], + ['ServiceName', 'String'], + ['Value', 'Float64'], + ['Exemplars.TimeUnix', "Array(DateTime64(9, 'UTC'))"], + ['Exemplars.Value', 'Array(Float64)'], + ['Exemplars.TraceId', 'Array(String)'], + ['Exemplars.SpanId', 'Array(String)'], + ['Exemplars.FilteredAttributes', 'Array(Map(String, String))'], + ], + [[at(1), 'api', 3, [at(0)], [0.25], ['abc'], ['def'], [{ route: '/cart' }]]], + ), + options, + ); + + expect(built.exemplars).toEqual([ + { + seriesLabels: { ServiceName: 'api' }, + exemplars: [{ timestamp: ms(0), value: 0.25, labels: { route: '/cart', trace_id: 'abc', span_id: 'def' } }], + }, + ]); + }); + + it('warns about the rows and the series it leaves out', () => { + const notNumeric = buildTimeSeries(stubResponse([TIME, ['value', 'String']], [[at(0), '1']]), options); + const badTime = buildTimeSeries( + stubResponse( + [ + ['time', 'String'], + ['value', 'Float64'], + ], + [ + ['soon', 1], + [at(0), 2], + ], + ), + options, + ); + const tooMany = buildTimeSeries( + stubResponse( + [TIME, ['id', 'String'], ['value', 'Float64']], + Array.from({ length: MAX_SERIES + 1 }, (_unused, index) => [at(0), String(index), 1]), + ), + options, + ); + + expect(notNumeric.notices[0]?.message).toMatch(/no numeric column/); + expect(badTime.series[0]?.values).toEqual([[ms(0), 2]]); + expect(badTime.notices[0]?.message).toMatch(/1 rows were skipped/); + expect(tooMany.series).toHaveLength(MAX_SERIES); + expect(tooMany.notices[0]?.message).toMatch(/only the first 1000 are shown/); + }); +}); + +describe('buildExemplars', () => { + const EXEMPLARS = stubResponse( + [TIME, ['value', 'Float64'], ['service', 'String'], ['trace_id', 'String']], + [ + [at(2), 80, 'api', 't2'], + [at(1), 120, 'api', 't1'], + [at(1), 15, 'web', 't3'], + ], + ); + + it('attaches each exemplar to the series of its label columns', () => { + const series = ['api', 'web'].map((service) => ({ name: service, values: [], labels: { service } })); + + expect(buildExemplars(EXEMPLARS, series)).toEqual([ + { + seriesLabels: { service: 'api' }, + exemplars: [ + { timestamp: ms(1), value: 120, labels: { trace_id: 't1' } }, + { timestamp: ms(2), value: 80, labels: { trace_id: 't2' } }, + ], + }, + { seriesLabels: { service: 'web' }, exemplars: [{ timestamp: ms(1), value: 15, labels: { trace_id: 't3' } }] }, + ]); + }); + + it('attaches the exemplars to the first value column of a query returning several', () => { + // Charts match exemplars and series on all their labels: the name of the value column is one of them. + const built = buildTimeSeries( + stubResponse( + [TIME, ['service', 'String'], ['p50', 'Float64'], ['p95', 'Float64']], + [ + [at(1), 'api', 10, 90], + [at(1), 'web', 5, 20], + ], + ), + options, + ); + + expect(buildExemplars(EXEMPLARS, built.series).map((group) => group.seriesLabels)).toEqual([ + { __name__: 'p50', service: 'api' }, + { __name__: 'p50', service: 'web' }, + ]); + }); + + it('needs a time and a value', () => { + expect(() => buildExemplars(stubResponse([['trace_id', 'String']], [['t1']]), [])).toThrow( + /must return a time column and a numeric "value" column/, + ); + }); +}); diff --git a/clickhouse/src/queries/click-house-time-series-query/time-series.ts b/clickhouse/src/queries/click-house-time-series-query/time-series.ts new file mode 100644 index 000000000..7dccac193 --- /dev/null +++ b/clickhouse/src/queries/click-house-time-series-query/time-series.ts @@ -0,0 +1,621 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { + Exemplar, + Labels, + Notice, + TimeSeries, + TimeSeriesExemplars, + TimeSeriesHistogramTuple, + TimeSeriesValueTuple, +} from '@perses-dev/spec'; + +import type { ClickHouseQueryResponse } from '../../model/click-house-client'; +import type { ClickHouseColumn } from '../../model/click-house-types'; +import { findColumn, findTimeColumn, getTypeTimeZone, isArrayType, isNumericType } from '../../model/click-house-types'; +import { addLabels, toNumber, toText, toUnixMs } from '../../model/values'; +import type { HistogramColumns } from './histograms'; +import { findHistogramColumns, histogramColumnIndexes, readHistogram } from './histograms'; + +/** Maximum number of series returned by a query. */ +export const MAX_SERIES = 1000; + +/** Name of the label holding the name of the value column, when a result has several of them. */ +export const NAME_LABEL = '__name__'; + +const SECOND = 1000; +const MINUTE = 60 * SECOND; +const HOUR = 60 * MINUTE; + +/** Maximum number of slots of the time grid of a result. Charts fill each of them, for every series. */ +const MAX_GRID_SLOTS = 11_000; +/** Maximum number of slots of the time grids of all the series of a result. */ +const MAX_GRID_POINTS = 2_000_000; +// Durations the usual interval of the points is rounded to, from the roundest one. Charts draw the series of several +// queries on the common divisor of their steps, which must not be a tiny one. +const ROUND_STEPS = [12 * HOUR, HOUR, MINUTE, SECOND]; +// How far a rounded interval may be from the usual one. The points of a long series then drift from their slots: a +// few of them are a slot off, which is better than an odd step. +const ROUNDING_TOLERANCE = 0.005; +// How far from the most common interval the intervals of points written at regular intervals are: the months of a +// year, the days around a daylight saving time change, the jitter of a collector. +const INTERVAL_TOLERANCE = 0.15; +// Share of the points that may be in a slot of their usual interval that is already taken. +const SHARED_SLOTS_TOLERANCE = 0.01; + +// Columns of the metric tables of the OpenTelemetry Collector that describe a data point without identifying its +// series nor being its value. They are left out of the rows read from these tables, e.g. with `SELECT *`. +const OTEL_METRIC_COLUMNS = ['metricname', 'timeunix']; +const OTEL_BOOKKEEPING_COLUMNS = new Set([ + 'starttimeunix', + 'flags', + 'scopedroppedattrcount', + 'aggregationtemporality', + 'ismonotonic', + 'resourceschemaurl', + 'scopeschemaurl', + 'metricdescription', + 'min', + 'max', +]); + +/** Columns holding the exemplars of a data point, as written by the ClickHouse exporter of the Collector. */ +interface ExemplarColumns { + time: number; + value: number; + traceId: number; + spanId: number; + attributes: number; +} + +interface ColumnRoles { + /** Index of the time column, or -1 when the rows have no timestamp. */ + time: number; + timeZone: string | undefined; + values: number[]; + labels: number[]; + histogram?: HistogramColumns; + exemplars?: ExemplarColumns; +} + +function findExemplarColumns(columns: ClickHouseColumn[]): ExemplarColumns | undefined { + const time = findColumn(columns, ['exemplars.timeunix']); + const value = findColumn(columns, ['exemplars.value']); + if (time === -1 || value === -1) return undefined; + return { + time, + value, + traceId: findColumn(columns, ['exemplars.traceid']), + spanId: findColumn(columns, ['exemplars.spanid']), + attributes: findColumn(columns, ['exemplars.filteredattributes']), + }; +} + +/** + * classifyColumns tells what each column of a result is: the timestamp of the rows, a value (numeric types), part of + * a histogram or of the exemplars, or a label (everything else). Arrays that are not part of a histogram or of the + * exemplars are ignored: they can not identify a series. + */ +export function classifyColumns(columns: ClickHouseColumn[], serverTimeZone?: string): ColumnRoles { + const time = findTimeColumn(columns); + const timeColumn = columns[time]; + const histogram = findHistogramColumns(columns); + const exemplars = findExemplarColumns(columns); + const isOtelMetric = OTEL_METRIC_COLUMNS.every((name) => findColumn(columns, [name]) !== -1); + const special = histogram ? histogramColumnIndexes(histogram) : new Set(); + + const values: number[] = []; + const labels: number[] = []; + for (let index = 0; index < columns.length; index++) { + const column = columns[index]; + if (!column || index === time || special.has(index)) continue; + if (isOtelMetric && OTEL_BOOKKEEPING_COLUMNS.has(column.name.toLowerCase())) continue; + if (isArrayType(column.type)) continue; + if (isNumericType(column.type)) { + // The values of a histogram are its buckets: its other numbers are not series of their own. + if (!histogram) values.push(index); + } else { + labels.push(index); + } + } + return { + time, + timeZone: (timeColumn && getTypeTimeZone(timeColumn.type)) ?? serverTimeZone, + values, + labels, + histogram, + exemplars, + }; +} + +/** labelsKey returns a key identifying a set of labels whatever their order. */ +export function labelsKey(labels: Labels): string { + return JSON.stringify( + Object.keys(labels) + .toSorted() + .map((name) => [name, labels[name]]), + ); +} + +/** formatSelector writes labels as a selector, e.g. `{service="api", env="prod"}`. */ +function formatSelector(labels: Labels): string { + return `{${Object.entries(labels) + .map(([name, value]) => `${name}=${JSON.stringify(value)}`) + .join(', ')}}`; +} + +/** formatSeriesName replaces the `{{label}}` references of a series name format with the values of the labels. */ +export function formatSeriesName(format: string, labels: Labels): string { + return format.replace(/\{\{\s*(.+?)\s*\}\}/g, (_match, name: string) => labels[name] ?? ''); +} + +interface SeriesGroup { + labels: Labels; + key: string; + /** One list of points per value column. */ + values: TimeSeriesValueTuple[][]; + histograms: TimeSeriesHistogramTuple[]; + exemplars: Exemplar[]; +} + +function readExemplars(row: unknown[], columns: ExemplarColumns, timeZone: string | undefined): Exemplar[] { + const times = row[columns.time]; + const values = row[columns.value]; + if (!Array.isArray(times) || !Array.isArray(values)) return []; + const traceIds: unknown = row[columns.traceId]; + const spanIds: unknown = row[columns.spanId]; + const attributes: unknown = row[columns.attributes]; + const exemplars: Exemplar[] = []; + for (let index = 0; index < values.length; index++) { + const value = toNumber(values[index]); + const timestamp = toUnixMs(times[index], timeZone); + if (value === null || Number.isNaN(timestamp)) continue; + const labels: Labels = {}; + if (Array.isArray(attributes)) { + for (const [name, attribute] of Object.entries(attributes[index] ?? {})) { + labels[name] = toText(attribute); + } + } + const traceId = Array.isArray(traceIds) ? toText(traceIds[index]) : ''; + const spanId = Array.isArray(spanIds) ? toText(spanIds[index]) : ''; + if (traceId) labels.trace_id = traceId; + if (spanId) labels.span_id = spanId; + exemplars.push({ timestamp, value, labels }); + } + return exemplars; +} + +function greatestCommonDivisor(a: number, b: number): number { + let [dividend, divisor] = [a, b]; + while (divisor !== 0) { + [dividend, divisor] = [divisor, dividend % divisor]; + } + return dividend; +} + +// The intervals between the consecutive points of each series, in whole milliseconds. They are measured within +// each series: series written at different times of the same interval do not shrink them. +function intervalsOf(series: TimeSeries[]): number[] { + const intervals: number[] = []; + for (const { values } of series) { + for (let index = 1; index < values.length; index++) { + const interval = Math.round((values[index]?.[0] ?? 0) - (values[index - 1]?.[0] ?? 0)); + if (interval > 0) intervals.push(interval); + } + } + return intervals; +} + +// The interval the points are usually at, when most of them are at about the same one: the average of the intervals +// close to the most common one, rounded to a round duration when it is close to one. `longest` is the number of +// intervals of the longest series. +function usualInterval(intervals: number[], longest: number): number | undefined { + const counts = new Map(); + for (const interval of intervals) { + counts.set(interval, (counts.get(interval) ?? 0) + 1); + } + let mostCommon = 0; + let mostCommonCount = 0; + for (const [interval, count] of counts) { + // The shortest of the most common ones: a longer one is a hole in a series. + if (count > mostCommonCount || (count === mostCommonCount && interval < mostCommon)) { + mostCommon = interval; + mostCommonCount = count; + } + } + let sum = 0; + let count = 0; + for (const interval of intervals) { + if (Math.abs(interval - mostCommon) <= mostCommon * INTERVAL_TOLERANCE) { + sum += interval; + count++; + } + } + if (count * 2 <= intervals.length) return undefined; + + const average = sum / count; + // A short series can not tell its interval precisely, e.g. three days around a daylight saving time change: its + // points may be a quarter of a slot off at its end. + const tolerance = Math.max(ROUNDING_TOLERANCE, 1 / (4 * longest)); + for (const unit of ROUND_STEPS) { + const rounded = Math.round(average / unit) * unit; + if (rounded > 0 && Math.abs(rounded - average) <= average * tolerance) return rounded; + } + return Math.max(1, Math.round(average)); +} + +// The smallest of 1, 2, 5, 10, 20, 50... that is at least a number: a step stays round when it is stretched. +function roundMultiple(least: number): number { + for (let magnitude = 1; ; magnitude *= 10) { + for (const factor of [1, 2, 5]) { + if (magnitude * factor >= least) return magnitude * factor; + } + } +} + +// Whole seconds keep the timestamps of the histograms, which are in seconds, exact. +function gridAnchor(first: number, stepMs: number): number { + return stepMs % SECOND === 0 ? Math.floor(first / SECOND) * SECOND : first; +} + +// Number of slots between the first point of a series and another one of its points, on a time grid. +function slotsAfter(first: number, timestamp: number, stepMs: number): number { + return Math.round((timestamp - first) / stepMs); +} + +// Counts the points of the series that are in the same slot of a time grid as the point before them. +function countSharedSlots(series: TimeSeries[], stepMs: number): number { + let shared = 0; + for (const { values } of series) { + const first = values[0]?.[0] ?? 0; + let previous: number | undefined; + for (const [timestamp] of values) { + const slot = slotsAfter(first, timestamp, stepMs); + if (slot === previous) shared++; + previous = slot; + } + } + return shared; +} + +/** + * chooseStepMs returns the step of the time grid the points of the series are put on. Charts draw each series on + * this grid, one point per slot, and only join the points of consecutive slots: the step is the interval between + * two points. + * + * - When most points are at about the same interval, it is this interval: a metric written every minute and + * grouped by shorter intervals, the points of a collector, the months of a year. Close to no points may share a + * slot. + * - Else it is the common divisor of the intervals between the points, the grid all of them are exactly on: a + * series with more holes than points keeps its points where they are. + * + * The step is never so short that charts would fill more slots than they can. + */ +function chooseStepMs(series: TimeSeries[], first: number, last: number, options: BuildTimeSeriesOptions): number { + const stepMs = naturalStepMs(series, options); + // A multiple of the step keeps the points that are on its grid on the one of the longer step. + const maxSlots = Math.min(MAX_GRID_SLOTS, Math.max(1, Math.floor(MAX_GRID_POINTS / series.length))); + const extent = Math.max(options.instant, last) - Math.min(options.rangeStart, first); + return stepMs * roundMultiple(extent / (stepMs * maxSlots)); +} + +// The step the points of the series are at, before it is stretched to fit the charts. +function naturalStepMs(series: TimeSeries[], options: BuildTimeSeriesOptions): number { + const intervals = intervalsOf(series); + // A single point per series tells nothing. + if (intervals.length === 0) return options.intervalMs; + + let longest = 1; + for (const { values } of series) { + longest = Math.max(longest, values.length - 1); + } + const divisor = intervals.reduce(greatestCommonDivisor); + const usual = usualInterval(intervals, longest); + // The drift of points written slightly more often than their usual interval puts a few of them in a slot that is + // already taken. More of them means that the points have no usual interval. + const fits = + usual !== undefined && + usual >= 2 * divisor && + countSharedSlots(series, usual) <= intervals.length * SHARED_SLOTS_TOLERANCE; + return fits ? usual : divisor; +} + +// Moves the points of a series onto the time grid `start + n * stepMs` the charts draw on: its first point to the +// nearest slot, and the next ones as many slots after it as they are steps after it. Counting from the first point +// rather than from the start of the grid keeps a series written halfway between two slots on one side of them. +// Points sharing a slot are merged, the last one winning: without this, a chart would shift each of them to the +// next free slot. +function alignToGrid(points: T[], start: number, stepMs: number, scale = 1): T[] { + const first = (points[0]?.[0] ?? 0) * scale; + const firstSlot = Math.round((first - start) / stepMs); + const aligned: T[] = []; + let lastSlot: number | undefined; + for (const point of points) { + const slot = firstSlot + slotsAfter(first, point[0] * scale, stepMs); + const moved = [(start + slot * stepMs) / scale, point[1]] as T; + if (slot === lastSlot) { + aligned[aligned.length - 1] = moved; + } else { + aligned.push(moved); + lastSlot = slot; + } + } + return aligned; +} + +function byTime(points: T[]): T[] { + for (let index = 1; index < points.length; index++) { + if ((points[index]?.[0] ?? 0) < (points[index - 1]?.[0] ?? 0)) { + return points.toSorted((a, b) => a[0] - b[0]); + } + } + return points; +} + +export interface BuildTimeSeriesOptions { + /** Timestamp, in milliseconds, of the rows of a result without a time column. */ + instant: number; + /** Start of the time range, in milliseconds: the time grid of the series starts at or right before it. */ + rangeStart: number; + /** Interval of the query, in milliseconds: the step of the series whose points do not tell their interval. */ + intervalMs: number; + seriesNameFormat?: string; +} + +export interface BuiltTimeSeries { + series: TimeSeries[]; + exemplars: TimeSeriesExemplars[]; + /** Start of the time grid of the series, in milliseconds. */ + start: number; + stepMs: number; + notices: Notice[]; +} + +/** + * buildTimeSeries converts a result into time series. + * + * - The rows are grouped by the values of their label columns: there is one series per group and value column. + * - Without label columns, a series is named after its value column. With them, it is named after its labels, and + * after its value column too when there are several. + * - A result without a time column is a table: each row is a series of its own, with a single point at the end of + * the time range, and the series keep the order of the rows. + */ +export function buildTimeSeries(response: ClickHouseQueryResponse, options: BuildTimeSeriesOptions): BuiltTimeSeries { + const { columns, rows } = response; + const roles = classifyColumns(columns, response.timeZone); + const notices: Notice[] = []; + const isTable = roles.time === -1; + const groups = new Map(); + // Rows of a series come with the same raw label values: canonicalize the labels once per distinct combination. + const groupsByRawLabels = new Map(); + let skipped = 0; + + for (const row of rows) { + const timestamp = isTable ? options.instant : toUnixMs(row[roles.time], roles.timeZone); + if (Number.isNaN(timestamp)) { + skipped++; + continue; + } + const rawKey = roles.labels.length === 0 ? '' : JSON.stringify(roles.labels.map((index) => row[index])); + // The rows of a table are all at the same time: the ones with the same labels are not points of one series. + let group = isTable ? undefined : groupsByRawLabels.get(rawKey); + if (!group) { + const labels: Labels = {}; + for (const index of roles.labels) { + addLabels(labels, columns[index]?.name ?? '', row[index]); + } + const key = labelsKey(labels); + group = isTable ? undefined : groups.get(key); + if (!group) { + group = { + labels, + key, + values: roles.values.map(() => []), + histograms: [], + exemplars: [], + }; + groups.set(isTable ? String(groups.size) : key, group); + } + if (!isTable) groupsByRawLabels.set(rawKey, group); + } + for (let position = 0; position < roles.values.length; position++) { + group.values[position]?.push([timestamp, toNumber(row[roles.values[position] ?? -1])]); + } + if (roles.histogram) { + const histogram = readHistogram(row, roles.histogram); + if (histogram) group.histograms.push([timestamp / SECOND, histogram]); + } + if (roles.exemplars) { + for (const exemplar of readExemplars(row, roles.exemplars, roles.timeZone)) { + group.exemplars.push(exemplar); + } + } + } + + if (skipped > 0) { + notices.push({ + type: 'warning', + message: `${skipped} rows were skipped because their "${columns[roles.time]?.name}" column is not a date/time.`, + }); + } + if (rows.length > 0 && roles.values.length === 0 && !roles.histogram) { + notices.push({ + type: 'warning', + message: 'The query returns no numeric column: cast the columns to plot to a number type such as Float64.', + }); + } + + // The series of a table keep the order of its rows, which the query chose, e.g. to list a top 10. The ones of a + // time series result are sorted by labels: the order of their first rows changes from one refresh to the next. + const sortedGroups = isTable + ? [...groups.values()] + : [...groups.values()].toSorted((a, b) => (a.key < b.key ? -1 : Number(a.key > b.key))); + const hasLabels = roles.labels.length > 0; + const severalValues = roles.values.length > 1; + const series: TimeSeries[] = []; + const exemplars: TimeSeriesExemplars[] = []; + + const addSeries = ( + group: SeriesGroup, + valueColumn: string | undefined, + values: TimeSeriesValueTuple[], + histograms?: TimeSeriesHistogramTuple[], + ): void => { + const labels: Labels = + valueColumn !== undefined && severalValues ? { [NAME_LABEL]: valueColumn, ...group.labels } : { ...group.labels }; + const selector = hasLabels ? formatSelector(group.labels) : ''; + const name = valueColumn !== undefined && (severalValues || !hasLabels) ? `${valueColumn}${selector}` : selector; + const entry: TimeSeries = { name, values: byTime(values), labels }; + // A format that only reads labels the series does not have names nothing: the series keeps its name. + const formattedName = options.seriesNameFormat ? formatSeriesName(options.seriesNameFormat, labels).trim() : ''; + if (formattedName !== '') entry.formattedName = formattedName; + if (histograms) entry.histograms = byTime(histograms); + series.push(entry); + if (group.exemplars.length > 0 && series.length <= MAX_SERIES) { + exemplars.push({ + seriesLabels: labels, + exemplars: group.exemplars.toSorted((a, b) => a.timestamp - b.timestamp), + }); + // The exemplars of a row belong to the first series of its group. + group.exemplars = []; + } + }; + + if (roles.histogram) { + for (const group of sortedGroups) { + if (group.histograms.length === 0) continue; + // A histogram series plots the sum of its observations, like a native histogram of Prometheus. + const values = group.histograms.map(([time, histogram]): TimeSeriesValueTuple => { + const sum = Number(histogram.sum); + return [time * SECOND, Number.isFinite(sum) ? sum : null]; + }); + addSeries(group, undefined, values, group.histograms); + } + } else { + for (let position = 0; position < roles.values.length; position++) { + const valueColumn = columns[roles.values[position] ?? -1]?.name ?? ''; + for (const group of sortedGroups) { + const values = group.values[position] ?? []; + if (values.some(([, value]) => value !== null)) addSeries(group, valueColumn, values); + } + } + } + + if (series.length > MAX_SERIES) { + notices.push({ + type: 'warning', + message: `The query returns ${series.length} series: only the first ${MAX_SERIES} are shown. Drop the label columns with too many values, or cast them to a number if they are values.`, + }); + series.length = MAX_SERIES; + } + + let first = Infinity; + let last = -Infinity; + for (const { values } of series) { + first = Math.min(first, values[0]?.[0] ?? Infinity); + last = Math.max(last, values.at(-1)?.[0] ?? -Infinity); + } + // A table has a single point per series, at the end of the time range: one step spans the whole range. + const stepMs = isTable + ? Math.max(options.instant - options.rangeStart, 1) + : chooseStepMs(series, first, last, options); + + // Anchor the time grid on the first point, then extend it back to the start of the time range. + let start = options.rangeStart; + if (Number.isFinite(first)) { + const anchor = gridAnchor(first, stepMs); + start = anchor - Math.max(0, Math.ceil((anchor - options.rangeStart) / stepMs)) * stepMs; + let merged = 0; + for (const entry of series) { + const pointCount = entry.values.length; + entry.values = alignToGrid(entry.values, start, stepMs); + merged += pointCount - entry.values.length; + if (entry.histograms) entry.histograms = alignToGrid(entry.histograms, start, stepMs, SECOND); + } + if (merged > 0) { + notices.push({ + type: 'warning', + message: `The query returns points too close to each other to be drawn: ${merged} of them are hidden by the next point of their series. Aggregate the rows over time, e.g. with GROUP BY $__timeInterval(column).`, + }); + } + } + + return { series, exemplars, start, stepMs, notices }; +} + +/** + * buildExemplars converts the result of an exemplar query. Each row is an exemplar: its time column is its + * timestamp and its `value` column, or else its first numeric column, is its value. The columns named like a label + * of the series tell which series the exemplar belongs to, and the other ones are the labels of the exemplar, + * e.g. `trace_id`. + */ +export function buildExemplars(response: ClickHouseQueryResponse, series: TimeSeries[]): TimeSeriesExemplars[] { + const { columns, rows } = response; + const time = findTimeColumn(columns); + const named = findColumn(columns, ['value']); + const value = + named !== -1 ? named : columns.findIndex((column, index) => index !== time && isNumericType(column.type)); + if (time === -1 || value === -1) { + throw new Error('An exemplar query must return a time column and a numeric "value" column.'); + } + const timeZone = getTypeTimeZone(columns[time]?.type ?? '') ?? response.timeZone; + + const seriesLabelNames = new Set(); + // With several value columns, the series of the same labels differ by the name of their value column. + const firstValueColumns = new Map(); + for (const { labels = {} } of series) { + const { [NAME_LABEL]: valueColumn, ...others } = labels; + for (const name of Object.keys(labels)) seriesLabelNames.add(name); + if (valueColumn !== undefined) { + const key = labelsKey(others); + if (!firstValueColumns.has(key)) firstValueColumns.set(key, valueColumn); + } + } + + const groups = new Map(); + for (const row of rows) { + const timestamp = toUnixMs(row[time], timeZone); + const exemplarValue = toNumber(row[value]); + if (Number.isNaN(timestamp) || exemplarValue === null) continue; + const labels: Labels = {}; + for (let index = 0; index < columns.length; index++) { + if (index !== time && index !== value) addLabels(labels, columns[index]?.name ?? '', row[index]); + } + const seriesLabels: Labels = {}; + const exemplarLabels: Labels = {}; + for (const [name, label] of Object.entries(labels)) { + (seriesLabelNames.has(name) ? seriesLabels : exemplarLabels)[name] = label; + } + const key = labelsKey(seriesLabels); + let group = groups.get(key); + if (!group) { + // Exemplars that do not name a value column belong to the first one of the series with their labels. + const valueColumn = seriesLabels[NAME_LABEL] === undefined ? firstValueColumns.get(key) : undefined; + group = { + seriesLabels: valueColumn === undefined ? seriesLabels : { [NAME_LABEL]: valueColumn, ...seriesLabels }, + exemplars: [], + }; + groups.set(key, group); + } + group.exemplars.push({ + timestamp, + value: exemplarValue, + labels: exemplarLabels, + }); + } + for (const group of groups.values()) { + group.exemplars.sort((a, b) => a.timestamp - b.timestamp); + } + return [...groups.values()]; +} diff --git a/clickhouse/src/queries/click-house-trace-query/ClickHouseTraceQuery.tsx b/clickhouse/src/queries/click-house-trace-query/ClickHouseTraceQuery.tsx new file mode 100644 index 000000000..7f92230df --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/ClickHouseTraceQuery.tsx @@ -0,0 +1,26 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { TraceQueryPlugin } from '@perses-dev/plugin-system'; + +import { queryDependencies } from '../../model/execute-query'; +import type { ClickHouseTraceQuerySpec } from './click-house-trace-query-types'; +import { ClickHouseTraceQueryEditor } from './ClickHouseTraceQueryEditor'; +import { getTraceData } from './get-click-house-trace-data'; + +export const ClickHouseTraceQuery: TraceQueryPlugin = { + getTraceData, + OptionsEditorComponent: ClickHouseTraceQueryEditor, + createInitialOptions: () => ({ query: '' }), + dependsOn: (spec) => queryDependencies(spec.datasource, spec.query), +}; diff --git a/clickhouse/src/queries/click-house-trace-query/ClickHouseTraceQueryEditor.tsx b/clickhouse/src/queries/click-house-trace-query/ClickHouseTraceQueryEditor.tsx new file mode 100644 index 000000000..b3fa06770 --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/ClickHouseTraceQueryEditor.tsx @@ -0,0 +1,77 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { Stack } from '@mui/material'; +import type { OptionsEditorProps } from '@perses-dev/plugin-system'; +import type { ReactElement } from 'react'; + +import { ClickHouseDatasourceSelect, DraftTextField, QueryExamples, SQLField } from '../../components'; +import { TRACE_EXAMPLES } from '../../components/query-examples'; +import { isTableName } from '../../model/sql'; +import type { ClickHouseTraceQuerySpec } from './click-house-trace-query-types'; +import { DEFAULT_SEARCH_LIMIT, DEFAULT_TRACE_TABLE } from './click-house-trace-query-types'; + +type ClickHouseTraceQueryEditorProps = OptionsEditorProps; + +export function ClickHouseTraceQueryEditor(props: ClickHouseTraceQueryEditorProps): ReactElement { + const { onChange, value, isReadonly } = props; + const isTableValid = value.table === undefined || isTableName(value.table); + + const handleLimitChange = (text: string): void => { + const limit = Number(text); + onChange({ ...value, limit: text.trim() !== '' && Number.isInteger(limit) && limit > 0 ? limit : undefined }); + }; + + return ( + + onChange({ ...value, datasource })} + isReadonly={isReadonly} + /> + onChange({ ...value, query })} + placeholder="Enter a trace ID, or a ClickHouse SQL query returning the TraceId and Timestamp of the spans to search for" + isReadonly={isReadonly} + /> + + onChange({ ...value, table: table.trim() || undefined })} + placeholder={DEFAULT_TRACE_TABLE} + error={!isTableValid} + helperText={ + isTableValid + ? 'Table of the spans, in the OpenTelemetry schema: "table" or "database.table".' + : 'Expected a table name: "table" or "database.table".' + } + isReadonly={isReadonly} + /> + + + + + ); +} diff --git a/clickhouse/src/queries/click-house-trace-query/click-house-trace-query-types.ts b/clickhouse/src/queries/click-house-trace-query/click-house-trace-query-types.ts new file mode 100644 index 000000000..f96cc9a83 --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/click-house-trace-query-types.ts @@ -0,0 +1,30 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { ClickHouseQuerySpec } from '../../model/execute-query'; + +/** Table of the spans written by the ClickHouse exporter of the OpenTelemetry Collector. */ +export const DEFAULT_TRACE_TABLE = 'otel_traces'; + +/** Number of traces returned by a search when the query does not set a limit. */ +export const DEFAULT_SEARCH_LIMIT = 20; + +export interface ClickHouseTraceQuerySpec extends ClickHouseQuerySpec { + /** + * Table holding the spans, optionally qualified by its database. It follows the schema of the ClickHouse exporter + * of the OpenTelemetry Collector. Defaults to `otel_traces`. + */ + table?: string; + /** Maximum number of traces returned by a search. Defaults to 20. */ + limit?: number; +} diff --git a/clickhouse/src/queries/click-house-trace-query/click-house-trace-query.test.ts b/clickhouse/src/queries/click-house-trace-query/click-house-trace-query.test.ts new file mode 100644 index 000000000..49503e5af --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/click-house-trace-query.test.ts @@ -0,0 +1,211 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { TraceQueryContext } from '@perses-dev/plugin-system'; + +import { ClickHouseError } from '../../model/click-house-client'; +import type { StubClient } from '../../test/stubs'; +import { stubClient, stubDatasourceStore, stubResponse } from '../../test/stubs'; +import { ClickHouseTraceQuery } from './ClickHouseTraceQuery'; + +function createContext(client: StubClient, variableState: TraceQueryContext['variableState'] = {}): TraceQueryContext { + return { + datasourceStore: stubDatasourceStore(client), + variableState, + absoluteTimeRange: { + start: new Date('2026-01-01T10:00:00.000Z'), + end: new Date('2026-01-01T11:00:00.000Z'), + }, + }; +} + +const SPANS = stubResponse( + [ + ['Timestamp', 'DateTime64(9)'], + ['TraceId', 'String'], + ['SpanId', 'String'], + ['Duration', 'UInt64'], + ], + [['2026-01-01T10:00:00Z', '0000000000000000000000000000abcd', 'aaaa000000000001', '1000']], +); + +const MATCHES = stubResponse( + [ + ['TraceId', 'String'], + ['FirstMatch', 'DateTime64(9)'], + ['LastMatch', 'DateTime64(9)'], + ], + [ + ['t2', '2026-01-01T10:20:00Z', '2026-01-01T10:20:05Z'], + ['t1', '2026-01-01T10:10:00Z', '2026-01-01T10:10:01Z'], + ['t0', '2026-01-01T10:05:00Z', '2026-01-01T10:05:00Z'], + ], +); + +const SUMMARIES = stubResponse( + [ + ['TraceId', 'String'], + ['StartUnixNano', 'String'], + ['EndUnixNano', 'String'], + ['RootServiceName', 'LowCardinality(String)'], + ['RootSpanName', 'LowCardinality(String)'], + ['RootSpans', 'UInt64'], + ['FirstServiceName', 'LowCardinality(String)'], + ['FirstSpanName', 'LowCardinality(String)'], + ['SpanCounts', 'Map(String, UInt64)'], + ['ErrorCounts', 'Map(String, UInt64)'], + ], + [ + [ + 't2', + '1767262800000000000', + '1767262802500000000', + 'frontend', + 'GET /cart', + '1', + 'frontend', + 'GET /cart', + { frontend: '3', db: '2' }, + { frontend: '0', db: '1' }, + ], + // The root span of this trace is missing. + ['t1', '1767262200000000000', '1767262200001000000', '', '', '0', 'db', 'SELECT', { db: '1' }, { db: '0' }], + ], +); + +describe('ClickHouseTraceQuery', () => { + it('reads the trace whose ID is the query, from the table of the query', async () => { + const client = stubClient(() => SPANS); + + const response = await ClickHouseTraceQuery.getTraceData( + { query: ' ABCD ', table: 'otel.otel_traces' }, + createContext(client), + ); + + // IDs are stored as 32 lower case hexadecimal digits. The trace is not looked for in the time range only. + const statement = + "SELECT * FROM `otel`.`otel_traces` WHERE TraceId = '0000000000000000000000000000abcd' ORDER BY Timestamp"; + expect(client.statements()).toEqual([statement]); + expect(response.metadata?.executedQueryString).toBe(statement); + expect(response.trace?.resourceSpans[0]?.scopeSpans[0]?.spans[0]?.spanId).toBe('aaaa000000000001'); + expect(response.searchResult).toBeUndefined(); + }); + + it('reads the trace whose ID is the value of a variable', async () => { + const client = stubClient(() => SPANS); + + const response = await ClickHouseTraceQuery.getTraceData( + { query: '$traceId' }, + createContext(client, { traceId: { value: '0000000000000000000000000000abcd', loading: false } }), + ); + + expect(response.trace).toBeDefined(); + // Nothing to display before the variable has a value. + await expect( + ClickHouseTraceQuery.getTraceData( + { query: '$traceId' }, + createContext(client, { traceId: { value: '', loading: false } }), + ), + ).resolves.toEqual({}); + }); + + it('fails when the trace does not exist', async () => { + const client = stubClient(() => stubResponse([['Timestamp', 'DateTime64(9)']])); + + await expect(ClickHouseTraceQuery.getTraceData({ query: 'abcd' }, createContext(client))).rejects.toThrow( + 'Trace 0000000000000000000000000000abcd was not found in otel_traces.', + ); + }); + + it('searches the traces of the spans returned by a query, then summarizes them from all their spans', async () => { + const client = stubClient((sql) => (sql.includes('FirstMatch') ? MATCHES : SUMMARIES)); + + const response = await ClickHouseTraceQuery.getTraceData( + { + query: "SELECT TraceId, Timestamp FROM otel_traces WHERE $__timeFilter(Timestamp) AND StatusCode = 'Error'", + limit: 2, + }, + createContext(client), + ); + + const [matchStatement = '', summaryStatement = ''] = client.statements(); + expect(matchStatement).toBe( + [ + 'SELECT TraceId, min(Timestamp) AS FirstMatch, max(Timestamp) AS LastMatch', + "FROM (\nSELECT TraceId, Timestamp FROM otel_traces WHERE (Timestamp >= toDateTime(1767261600) AND Timestamp <= toDateTime(1767265200)) AND StatusCode = 'Error'\n)", + "WHERE TraceId != ''", + 'GROUP BY TraceId', + 'ORDER BY LastMatch DESC', + // One more than the limit, to know whether more traces match. + 'LIMIT 3', + ].join('\n'), + ); + // Only the traces within the limit, from all their spans, however far from the matched ones. + expect(summaryStatement).toContain("WHERE TraceId IN ('t2', 't1')"); + expect(summaryStatement).not.toContain('Timestamp >='); + expect(summaryStatement).toContain('FROM `otel_traces`'); + + expect(response.searchResult).toEqual([ + { + traceId: 't2', + rootServiceName: 'frontend', + rootTraceName: 'GET /cart', + startTimeUnixMs: 1767262800000, + durationMs: 2500, + serviceStats: { frontend: { spanCount: 3 }, db: { spanCount: 2, errorCount: 1 } }, + }, + { + traceId: 't1', + // Named after its first span, as its root span is missing. + rootServiceName: 'db', + rootTraceName: 'SELECT', + startTimeUnixMs: 1767262200000, + durationMs: 1, + serviceStats: { db: { spanCount: 1 } }, + }, + ]); + expect(response.metadata?.hasMoreResults).toBe(true); + expect(response.metadata?.notices?.[0]?.type).toBe('info'); + }); + + it('does not summarize when the search matches nothing', async () => { + const client = stubClient(() => stubResponse(MATCHES.columns.map(({ name, type }) => [name, type]))); + + const response = await ClickHouseTraceQuery.getTraceData( + { query: 'SELECT TraceId, Timestamp FROM otel_traces' }, + createContext(client), + ); + + expect(response.searchResult).toEqual([]); + expect(client.statements()).toHaveLength(1); + }); + + it('tells which columns a search query must return', async () => { + const client = stubClient(() => { + throw new ClickHouseError('ClickHouse query failed: Unknown expression identifier `TraceId`', { code: 47 }); + }); + + await expect( + ClickHouseTraceQuery.getTraceData({ query: 'SELECT ServiceName FROM otel_traces' }, createContext(client)), + ).rejects.toThrow(/must return the "TraceId" and "Timestamp" columns/); + }); + + it('lists nothing for an empty query', async () => { + const client = stubClient(() => SPANS); + + await expect(ClickHouseTraceQuery.getTraceData({ query: '' }, createContext(client))).resolves.toEqual({ + searchResult: [], + }); + expect(client.statements()).toEqual([]); + }); +}); diff --git a/clickhouse/src/queries/click-house-trace-query/get-click-house-trace-data.ts b/clickhouse/src/queries/click-house-trace-query/get-click-house-trace-data.ts new file mode 100644 index 000000000..e504867b3 --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/get-click-house-trace-data.ts @@ -0,0 +1,102 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { TraceQueryPlugin } from '@perses-dev/plugin-system'; +import type { Notice } from '@perses-dev/spec'; +import { isValidTraceId } from '@perses-dev/spec'; + +import { ClickHouseError } from '../../model/click-house-client'; +import type { ClickHouseQueryContext } from '../../model/execute-query'; +import { prepareQuery, runStatement, truncationNotices } from '../../model/execute-query'; +import { interpolateVariables } from '../../model/interpolation'; +import type { ClickHouseTraceQuerySpec } from './click-house-trace-query-types'; +import { DEFAULT_SEARCH_LIMIT, DEFAULT_TRACE_TABLE } from './click-house-trace-query-types'; +import { buildTrace } from './otlp'; +import { buildSearchResult, readMatchedTraces } from './search'; +import { buildMatchQuery, buildSummaryQuery, buildTraceQuery } from './trace-sql'; + +const TRACE_ID_LENGTH = 32; +// Error code of ClickHouse for a column that does not exist. +const UNKNOWN_IDENTIFIER = 47; + +export const getTraceData: TraceQueryPlugin['getTraceData'] = async ( + spec, + context, + abortSignal, +) => { + if (!spec.query?.trim()) { + return { searchResult: [] }; + } + + const { datasourceStore, variableState } = context; + const table = spec.table || DEFAULT_TRACE_TABLE; + + // As for the other trace datasources, a trace ID asks for the trace and anything else is a search. + const traceId = interpolateVariables(spec.query, variableState).trim(); + if (traceId === '') { + // A variable without a value, e.g. before a trace is selected: there is nothing to display yet. + return {}; + } + if (isValidTraceId(traceId)) { + // The exporter stores trace IDs as 32 lower case hexadecimal digits. + const normalizedTraceId = traceId.toLowerCase().padStart(TRACE_ID_LENGTH, '0'); + const statement = buildTraceQuery(table, normalizedTraceId); + const result = await runStatement(spec.datasource, statement, context, abortSignal); + if (result.rows.length === 0) { + throw new Error(`Trace ${normalizedTraceId} was not found in ${table}.`); + } + const notices = truncationNotices(result); + return { + trace: buildTrace(result), + metadata: { executedQueryString: statement, ...(notices.length > 0 && { notices }) }, + }; + } + + const queryContext: ClickHouseQueryContext = { datasourceStore, variableState, timeRange: context.absoluteTimeRange }; + const limit = spec.limit ?? DEFAULT_SEARCH_LIMIT; + const matchStatement = buildMatchQuery(prepareQuery(spec.query, queryContext).sql, limit); + let matched; + try { + matched = readMatchedTraces(await runStatement(spec.datasource, matchStatement, context, abortSignal), limit); + } catch (error) { + if (error instanceof ClickHouseError && error.code === UNKNOWN_IDENTIFIER) { + throw new Error( + `${error.message} A trace search query must return the "TraceId" and "Timestamp" columns of the spans to search for.`, + { cause: error }, + ); + } + throw error; + } + + const { traceIds, hasMore: hasMoreResults } = matched; + if (traceIds.length === 0) { + return { searchResult: [], metadata: { executedQueryString: matchStatement } }; + } + + // The traces are summarized from all their spans, not only from the ones matched by the search. + const summary = await runStatement(spec.datasource, buildSummaryQuery(table, traceIds), context, abortSignal); + const notices: Notice[] = hasMoreResults + ? [ + { + type: 'info', + message: + 'Not all matching traces are currently displayed. Increase the result limit to view additional traces.', + }, + ] + : []; + + return { + searchResult: buildSearchResult(summary), + metadata: { executedQueryString: matchStatement, hasMoreResults, ...(notices.length > 0 && { notices }) }, + }; +}; diff --git a/clickhouse/src/queries/click-house-trace-query/index.ts b/clickhouse/src/queries/click-house-trace-query/index.ts new file mode 100644 index 000000000..ae217ec2c --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/index.ts @@ -0,0 +1,17 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export * from './ClickHouseTraceQuery'; +export * from './ClickHouseTraceQueryEditor'; +export * from './get-click-house-trace-data'; +export * from './click-house-trace-query-types'; diff --git a/clickhouse/src/queries/click-house-trace-query/otlp.test.ts b/clickhouse/src/queries/click-house-trace-query/otlp.test.ts new file mode 100644 index 000000000..6869214e3 --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/otlp.test.ts @@ -0,0 +1,192 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { stubResponse } from '../../test/stubs'; +import { buildTrace } from './otlp'; + +const COLUMNS: Array<[string, string]> = [ + ['Timestamp', 'DateTime64(9)'], + ['TraceId', 'String'], + ['SpanId', 'String'], + ['ParentSpanId', 'String'], + ['SpanName', 'LowCardinality(String)'], + ['SpanKind', 'LowCardinality(String)'], + ['ServiceName', 'LowCardinality(String)'], + ['ResourceAttributes', 'Map(LowCardinality(String), String)'], + ['ScopeName', 'String'], + ['ScopeVersion', 'String'], + ['SpanAttributes', 'Map(LowCardinality(String), String)'], + ['Duration', 'UInt64'], + ['StatusCode', 'LowCardinality(String)'], + ['StatusMessage', 'String'], + ['Events.Timestamp', 'Array(DateTime64(9))'], + ['Events.Name', 'Array(LowCardinality(String))'], + ['Events.Attributes', 'Array(Map(LowCardinality(String), String))'], + ['Links.TraceId', 'Array(String)'], + ['Links.SpanId', 'Array(String)'], + ['Links.Attributes', 'Array(Map(LowCardinality(String), String))'], +]; + +const TRACE_ID = '5b8efff798038103d269b633813fc60c'; + +describe('buildTrace', () => { + it('converts the spans of the OpenTelemetry traces table into an OTLP trace', () => { + const trace = buildTrace( + stubResponse(COLUMNS, [ + [ + '2026-01-01T10:00:00.000000001Z', + TRACE_ID, + 'AAAA000000000001', + '', + 'GET /cart', + 'Server', + 'frontend', + { 'service.name': 'frontend', 'host.name': 'a' }, + 'http', + '1.2', + { 'http.method': 'GET' }, + '2500000000', + 'Error', + 'boom', + ['2026-01-01T10:00:01Z'], + ['exception'], + [{ 'exception.message': 'boom' }], + ['11111111111111111111111111111111'], + ['2222222222222222'], + [{ reason: 'retry' }], + ], + [ + '2026-01-01T10:00:00.5Z', + TRACE_ID, + 'aaaa000000000002', + 'aaaa000000000001', + 'query', + 'Client', + 'frontend', + // The keys of a map do not always come in the same order. + { 'host.name': 'a', 'service.name': 'frontend' }, + 'http', + '1.2', + {}, + '1000', + 'Unset', + '', + [], + [], + [], + [], + [], + [], + ], + [ + '2026-01-01T10:00:00.6Z', + TRACE_ID, + 'bbbb000000000003', + 'aaaa000000000002', + 'SELECT', + 'SPAN_KIND_INTERNAL', + 'db', + {}, + '', + '', + {}, + '1', + 'Ok', + '', + [], + [], + [], + [], + [], + [], + ], + ]), + ); + + expect(trace.resourceSpans.map((resource) => resource.scopeSpans.map((scope) => scope.spans.length))).toEqual([ + // The two spans of the frontend share their resource and their scope. + [2], + [1], + ]); + expect(trace.resourceSpans[0]?.resource?.attributes).toEqual([ + { key: 'service.name', value: { stringValue: 'frontend' } }, + { key: 'host.name', value: { stringValue: 'a' } }, + ]); + // The service name is a resource attribute even when the resource attributes do not hold it. + expect(trace.resourceSpans[1]?.resource?.attributes).toEqual([ + { key: 'service.name', value: { stringValue: 'db' } }, + ]); + expect(trace.resourceSpans[0]?.scopeSpans[0]?.scope).toEqual({ name: 'http', version: '1.2' }); + expect(trace.resourceSpans[0]?.scopeSpans[0]?.spans[0]).toEqual({ + traceId: TRACE_ID, + spanId: 'aaaa000000000001', + name: 'GET /cart', + kind: 'SPAN_KIND_SERVER', + // Nanoseconds, kept exact. + startTimeUnixNano: '1767261600000000001', + endTimeUnixNano: '1767261602500000001', + attributes: [{ key: 'http.method', value: { stringValue: 'GET' } }], + events: [ + { + name: 'exception', + timeUnixNano: '1767261601000000000', + attributes: [{ key: 'exception.message', value: { stringValue: 'boom' } }], + }, + ], + links: [ + { + traceId: '11111111111111111111111111111111', + spanId: '2222222222222222', + attributes: [{ key: 'reason', value: { stringValue: 'retry' } }], + }, + ], + status: { code: 'STATUS_CODE_ERROR', message: 'boom' }, + }); + const [, child] = trace.resourceSpans[0]?.scopeSpans[0]?.spans ?? []; + expect(child).toMatchObject({ + parentSpanId: 'aaaa000000000001', + kind: 'SPAN_KIND_CLIENT', + status: { code: 'STATUS_CODE_UNSET' }, + }); + expect(trace.resourceSpans[1]?.scopeSpans[0]?.spans[0]).toMatchObject({ + kind: 'SPAN_KIND_INTERNAL', + status: { code: 'STATUS_CODE_OK' }, + }); + }); + + it('flattens the typed attributes of the JSON schema of the exporter', () => { + const trace = buildTrace( + stubResponse( + [ + ['Timestamp', 'DateTime64(9)'], + ['TraceId', 'String'], + ['SpanId', 'String'], + ['Duration', 'UInt64'], + ['SpanAttributes', 'JSON'], + ], + [['2026-01-01T10:00:00Z', TRACE_ID, 'aaaa000000000001', '1', { http: { status_code: 200, ok: true } }]], + ), + ); + + expect(trace.resourceSpans[0]?.scopeSpans[0]?.spans[0]?.attributes).toEqual([ + { key: 'http.status_code', value: { intValue: '200' } }, + { key: 'http.ok', value: { boolValue: true } }, + ]); + }); + + it('rejects a table that does not follow the OpenTelemetry schema', () => { + expect(() => buildTrace(stubResponse([['Timestamp', 'DateTime64(9)']], [['2026-01-01T10:00:00Z']]))).toThrow( + 'The trace table has no "TraceId" column', + ); + }); +}); diff --git a/clickhouse/src/queries/click-house-trace-query/otlp.ts b/clickhouse/src/queries/click-house-trace-query/otlp.ts new file mode 100644 index 000000000..064bba7a5 --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/otlp.ts @@ -0,0 +1,202 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { otlpcommonv1, otlptracev1 } from '@perses-dev/spec'; + +import type { ClickHouseQueryResponse } from '../../model/click-house-client'; +import type { ClickHouseColumn } from '../../model/click-house-types'; +import { findColumn, getTypeTimeZone } from '../../model/click-house-types'; +import { isRecord, toText, toUnixNano } from '../../model/values'; + +const SPAN_KINDS = new Set(['INTERNAL', 'SERVER', 'CLIENT', 'PRODUCER', 'CONSUMER']); +const SERVICE_NAME = 'service.name'; + +function toAnyValue(value: unknown): otlpcommonv1.AnyValue { + if (typeof value === 'boolean') return { boolValue: value }; + if (typeof value === 'number') { + return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value }; + } + if (Array.isArray(value)) return { arrayValue: { values: value.map(toAnyValue) } }; + return { stringValue: toText(value) }; +} + +/** + * toAttributes converts an attribute column. With the default schema it is a map of strings. With the JSON schema + * of the exporter the values keep their type, and ClickHouse nests the dotted names (`http.method` comes back as + * `{http: {method: ...}}`): they are flattened back. + */ +function toAttributes(value: unknown, prefix = '', result: otlpcommonv1.KeyValue[] = []): otlpcommonv1.KeyValue[] { + if (!isRecord(value)) return result; + for (const key of Object.keys(value)) { + const item = value[key]; + if (isRecord(item)) { + toAttributes(item, `${prefix}${key}.`, result); + } else if (item !== null && item !== undefined) { + result.push({ key: `${prefix}${key}`, value: toAnyValue(item) }); + } + } + return result; +} + +function toStatusCode(value: unknown): otlptracev1.Status['code'] { + const status = toText(value).toUpperCase(); + if (status === 'ERROR' || status === 'STATUS_CODE_ERROR' || status === '2') return 'STATUS_CODE_ERROR'; + if (status === 'OK' || status === 'STATUS_CODE_OK' || status === '1') return 'STATUS_CODE_OK'; + return 'STATUS_CODE_UNSET'; +} + +function toSpanKind(value: unknown): string { + const kind = toText(value) + .toUpperCase() + .replace(/^SPAN_KIND_/, ''); + return SPAN_KINDS.has(kind) ? `SPAN_KIND_${kind}` : 'SPAN_KIND_UNSPECIFIED'; +} + +function toArray(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; +} + +interface SpanColumns { + timestamp: number; + traceId: number; + spanId: number; + parentSpanId: number; + spanName: number; + spanKind: number; + serviceName: number; + resourceAttributes: number; + scopeName: number; + scopeVersion: number; + spanAttributes: number; + duration: number; + statusCode: number; + statusMessage: number; + eventTimestamps: number; + eventNames: number; + eventAttributes: number; + linkTraceIds: number; + linkSpanIds: number; + linkAttributes: number; +} + +function findSpanColumns(columns: ClickHouseColumn[]): SpanColumns { + const index = (name: string): number => findColumn(columns, [name]); + const required = (name: string): number => { + const found = index(name.toLowerCase()); + if (found === -1) { + throw new Error(`The trace table has no "${name}" column: it must follow the OpenTelemetry schema.`); + } + return found; + }; + return { + timestamp: required('Timestamp'), + traceId: required('TraceId'), + spanId: required('SpanId'), + duration: required('Duration'), + parentSpanId: index('parentspanid'), + spanName: index('spanname'), + spanKind: index('spankind'), + serviceName: index('servicename'), + resourceAttributes: index('resourceattributes'), + scopeName: index('scopename'), + scopeVersion: index('scopeversion'), + spanAttributes: index('spanattributes'), + statusCode: index('statuscode'), + statusMessage: index('statusmessage'), + eventTimestamps: index('events.timestamp'), + eventNames: index('events.name'), + eventAttributes: index('events.attributes'), + linkTraceIds: index('links.traceid'), + linkSpanIds: index('links.spanid'), + linkAttributes: index('links.attributes'), + }; +} + +/** + * buildTrace converts the spans of a trace, as stored by the ClickHouse exporter of the OpenTelemetry Collector, + * into an OTLP trace: spans grouped by resource, then by instrumentation scope. + */ +export function buildTrace(response: ClickHouseQueryResponse): otlptracev1.TracesData { + const { columns, rows } = response; + const span = findSpanColumns(columns); + const timeZone = getTypeTimeZone(columns[span.timestamp]?.type ?? '') ?? response.timeZone; + const resources = new Map< + string, + { resourceSpan: otlptracev1.ResourceSpan; scopes: Map } + >(); + + for (const row of rows) { + const start = toUnixNano(row[span.timestamp], timeZone); + if (start === undefined) continue; + let duration = 0n; + try { + duration = BigInt(toText(row[span.duration]) || '0'); + } catch { + // Not an integer number of nanoseconds: the span is displayed without a duration. + } + + const serviceName = toText(row[span.serviceName]); + const resourceAttributes = toAttributes(row[span.resourceAttributes]); + if (serviceName && !resourceAttributes.some((attribute) => attribute.key === SERVICE_NAME)) { + resourceAttributes.push({ key: SERVICE_NAME, value: { stringValue: serviceName } }); + } + // Attributes are sorted in the key: ClickHouse does not always return the keys of a map in the same order. + const resourceKey = JSON.stringify(resourceAttributes.toSorted((a, b) => (a.key < b.key ? -1 : 1))); + let resource = resources.get(resourceKey); + if (!resource) { + resource = { resourceSpan: { resource: { attributes: resourceAttributes }, scopeSpans: [] }, scopes: new Map() }; + resources.set(resourceKey, resource); + } + + const scopeName = toText(row[span.scopeName]); + const scopeVersion = toText(row[span.scopeVersion]); + const scopeKey = JSON.stringify([scopeName, scopeVersion]); + let spans = resource.scopes.get(scopeKey); + if (!spans) { + spans = []; + resource.scopes.set(scopeKey, spans); + resource.resourceSpan.scopeSpans.push({ scope: { name: scopeName, version: scopeVersion }, spans }); + } + + const eventTimestamps = toArray(row[span.eventTimestamps]); + const eventAttributes = toArray(row[span.eventAttributes]); + const linkSpanIds = toArray(row[span.linkSpanIds]); + const linkAttributes = toArray(row[span.linkAttributes]); + const parentSpanId = toText(row[span.parentSpanId]).toLowerCase(); + const statusMessage = toText(row[span.statusMessage]); + + spans.push({ + traceId: toText(row[span.traceId]).toLowerCase(), + spanId: toText(row[span.spanId]).toLowerCase(), + ...(parentSpanId && { parentSpanId }), + name: toText(row[span.spanName]), + kind: toSpanKind(row[span.spanKind]), + startTimeUnixNano: String(start), + endTimeUnixNano: String(start + duration), + attributes: toAttributes(row[span.spanAttributes]), + events: toArray(row[span.eventNames]).map((name, position) => ({ + name: toText(name), + timeUnixNano: String(toUnixNano(eventTimestamps[position], timeZone) ?? start), + attributes: toAttributes(eventAttributes[position]), + })), + links: toArray(row[span.linkTraceIds]).map((traceId, position) => ({ + traceId: toText(traceId).toLowerCase(), + spanId: toText(linkSpanIds[position]).toLowerCase(), + attributes: toAttributes(linkAttributes[position]), + })), + status: { code: toStatusCode(row[span.statusCode]), ...(statusMessage && { message: statusMessage }) }, + }); + } + + return { resourceSpans: [...resources.values()].map(({ resourceSpan }) => resourceSpan) }; +} diff --git a/clickhouse/src/queries/click-house-trace-query/search.ts b/clickhouse/src/queries/click-house-trace-query/search.ts new file mode 100644 index 000000000..fa861bc62 --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/search.ts @@ -0,0 +1,98 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { ServiceStats, TraceSearchResult } from '@perses-dev/spec'; + +import type { ClickHouseQueryResponse } from '../../model/click-house-client'; +import { findColumn, getTypeTimeZone } from '../../model/click-house-types'; +import { isRecord, toNumber, toText, toUnixMs } from '../../model/values'; + +const NANOS_PER_MILLI = 1_000_000; + +export interface MatchedTraces { + traceIds: string[]; + /** True when more traces than the limit match. */ + hasMore: boolean; +} + +/** + * readMatchedTraces reads the result of the statement built by `buildMatchQuery`: the matched traces, the most + * recent ones first, of which the first `limit` ones are kept. + */ +export function readMatchedTraces(response: ClickHouseQueryResponse, limit: number): MatchedTraces { + const { columns, rows } = response; + const traceId = findColumn(columns, ['traceid']); + const first = findColumn(columns, ['firstmatch']); + const last = findColumn(columns, ['lastmatch']); + const timeZone = getTypeTimeZone(columns[first]?.type ?? '') ?? response.timeZone; + const matched: MatchedTraces = { traceIds: [], hasMore: rows.length > limit }; + for (const row of rows.slice(0, limit)) { + // The traces are ordered by their last matched span: it must be a time. + if (Number.isNaN(toUnixMs(row[first], timeZone)) || Number.isNaN(toUnixMs(row[last], timeZone))) { + throw new Error('The "Timestamp" column of a trace search query must be a date/time.'); + } + matched.traceIds.push(toText(row[traceId])); + } + return matched; +} + +function toUnixNanoBigInt(value: unknown): bigint { + try { + return BigInt(toText(value) || '0'); + } catch { + return 0n; + } +} + +/** buildSearchResult reads the result of the statement built by `buildSummaryQuery`. */ +export function buildSearchResult(response: ClickHouseQueryResponse): TraceSearchResult[] { + const { columns, rows } = response; + const index = (name: string): number => findColumn(columns, [name]); + const traceId = index('traceid'); + const start = index('startunixnano'); + const end = index('endunixnano'); + const rootSpans = index('rootspans'); + const rootServiceName = index('rootservicename'); + const rootSpanName = index('rootspanname'); + const firstServiceName = index('firstservicename'); + const firstSpanName = index('firstspanname'); + const spanCounts = index('spancounts'); + const errorCounts = index('errorcounts'); + + return rows.map((row) => { + const startNano = toUnixNanoBigInt(row[start]); + const endNano = toUnixNanoBigInt(row[end]); + // A trace whose root span is missing, e.g. not received yet, is named after its first span. + const hasRoot = (toNumber(row[rootSpans]) ?? 0) > 0; + const spans: unknown = row[spanCounts]; + const errors: unknown = row[errorCounts]; + const serviceStats: Record = {}; + if (isRecord(spans)) { + for (const service of Object.keys(spans)) { + const errorCount = isRecord(errors) ? (toNumber(errors[service]) ?? 0) : 0; + serviceStats[service] = { + spanCount: toNumber(spans[service]) ?? 0, + ...(errorCount > 0 && { errorCount }), + }; + } + } + return { + traceId: toText(row[traceId]), + rootServiceName: toText(row[hasRoot ? rootServiceName : firstServiceName]), + rootTraceName: toText(row[hasRoot ? rootSpanName : firstSpanName]), + startTimeUnixMs: Number(startNano / BigInt(NANOS_PER_MILLI)), + durationMs: Number(endNano - startNano) / NANOS_PER_MILLI, + serviceStats, + }; + }); +} diff --git a/clickhouse/src/queries/click-house-trace-query/trace-sql.ts b/clickhouse/src/queries/click-house-trace-query/trace-sql.ts new file mode 100644 index 000000000..7becb89dc --- /dev/null +++ b/clickhouse/src/queries/click-house-trace-query/trace-sql.ts @@ -0,0 +1,64 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { asSubquery, quoteString, quoteTableName } from '../../model/sql'; + +const ERROR_STATUS = "StatusCode IN ('Error', 'STATUS_CODE_ERROR')"; + +/** buildTraceQuery returns the statement reading every span of a trace. */ +export function buildTraceQuery(table: string, traceId: string): string { + // The trace is not filtered by time, so that it can be opened whatever the time range of the dashboard: + // the lookup relies on the bloom filter index the exporter creates on TraceId. + return `SELECT * FROM ${quoteTableName(table)} WHERE TraceId = ${quoteString(traceId)} ORDER BY Timestamp`; +} + +/** + * buildMatchQuery returns the statement listing the traces of the spans returned by a search query: the most recent + * ones first, and one more than the limit, to tell whether more traces match. + */ +export function buildMatchQuery(searchQuery: string, limit: number): string { + return [ + 'SELECT TraceId, min(Timestamp) AS FirstMatch, max(Timestamp) AS LastMatch', + `FROM ${asSubquery(searchQuery)}`, + "WHERE TraceId != ''", + 'GROUP BY TraceId', + 'ORDER BY LastMatch DESC', + `LIMIT ${limit + 1}`, + ].join('\n'); +} + +/** + * buildSummaryQuery returns the statement summarizing traces from all their spans: their root span, time span, and + * number of spans and errors per service. + */ +export function buildSummaryQuery(table: string, traceIds: string[]): string { + return [ + 'SELECT', + ' TraceId,', + ' toString(min(toUnixTimestamp64Nano(toDateTime64(Timestamp, 9)))) AS StartUnixNano,', + ' toString(max(toUnixTimestamp64Nano(toDateTime64(Timestamp, 9)) + toInt64(Duration))) AS EndUnixNano,', + " argMinIf(ServiceName, Timestamp, ParentSpanId = '') AS RootServiceName,", + " argMinIf(SpanName, Timestamp, ParentSpanId = '') AS RootSpanName,", + " countIf(ParentSpanId = '') AS RootSpans,", + ' argMin(ServiceName, Timestamp) AS FirstServiceName,', + ' argMin(SpanName, Timestamp) AS FirstSpanName,', + ' sumMap(map(toString(ServiceName), toUInt64(1))) AS SpanCounts,', + ` sumMap(map(toString(ServiceName), toUInt64(${ERROR_STATUS}))) AS ErrorCounts`, + `FROM ${quoteTableName(table)}`, + // Not filtered by time, as a trace can start long before and end long after its matched spans: like the lookup + // of a trace, it relies on the bloom filter index the exporter creates on TraceId. + `WHERE TraceId IN (${traceIds.map(quoteString).join(', ')})`, + 'GROUP BY TraceId', + 'ORDER BY StartUnixNano DESC', + ].join('\n'); +} diff --git a/clickhouse/src/queries/click-stack-alerts-query/ClickStackAlertsQuery.tsx b/clickhouse/src/queries/click-stack-alerts-query/ClickStackAlertsQuery.tsx new file mode 100644 index 000000000..95f9c336d --- /dev/null +++ b/clickhouse/src/queries/click-stack-alerts-query/ClickStackAlertsQuery.tsx @@ -0,0 +1,30 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { AlertsQueryPlugin } from '@perses-dev/plugin-system'; +import { isVariableDatasource, parseVariables } from '@perses-dev/plugin-system'; + +import type { ClickStackAlertsQuerySpec } from './click-stack-alerts-query-types'; +import { ClickStackAlertsQueryEditor } from './ClickStackAlertsQueryEditor'; +import { getAlertsData } from './get-click-stack-alerts-data'; + +export const ClickStackAlertsQuery: AlertsQueryPlugin = { + getAlertsData, + OptionsEditorComponent: ClickStackAlertsQueryEditor, + createInitialOptions: () => ({}), + dependsOn: (spec) => { + const texts = [...(spec.tags ?? []), spec.search ?? '']; + if (isVariableDatasource(spec.datasource)) texts.push(spec.datasource); + return { variables: [...new Set(texts.flatMap((text) => parseVariables(text)))] }; + }, +}; diff --git a/clickhouse/src/queries/click-stack-alerts-query/ClickStackAlertsQueryEditor.tsx b/clickhouse/src/queries/click-stack-alerts-query/ClickStackAlertsQueryEditor.tsx new file mode 100644 index 000000000..3fc808759 --- /dev/null +++ b/clickhouse/src/queries/click-stack-alerts-query/ClickStackAlertsQueryEditor.tsx @@ -0,0 +1,148 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { Autocomplete, Stack, TextField } from '@mui/material'; +import type { DatasourceSelectProps, OptionsEditorProps } from '@perses-dev/plugin-system'; +import { DatasourceSelect } from '@perses-dev/plugin-system'; +import type { ReactElement } from 'react'; + +import { DraftTextField } from '../../components/DraftTextField'; +import type { ClickStackAlertSource, ClickStackAlertState } from '../../model/click-stack-client'; +import { + CLICKSTACK_DATASOURCE_KIND, + DEFAULT_CLICKSTACK, + isClickStackDatasourceSelectValue, +} from '../../model/click-stack-selectors'; +import type { ClickStackAlertsQuerySpec } from './click-stack-alerts-query-types'; +import { DEFAULT_ALERT_STATES } from './click-stack-alerts-query-types'; + +type ClickStackAlertsQueryEditorProps = OptionsEditorProps; + +// The states ClickStack sets, named as Perses displays them. +const STATE_LABELS: Partial> = { + ALERT: 'Firing', + PENDING: 'Pending', + OK: 'OK', +}; +const STATE_OPTIONS = Object.keys(STATE_LABELS) as ClickStackAlertState[]; + +const SOURCE_LABELS: Record = { + saved_search: 'Saved searches', + tile: 'Dashboard tiles', + inline: 'Charts', +}; +const SOURCE_OPTIONS = Object.keys(SOURCE_LABELS) as ClickStackAlertSource[]; + +const NO_TAGS: string[] = []; + +function isDefaultStates(states: ClickStackAlertState[]): boolean { + return states.length === DEFAULT_ALERT_STATES.length && DEFAULT_ALERT_STATES.every((state) => states.includes(state)); +} + +export function ClickStackAlertsQueryEditor(props: ClickStackAlertsQueryEditorProps): ReactElement { + const { onChange, value, isReadonly } = props; + + const handleDatasourceChange: DatasourceSelectProps['onChange'] = (next) => { + if (!isClickStackDatasourceSelectValue(next)) { + throw new Error('Got unexpected non ClickStack datasource selection'); + } + onChange({ ...value, datasource: next }); + }; + + const handleStatesChange = (states: ClickStackAlertState[]): void => { + // Without any state, or with the default ones, the spec is left without states: the default ones apply. + onChange({ ...value, states: states.length === 0 || isDefaultStates(states) ? undefined : states }); + }; + + return ( + + + + STATE_LABELS[state] ?? state} + value={value.states && value.states.length > 0 ? value.states : [...DEFAULT_ALERT_STATES]} + onChange={(_event, states) => handleStatesChange(states)} + renderInput={(params) => ( + + )} + /> + SOURCE_LABELS[source] ?? source} + value={value.sources ?? []} + onChange={(_event, sources) => onChange({ ...value, sources: sources.length > 0 ? sources : undefined })} + renderInput={(params) => ( + + )} + /> + + { + const cleaned = [...new Set(tags.map((tag) => tag.trim()).filter((tag) => tag !== ''))]; + onChange({ ...value, tags: cleaned.length > 0 ? cleaned : undefined }); + }} + renderInput={(params) => ( + + )} + /> + onChange({ ...value, search: search.trim() || undefined })} + helperText="Alerts whose name contains this text. Variables are supported." + isReadonly={isReadonly} + /> + + ); +} diff --git a/clickhouse/src/queries/click-stack-alerts-query/alerts.ts b/clickhouse/src/queries/click-stack-alerts-query/alerts.ts new file mode 100644 index 000000000..409794c82 --- /dev/null +++ b/clickhouse/src/queries/click-stack-alerts-query/alerts.ts @@ -0,0 +1,151 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { Alert, AlertState } from '@perses-dev/spec'; + +import type { ClickStackAlert } from '../../model/click-stack-client'; + +const STATES: Record = { + ALERT: 'firing', + PENDING: 'pending', + OK: 'inactive', +}; + +const COMPARATORS: Record = { + above: '>=', + above_exclusive: '>', + below: '<', + below_or_equal: '<=', + equal: '=', + not_equal: '!=', +}; + +// Labels set from the fields of an alert: a tag can not replace them. +const RESERVED_LABELS = new Set(['alertname', 'source', 'interval', 'group_by', 'tags']); +// A `key:value` tag whose key reads as a label name, e.g. `team:checkout`. It leaves out URLs and times. +const LABEL_TAG = /^([A-Za-z_][\w.-]*):(?!\/\/)(.+)$/; + +export interface BuildAlertsOptions { + /** URL of the ClickStack UI. Alerts have no link without it. */ + uiUrl?: string; + /** Current time, in milliseconds: tells whether a silence is still active. */ + now: number; +} + +function formatCondition(alert: ClickStackAlert): string | undefined { + const { threshold, thresholdMax, thresholdType, interval, numConsecutiveWindows } = alert; + if (typeof threshold !== 'number' || !thresholdType) return undefined; + let condition: string; + if (thresholdType === 'between' || thresholdType === 'not_between') { + condition = `${thresholdType === 'between' ? 'between' : 'not between'} ${threshold} and ${thresholdMax ?? '?'}`; + } else { + condition = `${COMPARATORS[thresholdType] ?? thresholdType} ${threshold}`; + } + if (interval) condition += ` over ${interval}`; + if (typeof numConsecutiveWindows === 'number' && numConsecutiveWindows > 1) { + condition += `, for ${numConsecutiveWindows} consecutive windows`; + } + return condition; +} + +function isHttpUrl(text: string): boolean { + return /^https?:\/\/\S+$/i.test(text); +} + +// Link to what the alert watches in the ClickStack UI, as ClickStack builds it. +function buildSourceUrl(alert: ClickStackAlert, uiUrl: string): string { + const base = uiUrl.replace(/\/+$/, ''); + if (alert.source === 'tile' && alert.dashboardId) { + const tile = alert.tileId ? `?highlightedTileId=${encodeURIComponent(alert.tileId)}` : ''; + return `${base}/dashboards/${encodeURIComponent(alert.dashboardId)}${tile}`; + } + if (alert.source === 'saved_search' && alert.savedSearchId) { + return `${base}/search/${encodeURIComponent(alert.savedSearchId)}`; + } + if (alert.source === 'inline') { + return `${base}/chart?alertId=${encodeURIComponent(alert.id)}`; + } + return `${base}/alerts`; +} + +/** + * buildAlert converts a ClickStack alert. + * + * - Its name is its display name: the `name` field of ClickStack is the title of its notifications. + * - Its labels are its name (`alertname`), what it watches (`source`), its evaluation interval, its grouping, and + * its tags: a `key:value` tag is the label `key`, and the other tags are joined in the `tags` label. + * - Its severity is its `severity` label, as ClickStack alerts have no severity of their own. + * - A note that is a link is also its `runbook_url` annotation, the one alert tables open as a runbook. + * - ClickStack does not tell when an alert started firing: `startsAt` is the time of its last evaluation. + */ +export function buildAlert(alert: ClickStackAlert, options: BuildAlertsOptions): Alert { + const name = alert.displayName || alert.name || alert.id; + const labels: Record = { alertname: name }; + if (alert.source) labels.source = alert.source; + if (alert.interval) labels.interval = alert.interval; + if (alert.groupBy) labels.group_by = alert.groupBy; + const otherTags: string[] = []; + for (const tag of alert.tags ?? []) { + const [, key, value] = LABEL_TAG.exec(tag.trim()) ?? []; + if (key !== undefined && value !== undefined && value.trim() !== '' && !RESERVED_LABELS.has(key)) { + labels[key] = value.trim(); + } else if (tag.trim() !== '') { + otherTags.push(tag.trim()); + } + } + if (otherTags.length > 0) labels.tags = otherTags.join(','); + + const annotations: Record = {}; + if (alert.message) annotations.message = alert.message; + if (alert.note) { + annotations.note = alert.note; + if (isHttpUrl(alert.note.trim())) annotations.runbook_url = alert.note.trim(); + } + if (alert.name && alert.name !== name) annotations.title = alert.name; + const condition = formatCondition(alert); + if (condition) annotations.condition = condition; + const state = alert.state ? STATES[alert.state] : undefined; + // A state the plugin does not know is shown as inactive: keep it readable. + if (alert.state && state === undefined) annotations.clickstack_state = alert.state; + const lastError = alert.executionErrors?.at(-1); + if (lastError?.message) { + annotations.error = lastError.type ? `${lastError.type}: ${lastError.message}` : lastError.message; + } + + const lastEvaluation = alert.updatedAt || alert.createdAt || new Date(options.now).toISOString(); + const result: Alert = { + id: alert.id, + name, + state: state ?? 'inactive', + labels, + annotations, + startsAt: lastEvaluation, + updatedAt: lastEvaluation, + }; + if (labels.severity) result.severity = labels.severity; + if (options.uiUrl) result.sourceURL = buildSourceUrl(alert, options.uiUrl); + + // A silence stays on the alert once over: only one that has not ended yet suppresses it. + const silencedUntil = alert.silenced?.until ? Date.parse(alert.silenced.until) : NaN; + if (silencedUntil > options.now) { + result.suppressed = true; + result.suppressedBy = [{ type: 'silence', id: alert.silenced?.by || alert.id }]; + annotations.silenced_until = new Date(silencedUntil).toISOString(); + } + return result; +} + +/** buildAlerts converts the alerts of ClickStack into the alerts Perses displays. */ +export function buildAlerts(alerts: ClickStackAlert[], options: BuildAlertsOptions): Alert[] { + return alerts.map((alert) => buildAlert(alert, options)); +} diff --git a/clickhouse/src/queries/click-stack-alerts-query/click-stack-alerts-query-types.ts b/clickhouse/src/queries/click-stack-alerts-query/click-stack-alerts-query-types.ts new file mode 100644 index 000000000..16fb7bfbf --- /dev/null +++ b/clickhouse/src/queries/click-stack-alerts-query/click-stack-alerts-query-types.ts @@ -0,0 +1,30 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { ClickStackAlertSource, ClickStackAlertState } from '../../model/click-stack-client'; +import type { ClickStackDatasourceSelectValue } from '../../model/click-stack-selectors'; + +/** States of the alerts listed when a query does not select any: the alerts that are firing or about to. */ +export const DEFAULT_ALERT_STATES: readonly ClickStackAlertState[] = ['ALERT', 'PENDING']; + +export interface ClickStackAlertsQuerySpec { + datasource?: ClickStackDatasourceSelectValue; + /** Only the alerts in one of these states. Defaults to the firing and pending ones. */ + states?: ClickStackAlertState[]; + /** Only the alerts watching one of these kinds of sources. Defaults to all of them. */ + sources?: ClickStackAlertSource[]; + /** Only the alerts with one of these tags. Variables are supported: a variable with several values is as many tags. */ + tags?: string[]; + /** Only the alerts whose name contains this text. Variables are supported. */ + search?: string; +} diff --git a/clickhouse/src/queries/click-stack-alerts-query/click-stack-alerts-query.test.ts b/clickhouse/src/queries/click-stack-alerts-query/click-stack-alerts-query.test.ts new file mode 100644 index 000000000..d29df480c --- /dev/null +++ b/clickhouse/src/queries/click-stack-alerts-query/click-stack-alerts-query.test.ts @@ -0,0 +1,209 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { AlertsQueryContext } from '@perses-dev/plugin-system'; + +import type { ClickStackAlert, ClickStackAlertsParams } from '../../model/click-stack-client'; +import { stubDatasourceStore } from '../../test/stubs'; +import { buildAlert } from './alerts'; +import { ClickStackAlertsQuery } from './ClickStackAlertsQuery'; +import { buildAlertsParams } from './get-click-stack-alerts-data'; + +const now = Date.parse('2026-11-26T14:00:00Z'); +const options = { uiUrl: 'http://clickstack:8080/', now }; + +// As returned by ClickStack 2.47. +const TILE_ALERT: ClickStackAlert = { + id: '6b082f6e859a84a79ab54932', + name: 'Log throughput is unusual: {{value}}', + displayName: 'Log throughput is unusual', + tags: ['perses-demo', 'team:checkout', 'severity:warning', 'source:ignored', 'https://example.com/doc'], + message: 'Silenced: shown as suppressed.', + note: 'https://runbooks.example.com/logs', + threshold: 1000000, + thresholdMax: 2000000, + interval: '1m', + numConsecutiveWindows: 3, + thresholdType: 'not_between', + source: 'tile', + state: 'ALERT', + tileId: 'tile 1', + dashboardId: 'dash1', + silenced: { by: 'user1', at: '2026-11-26T13:06:42.921Z', until: '2026-12-26T13:06:42.000Z' }, + executionErrors: [ + { timestamp: '2026-11-26T13:00:00Z', type: 'QUERY_ERROR', message: 'old' }, + { timestamp: '2026-11-26T13:15:00Z', type: 'WEBHOOK_ERROR', message: 'Failed to send notification' }, + ], + createdAt: '2026-11-26T13:06:42.902Z', + updatedAt: '2026-11-26T13:15:00.067Z', +}; + +function withState(state: string): unknown { + return buildAlert({ id: 'a', state }, options); +} + +function sourceUrl(alert: Partial): string | undefined { + return buildAlert({ id: 'alert/1', ...alert }, options).sourceURL; +} + +function condition(alert: Partial): string | undefined { + return buildAlert({ id: 'a', threshold: 5, ...alert }, options).annotations.condition; +} + +interface AlertsResponse { + alerts: ClickStackAlert[]; + total: number; +} + +function createContext(response: AlertsResponse): { + context: AlertsQueryContext; + getAlerts: ReturnType Promise>>; +} { + const getAlerts = vi.fn(async (_params: ClickStackAlertsParams) => response); + const client = { options: { datasourceUrl: '/proxy', uiUrl: 'http://clickstack:8080' }, getAlerts }; + return { context: { datasourceStore: stubDatasourceStore(client), variableState: {} }, getAlerts }; +} + +describe('buildAlert', () => { + it('converts a ClickStack alert', () => { + expect(buildAlert(TILE_ALERT, options)).toEqual({ + id: '6b082f6e859a84a79ab54932', + // The display name: `name` is the title template of the notifications. + name: 'Log throughput is unusual', + state: 'firing', + labels: { + alertname: 'Log throughput is unusual', + // A `key:value` tag is a label, unless it would replace a label of the alert. + source: 'tile', + interval: '1m', + team: 'checkout', + severity: 'warning', + tags: 'perses-demo,source:ignored,https://example.com/doc', + }, + annotations: { + message: 'Silenced: shown as suppressed.', + note: 'https://runbooks.example.com/logs', + // A note that is a link is the runbook of the alert. + runbook_url: 'https://runbooks.example.com/logs', + title: 'Log throughput is unusual: {{value}}', + condition: 'not between 1000000 and 2000000 over 1m, for 3 consecutive windows', + error: 'WEBHOOK_ERROR: Failed to send notification', + silenced_until: '2026-12-26T13:06:42.000Z', + }, + severity: 'warning', + // ClickStack does not tell when an alert started firing: this is its last evaluation. + startsAt: '2026-11-26T13:15:00.067Z', + updatedAt: '2026-11-26T13:15:00.067Z', + sourceURL: 'http://clickstack:8080/dashboards/dash1?highlightedTileId=tile%201', + suppressed: true, + suppressedBy: [{ type: 'silence', id: 'user1' }], + }); + }); + + it('maps the states of ClickStack', () => { + expect(withState('ALERT')).toMatchObject({ state: 'firing' }); + expect(withState('PENDING')).toMatchObject({ state: 'pending' }); + expect(withState('OK')).toMatchObject({ state: 'inactive', annotations: {} }); + // States that ClickStack does not set yet stay readable. + expect(withState('INSUFFICIENT_DATA')).toMatchObject({ + state: 'inactive', + annotations: { clickstack_state: 'INSUFFICIENT_DATA' }, + }); + }); + + it('does not suppress an alert whose silence is over', () => { + const alert = buildAlert({ ...TILE_ALERT, silenced: { until: '2026-11-26T13:59:59Z' } }, options); + + expect(alert.suppressed).toBeUndefined(); + expect(alert.annotations.silenced_until).toBeUndefined(); + }); + + it('links to what the alert watches', () => { + expect(sourceUrl({ source: 'saved_search', savedSearchId: 's1' })).toBe('http://clickstack:8080/search/s1'); + expect(sourceUrl({ source: 'inline' })).toBe('http://clickstack:8080/chart?alertId=alert%2F1'); + expect(sourceUrl({ source: 'tile' })).toBe('http://clickstack:8080/alerts'); + // No link without the URL of the ClickStack UI. + expect(buildAlert({ id: 'a', source: 'tile', dashboardId: 'd' }, { now }).sourceURL).toBeUndefined(); + }); + + it('writes the condition of each kind of threshold', () => { + expect(condition({ thresholdType: 'above', interval: '5m' })).toBe('>= 5 over 5m'); + expect(condition({ thresholdType: 'below_or_equal' })).toBe('<= 5'); + expect(condition({ thresholdType: 'between', thresholdMax: 9 })).toBe('between 5 and 9'); + expect(condition({ thresholdType: 'anomaly' })).toBe('anomaly 5'); + }); +}); + +describe('buildAlertsParams', () => { + it('lists the firing and pending alerts by default', () => { + expect(buildAlertsParams({}, {})).toEqual({ states: ['ALERT', 'PENDING'] }); + expect(buildAlertsParams({ states: [], sources: [], tags: [], search: ' ' }, {})).toEqual({ + states: ['ALERT', 'PENDING'], + }); + }); + + it('replaces the variables: one tag per value of a variable', () => { + const variableState = { + team: { value: ['checkout', 'platform'], loading: false }, + env: { value: 'prod', loading: false }, + name: { value: 'cart', loading: false }, + }; + + expect( + buildAlertsParams( + { states: ['OK'], sources: ['tile'], tags: ['team:$team', '$env', 'prod'], search: '$name errors' }, + variableState, + ), + ).toEqual({ + states: ['OK'], + sources: ['tile'], + tags: ['team:checkout', 'team:platform', 'prod'], + search: 'cart errors', + }); + }); +}); + +describe('ClickStackAlertsQuery', () => { + it('returns the alerts of ClickStack, with links to its UI', async () => { + const { context, getAlerts } = createContext({ alerts: [TILE_ALERT], total: 1 }); + + const response = await ClickStackAlertsQuery.getAlertsData({ tags: ['prod'] }, context); + + expect(getAlerts).toHaveBeenCalledWith({ states: ['ALERT', 'PENDING'], tags: ['prod'], signal: undefined }); + expect(response.alerts.map((alert) => [alert.name, alert.sourceURL])).toEqual([ + ['Log throughput is unusual', 'http://clickstack:8080/dashboards/dash1?highlightedTileId=tile%201'], + ]); + expect(response.metadata).toEqual({ + executedQueryString: 'GET /api/v2/alerts?state=ALERT&state=PENDING&tag=prod', + }); + }); + + it('warns when not all the alerts are shown', async () => { + const { context } = createContext({ alerts: [{ id: 'a' }], total: 7000 }); + + const response = await ClickStackAlertsQuery.getAlertsData({}, context); + + expect(response.metadata?.notices).toEqual([ + { type: 'warning', message: 'Only the first 1 of the 7000 alerts are shown.' }, + ]); + }); + + it('depends on the variables of its filters and of its datasource', () => { + expect( + ClickStackAlertsQuery.dependsOn?.( + { datasource: '$ds', tags: ['team:$team'], search: '${name}' }, + createContext({ alerts: [], total: 0 }).context, + ), + ).toEqual({ variables: ['team', 'name', 'ds'] }); + }); +}); diff --git a/clickhouse/src/queries/click-stack-alerts-query/get-click-stack-alerts-data.ts b/clickhouse/src/queries/click-stack-alerts-query/get-click-stack-alerts-data.ts new file mode 100644 index 000000000..e36c41c9a --- /dev/null +++ b/clickhouse/src/queries/click-stack-alerts-query/get-click-stack-alerts-data.ts @@ -0,0 +1,82 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { AlertsQueryPlugin, VariableStateMap } from '@perses-dev/plugin-system'; +import { parseVariables, replaceVariables } from '@perses-dev/plugin-system'; +import type { Notice } from '@perses-dev/spec'; + +import type { ClickStackDatasourceClient } from '../../datasources/click-stack-datasource/click-stack-datasource-types'; +import type { ClickStackAlertsParams } from '../../model/click-stack-client'; +import { ALERTS_PATH, buildAlertsSearchParams } from '../../model/click-stack-client'; +import { CLICKSTACK_DATASOURCE_KIND, DEFAULT_CLICKSTACK } from '../../model/click-stack-selectors'; +import { getDatasourceClient } from '../../model/datasource-client'; +import { buildAlerts } from './alerts'; +import type { ClickStackAlertsQuerySpec } from './click-stack-alerts-query-types'; +import { DEFAULT_ALERT_STATES } from './click-stack-alerts-query-types'; + +// Replaces the variables of a tag. A variable with several values gives as many tags, one per value. +function expandTag(tag: string, variableState: VariableStateMap): string[] { + const multiple = parseVariables(tag).find((name) => Array.isArray(variableState[name]?.value)); + const state = multiple === undefined ? undefined : variableState[multiple]; + if (multiple === undefined || state === undefined || !Array.isArray(state.value)) { + return [replaceVariables(tag, variableState)]; + } + return state.value.flatMap((value) => expandTag(tag, { ...variableState, [multiple]: { ...state, value } })); +} + +/** buildAlertsParams returns the filters of the alerts request of a query, with its variables replaced. */ +export function buildAlertsParams( + spec: ClickStackAlertsQuerySpec, + variableState: VariableStateMap, +): ClickStackAlertsParams { + const tags = new Set(); + for (const tag of spec.tags ?? []) { + for (const expanded of expandTag(tag, variableState)) { + if (expanded.trim() !== '') tags.add(expanded.trim()); + } + } + const search = spec.search ? replaceVariables(spec.search, variableState).trim() : ''; + return { + states: spec.states && spec.states.length > 0 ? spec.states : DEFAULT_ALERT_STATES, + ...(spec.sources && spec.sources.length > 0 && { sources: spec.sources }), + ...(tags.size > 0 && { tags: [...tags] }), + ...(search !== '' && { search }), + }; +} + +export const getAlertsData: AlertsQueryPlugin['getAlertsData'] = async ( + spec, + context, + abortSignal, +) => { + const client = await getDatasourceClient( + spec.datasource, + CLICKSTACK_DATASOURCE_KIND, + DEFAULT_CLICKSTACK, + context, + ); + const params = buildAlertsParams(spec, context.variableState); + const { alerts, total } = await client.getAlerts({ ...params, signal: abortSignal }); + + const notices: Notice[] = + total > alerts.length + ? [{ type: 'warning', message: `Only the first ${alerts.length} of the ${total} alerts are shown.` }] + : []; + return { + alerts: buildAlerts(alerts, { uiUrl: client.options.uiUrl, now: Date.now() }), + metadata: { + executedQueryString: `GET ${ALERTS_PATH}?${buildAlertsSearchParams(params).toString()}`, + ...(notices.length > 0 && { notices }), + }, + }; +}; diff --git a/clickhouse/src/queries/click-stack-alerts-query/index.ts b/clickhouse/src/queries/click-stack-alerts-query/index.ts new file mode 100644 index 000000000..a9822ecd6 --- /dev/null +++ b/clickhouse/src/queries/click-stack-alerts-query/index.ts @@ -0,0 +1,18 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export * from './alerts'; +export * from './click-stack-alerts-query-types'; +export * from './ClickStackAlertsQuery'; +export * from './ClickStackAlertsQueryEditor'; +export * from './get-click-stack-alerts-data'; diff --git a/clickhouse/src/queries/index.ts b/clickhouse/src/queries/index.ts index 713234e06..088c0b2d3 100644 --- a/clickhouse/src/queries/index.ts +++ b/clickhouse/src/queries/index.ts @@ -13,3 +13,6 @@ export * from './click-house-time-series-query'; export * from './click-house-log-query'; +export * from './click-house-trace-query'; +export * from './click-house-profile-query'; +export * from './click-stack-alerts-query'; diff --git a/clickhouse/src/queries/query-editor-model.ts b/clickhouse/src/queries/query-editor-model.ts deleted file mode 100644 index 5609beda8..000000000 --- a/clickhouse/src/queries/query-editor-model.ts +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright The Perses Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import type { OptionsEditorProps } from '@perses-dev/plugin-system'; -import { produce } from 'immer'; -import { useState } from 'react'; - -/** - * Generic type for any ClickHouse query spec that has a query field - */ -type ClickHouseQuerySpec = { - query?: string; -}; - -/** - * A hook for managing the `query` state in ClickHouse query specs. Returns the `query` value, along with - * `onChange` and `onBlur` event handlers to the input. Keeps a local copy of the user's input and only syncs those - * changes with the overall spec value once the input is blurred to prevent re-running queries in the panel's preview - * every time the user types. - */ -export function useQueryState( - props: OptionsEditorProps, -): { - query: string; - handleQueryChange: (e: string) => void; - handleQueryBlur: () => void; -} { - const { onChange, value } = props; - - // Local copy of the query's value - const [query, setQuery] = useState(value.query || ''); - - // This is basically "getDerivedStateFromProps" to make sure if spec's value changes external to this component, - // we render with the latest value - const [lastSyncedQuery, setLastSyncedQuery] = useState(value.query); - if (value.query !== lastSyncedQuery) { - setQuery(value.query || ''); - setLastSyncedQuery(value.query); - } - - // Update our local state's copy as the user types - const handleQueryChange = (e: string): void => { - setQuery(e); - }; - - // Propagate changes to the query's value when the input is blurred to avoid constantly re-running queries in the - // PanelPreview - const handleQueryBlur = (): void => { - setLastSyncedQuery(query); - onChange( - produce(value, (draft) => { - draft.query = query; - }), - ); - }; - - return { query, handleQueryChange, handleQueryBlur }; -} diff --git a/clickhouse/src/test/stubs.ts b/clickhouse/src/test/stubs.ts new file mode 100644 index 000000000..241407eb3 --- /dev/null +++ b/clickhouse/src/test/stubs.ts @@ -0,0 +1,59 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { DatasourceStore } from '@perses-dev/plugin-system'; + +import type { ClickHouseClient, ClickHouseQueryParams, ClickHouseQueryResponse } from '../model/click-house-client'; + +/** stubResponse builds the response of a query from its columns, as `[name, type]` pairs, and its rows. */ +export function stubResponse( + columns: Array<[name: string, type: string]>, + rows: unknown[][] = [], + extra: Partial = {}, +): ClickHouseQueryResponse { + return { columns: columns.map(([name, type]) => ({ name, type })), rows, truncated: false, ...extra }; +} + +export interface StubClient extends ClickHouseClient { + /** The statements the client was asked to run, in order. */ + statements: () => string[]; +} + +/** + * stubClient returns a client answering each query with what `respond` returns for its statement. A thrown error + * fails the query. + */ +export function stubClient(respond: (sql: string) => ClickHouseQueryResponse): StubClient { + const queries: ClickHouseQueryParams[] = []; + return { + query: async (params) => { + queries.push(params); + return respond(params.query); + }, + healthCheck: async () => true, + statements: () => queries.map((params) => params.query), + }; +} + +/** stubDatasourceStore returns a datasource store whose datasources all have the given client. */ +export function stubDatasourceStore(client: unknown): DatasourceStore { + return { + getDatasource: vi.fn(), + getDatasourceClient: vi.fn(async () => client), + listDatasourceSelectItems: vi.fn(async () => []), + getLocalDatasources: vi.fn(), + setLocalDatasources: vi.fn(), + getSavedDatasources: vi.fn(), + setSavedDatasources: vi.fn(), + } as unknown as DatasourceStore; +} diff --git a/clickhouse/src/variables/click-house-sql-variable/ClickHouseSQLVariable.tsx b/clickhouse/src/variables/click-house-sql-variable/ClickHouseSQLVariable.tsx new file mode 100644 index 000000000..af464c30a --- /dev/null +++ b/clickhouse/src/variables/click-house-sql-variable/ClickHouseSQLVariable.tsx @@ -0,0 +1,26 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { VariablePlugin } from '@perses-dev/plugin-system'; + +import { queryDependencies } from '../../model/execute-query'; +import type { ClickHouseSQLVariableSpec } from './click-house-sql-variable-types'; +import { ClickHouseSQLVariableEditor } from './ClickHouseSQLVariableEditor'; +import { getVariableOptions } from './get-variable-options'; + +export const ClickHouseSQLVariable: VariablePlugin = { + getVariableOptions, + dependsOn: (spec) => queryDependencies(spec.datasource, spec.query), + OptionsEditorComponent: ClickHouseSQLVariableEditor, + createInitialOptions: () => ({ query: '' }), +}; diff --git a/clickhouse/src/variables/click-house-sql-variable/ClickHouseSQLVariableEditor.tsx b/clickhouse/src/variables/click-house-sql-variable/ClickHouseSQLVariableEditor.tsx new file mode 100644 index 000000000..f91385653 --- /dev/null +++ b/clickhouse/src/variables/click-house-sql-variable/ClickHouseSQLVariableEditor.tsx @@ -0,0 +1,44 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { Stack } from '@mui/material'; +import type { OptionsEditorProps } from '@perses-dev/plugin-system'; +import type { ReactElement } from 'react'; + +import { ClickHouseDatasourceSelect, QueryExamples, SQLField } from '../../components'; +import { VARIABLE_EXAMPLES } from '../../components/query-examples'; +import type { ClickHouseSQLVariableSpec } from './click-house-sql-variable-types'; + +type ClickHouseSQLVariableEditorProps = OptionsEditorProps; + +export function ClickHouseSQLVariableEditor(props: ClickHouseSQLVariableEditorProps): ReactElement { + const { onChange, value, isReadonly } = props; + + return ( + + onChange({ ...value, datasource })} + isReadonly={isReadonly} + /> + onChange({ ...value, query })} + placeholder="Enter a ClickHouse SQL query returning the values of the variable" + isReadonly={isReadonly} + /> + + + ); +} diff --git a/clickhouse/src/variables/click-house-sql-variable/click-house-sql-variable-types.ts b/clickhouse/src/variables/click-house-sql-variable/click-house-sql-variable-types.ts new file mode 100644 index 000000000..e7b6afc6d --- /dev/null +++ b/clickhouse/src/variables/click-house-sql-variable/click-house-sql-variable-types.ts @@ -0,0 +1,16 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { ClickHouseQuerySpec } from '../../model/execute-query'; + +export type ClickHouseSQLVariableSpec = ClickHouseQuerySpec; diff --git a/clickhouse/src/variables/click-house-sql-variable/click-house-sql-variable.test.ts b/clickhouse/src/variables/click-house-sql-variable/click-house-sql-variable.test.ts new file mode 100644 index 000000000..480b1a300 --- /dev/null +++ b/clickhouse/src/variables/click-house-sql-variable/click-house-sql-variable.test.ts @@ -0,0 +1,82 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { VariablePlugin } from '@perses-dev/plugin-system'; + +import { stubClient, stubDatasourceStore, stubResponse } from '../../test/stubs'; +import { ClickHouseSQLVariable } from './ClickHouseSQLVariable'; +import { buildVariableOptions } from './get-variable-options'; + +type VariableContext = Parameters[1]; + +describe('buildVariableOptions', () => { + it('takes the values from the first column, once each', () => { + expect( + buildVariableOptions( + stubResponse( + [ + ['ServiceName', 'String'], + ['spans', 'UInt64'], + ], + [['api', '3'], ['web', '2'], ['api', '1'], [''], [null]], + ), + ), + ).toEqual([ + { value: 'api', label: 'api' }, + { value: 'web', label: 'web' }, + ]); + }); + + it('takes the values and their labels from the "value" and "label" columns', () => { + expect( + buildVariableOptions( + stubResponse( + [ + ['Label', 'String'], + ['Value', 'UInt32'], + ], + [ + ['Checkout', 7], + ['', 8], + ], + ), + ), + ).toEqual([ + { value: '7', label: 'Checkout' }, + { value: '8', label: '8' }, + ]); + }); +}); + +describe('ClickHouseSQLVariable', () => { + it('runs the query with the time range and the other variables', async () => { + const client = stubClient(() => stubResponse([['SpanName', 'String']], [['GET /cart']])); + const context = { + datasourceStore: stubDatasourceStore(client), + variables: { service: { value: ['api'], loading: false } }, + timeRange: { start: new Date('2026-01-01T10:00:00.000Z'), end: new Date('2026-01-01T11:00:00.000Z') }, + } as unknown as VariableContext; + const spec = { + query: + 'SELECT DISTINCT SpanName FROM otel_traces WHERE $__timeFilter(Timestamp) AND ServiceName IN (${service:sqlstring})', + }; + + await expect(ClickHouseSQLVariable.getVariableOptions(spec, context)).resolves.toEqual({ + data: [{ value: 'GET /cart', label: 'GET /cart' }], + }); + expect(client.statements()).toEqual([ + "SELECT DISTINCT SpanName FROM otel_traces WHERE (Timestamp >= toDateTime(1767261600) AND Timestamp <= toDateTime(1767265200)) AND ServiceName IN ('api')", + ]); + expect(ClickHouseSQLVariable.dependsOn?.(spec, context)).toEqual({ variables: ['service'] }); + }); +}); diff --git a/clickhouse/src/variables/click-house-sql-variable/get-variable-options.ts b/clickhouse/src/variables/click-house-sql-variable/get-variable-options.ts new file mode 100644 index 000000000..36cf5b353 --- /dev/null +++ b/clickhouse/src/variables/click-house-sql-variable/get-variable-options.ts @@ -0,0 +1,57 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { VariableOption, VariablePlugin } from '@perses-dev/plugin-system'; + +import type { ClickHouseQueryResponse } from '../../model/click-house-client'; +import { findColumn } from '../../model/click-house-types'; +import { executeQuery } from '../../model/execute-query'; +import { toText } from '../../model/values'; +import type { ClickHouseSQLVariableSpec } from './click-house-sql-variable-types'; + +/** + * buildVariableOptions converts a result into the options of a variable. The value of an option is the `value` + * column of a row, or else its first column, and its label is the `label` column, or else the value. Rows without a + * value are left out, and so are the ones repeating a value. + */ +export function buildVariableOptions(response: ClickHouseQueryResponse): VariableOption[] { + const { columns, rows } = response; + if (columns.length === 0) return []; + const named = findColumn(columns, ['value', '__value']); + const value = named === -1 ? 0 : named; + const label = findColumn(columns, ['label', '__text']); + const options = new Map(); + for (const row of rows) { + const optionValue = toText(row[value]); + if (optionValue === '' || options.has(optionValue)) continue; + const optionLabel = label === -1 ? '' : toText(row[label]); + options.set(optionValue, { value: optionValue, label: optionLabel || optionValue }); + } + return [...options.values()]; +} + +export const getVariableOptions: VariablePlugin['getVariableOptions'] = async ( + spec, + context, + abortSignal, +) => { + if (!spec.query?.trim()) { + return { data: [] }; + } + const result = await executeQuery( + spec, + { datasourceStore: context.datasourceStore, variableState: context.variables, timeRange: context.timeRange }, + abortSignal, + ); + return { data: buildVariableOptions(result) }; +}; diff --git a/clickhouse/src/variables/click-house-sql-variable/index.ts b/clickhouse/src/variables/click-house-sql-variable/index.ts new file mode 100644 index 000000000..197f25493 --- /dev/null +++ b/clickhouse/src/variables/click-house-sql-variable/index.ts @@ -0,0 +1,17 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export * from './ClickHouseSQLVariable'; +export * from './ClickHouseSQLVariableEditor'; +export * from './get-variable-options'; +export * from './click-house-sql-variable-types'; diff --git a/clickhouse/src/variables/index.ts b/clickhouse/src/variables/index.ts new file mode 100644 index 000000000..00636edd1 --- /dev/null +++ b/clickhouse/src/variables/index.ts @@ -0,0 +1,14 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export * from './click-house-sql-variable'; diff --git a/docs/clickhouse/README.md b/docs/clickhouse/README.md index 6b7c58682..ce9f62e22 100644 --- a/docs/clickhouse/README.md +++ b/docs/clickhouse/README.md @@ -1,16 +1,17 @@ --- tags: - - datasource + - datasource --- + # ClickHouse plugins -The ClickHouse package includes several plugins that provide comprehensive support for ClickHouse database in Perses dashboards. +The ClickHouse package includes plugins that run SQL against [ClickHouse](https://clickhouse.com) through its HTTP interface, so Perses can display the metrics, logs, traces and profiles stored in it. They read any table, and know the tables written by the [ClickHouse exporter](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/exporter/clickhouseexporter) of the OpenTelemetry Collector and by [ClickStack](https://clickhouse.com/docs/use-cases/observability/clickstack). The package also lists the alerts of ClickStack. -## Datasource (`ClickHouseDatasource`) +See [Writing queries](./queries.md) for the macros, the variables and the columns each query expects. -The ClickHouse datasource enables connection between Perses and your ClickHouse database for analytical querying. It works with various visualization panels and supports SQL queries. +## Datasource (`ClickHouseDatasource`) -It supports the [proxy](https://perses.dev/perses/docs/concepts/proxy/) feature of Perses that allows to restrict the access to your data source. +The ClickHouse datasource connects Perses to the HTTP interface of a ClickHouse server. It supports the [proxy](https://perses.dev/perses/docs/concepts/proxy/) feature of Perses, which is the recommended setup: the credentials of the ClickHouse user stay in a Perses Secret. Queries are sent as read-only, but only the grants of the ClickHouse user are a guarantee: connect with a read-only user. See also technical docs related to this plugin: @@ -19,18 +20,82 @@ See also technical docs related to this plugin: ## Time Series Query (`ClickHouseTimeSeriesQuery`) -The ClickHouse time series query plugin enables executing SQL queries against your ClickHouse database for time-based data visualization. It supports complex analytical queries and aggregations for metrics and time series data. +The ClickHouse time series query runs a SQL query and reads its numeric columns as values and its other columns as labels splitting the rows into series. A query without a time column is a table. It also reads the histograms and the exemplars of the OpenTelemetry metric tables. See also technical docs related to this plugin: +- [Writing time series queries](./queries.md#time-series-queries) - [Data model](./model.md#clickhousetimeseriesquery) - [Dashboard-as-Code Go lib](./go-sdk/timeseries-query.md) ## Log Query (`ClickHouseLogQuery`) -The ClickHouse log query plugin enables querying log data stored in your ClickHouse database. It supports log filtering, searching, and analysis for log management use cases. +The ClickHouse log query runs a SQL query whose rows are logs: a time column, a line and labels. In the log explorer, it also charts the volume of the logs over time, by level. See also technical docs related to this plugin: +- [Writing log queries](./queries.md#log-queries) - [Data model](./model.md#clickhouselogquery) - [Dashboard-as-Code Go lib](./go-sdk/log-query.md) + +## Trace Query (`ClickHouseTraceQuery`) + +The ClickHouse trace query reads the traces stored in the OpenTelemetry schema. A trace ID displays the trace, and a SQL query returning spans searches their traces. + +See also technical docs related to this plugin: + +- [Writing trace queries](./queries.md#trace-queries) +- [Data model](./model.md#clickhousetracequery) +- [Dashboard-as-Code Go lib](./go-sdk/trace-query.md) + +## Profile Query (`ClickHouseProfileQuery`) + +The ClickHouse profile query builds a flame graph from the samples returned by a SQL query, such as the ones of the OpenTelemetry profiles table. + +See also technical docs related to this plugin: + +- [Writing profile queries](./queries.md#profile-queries) +- [Data model](./model.md#clickhouseprofilequery) +- [Dashboard-as-Code Go lib](./go-sdk/profile-query.md) + +## Variable (`ClickHouseSQLVariable`) + +The ClickHouse SQL variable lists the values of a dashboard variable with a SQL query. + +See also technical docs related to this plugin: + +- [Writing variable queries](./queries.md#variable-queries) +- [Data model](./model.md#clickhousesqlvariable) +- [Dashboard-as-Code Go lib](./go-sdk/variable.md) + +## Annotation (`ClickHouseSQLAnnotation`) + +The ClickHouse SQL annotation marks the events returned by a SQL query, such as deployments or alert notifications, on the charts of a dashboard. + +See also technical docs related to this plugin: + +- [Writing annotation queries](./queries.md#annotation-queries) +- [Data model](./model.md#clickhousesqlannotation) +- [Dashboard-as-Code Go lib](./go-sdk/annotation.md) + +## Explorer (`ClickHouseExplorer`) + +The ClickHouse explorer runs ad hoc queries from the Explore page of Perses: time series as a graph or as a table, trace searches and traces, and profiles. Logs are explored with the log explorer, which runs the log queries of every datasource. + +## ClickStack Datasource (`ClickStackDatasource`) + +The ClickStack datasource connects Perses to the API of ClickStack (HyperDX). ClickStack only answers to the browsers of its own UI and requires an API key, so it is reached through the [proxy](https://perses.dev/perses/docs/concepts/proxy/) of Perses, with a Secret holding the key. + +See also technical docs related to this plugin: + +- [Data model](./model.md#clickstackdatasource) +- [Dashboard-as-Code Go lib](./go-sdk/clickstack-datasource.md) + +## ClickStack Alerts Query (`ClickStackAlertsQuery`) + +The ClickStack alerts query lists the alerts defined in ClickStack with their current state, to display them in an alert table. + +See also technical docs related to this plugin: + +- [Data model](./model.md#clickstackalertsquery) +- [Dashboard-as-Code Go lib](./go-sdk/clickstack-alerts-query.md) diff --git a/docs/clickhouse/go-sdk/annotation.md b/docs/clickhouse/go-sdk/annotation.md new file mode 100644 index 000000000..d1f26db62 --- /dev/null +++ b/docs/clickhouse/go-sdk/annotation.md @@ -0,0 +1,59 @@ +# ClickHouse SQL Annotation Go SDK + +## Constructor + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/annotation/sql" + +var options []sql.Option +sql.ClickHouseSQL("SELECT deployed_at AS time, version AS title FROM deployments WHERE $__timeFilter(deployed_at)", options...) +``` + +Need to provide the SQL query expression and a list of options. See [Writing annotation queries](../queries.md#annotation-queries). + +## Default options + +- [Query()](#query): with the expression provided in the constructor. + +## Available options + +#### Query + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/annotation/sql" + +sql.Query("SELECT started AS start, finished AS end, name AS title FROM maintenances WHERE $__timeFilter(started)") +``` + +Define the SQL query expression. + +#### Datasource + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/annotation/sql" + +sql.Datasource("MyClickHouseDatasource") +``` + +Define the datasource the query will use. + +## Example + +```golang +package main + +import ( + "github.com/perses/perses/go-sdk/annotation" + "github.com/perses/perses/go-sdk/dashboard" + "github.com/perses/plugins/clickhouse/sdk/go/annotation/sql" +) + +func main() { + dashboard.New("ClickHouse Dashboard", + dashboard.AddAnnotation("Deployments", + sql.ClickHouseSQL("SELECT deployed_at AS time, version AS title, service FROM deployments WHERE $__timeFilter(deployed_at)"), + annotation.Color("#1f77b4"), + ), + ) +} +``` diff --git a/docs/clickhouse/go-sdk/clickstack-alerts-query.md b/docs/clickhouse/go-sdk/clickstack-alerts-query.md new file mode 100644 index 000000000..4480d98ca --- /dev/null +++ b/docs/clickhouse/go-sdk/clickstack-alerts-query.md @@ -0,0 +1,98 @@ +# ClickStack Alerts Query Go SDK + +## Constructor + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/query/alerts" + +var options []alerts.Option +alerts.AlertsQuery(options...) +``` + +Need a list of options. Without options, the query lists the firing and the pending alerts. + +## Default options + +- None + +## Available options + +#### Datasource + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/query/alerts" + +alerts.Datasource("MyClickStackDatasource") +``` + +Define the datasource the query will use. + +#### States + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/query/alerts" + +alerts.States(alerts.StateAlert, alerts.StatePending, alerts.StateOK) +``` + +Define the states of the alerts to list: `StateAlert` (firing), `StatePending` and `StateOK`. By default, the firing and the pending alerts are listed. + +#### Sources + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/query/alerts" + +alerts.Sources(alerts.SourceSavedSearch, alerts.SourceTile) +``` + +Define what the alerts to list watch: `SourceSavedSearch`, `SourceTile` (a tile of a dashboard) or `SourceInline` (their own chart). By default, all the alerts are listed. + +#### Tags + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/query/alerts" + +alerts.Tags("team:$team", "production") +``` + +List the alerts with one of the tags. Variables are supported: a variable with several values is as many tags. + +#### Search + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/query/alerts" + +alerts.Search("checkout") +``` + +List the alerts whose name contains the text. Variables are supported. + +## Example + +```golang +package main + +import ( + "github.com/perses/perses/go-sdk/dashboard" + "github.com/perses/perses/go-sdk/panel" + panelgroup "github.com/perses/perses/go-sdk/panel-group" + alerttable "github.com/perses/plugins/alertmanager/sdk/go/panel" + "github.com/perses/plugins/clickhouse/sdk/go/clickstack/query/alerts" +) + +func main() { + dashboard.New("ClickStack Alerts Dashboard", + dashboard.AddPanelGroup("Alerts", + panelgroup.AddPanel("Alerts of the platform team", + alerttable.AlertTable(), + panel.AddQuery( + alerts.AlertsQuery( + alerts.States(alerts.StateAlert, alerts.StatePending, alerts.StateOK), + alerts.Tags("team:platform"), + ), + ), + ), + ), + ) +} +``` diff --git a/docs/clickhouse/go-sdk/clickstack-datasource.md b/docs/clickhouse/go-sdk/clickstack-datasource.md new file mode 100644 index 000000000..f8ae998b3 --- /dev/null +++ b/docs/clickhouse/go-sdk/clickstack-datasource.md @@ -0,0 +1,74 @@ +# ClickStack Datasource Go SDK + +## Constructor + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/datasource" + +var options []datasource.Option +datasource.ClickStack(options...) +``` + +Need a list of options. At least direct URL or proxy URL, in order to work. + +## Default options + +- None + +## Available options + +#### Direct URL + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/datasource" + +datasource.DirectURL("http://clickstack.example.com:8000") +``` + +Configure the access to the API of ClickStack with a direct URL. ClickStack only accepts the requests of the browsers of its own UI: prefer a proxy. + +#### Proxy + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/datasource" + +datasource.HTTPProxy("http://clickstack.example.com:8000", httpProxyOptions...) +``` + +Configure the access to the API of ClickStack with a proxy URL. More info at [HTTP Proxy](https://perses.dev/perses/docs/dac/go/helper/http-proxy). The secret of the proxy holds the API key of ClickStack as a bearer token. + +#### UI URL + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/clickstack/datasource" + +datasource.UIURL("https://clickstack.example.com") +``` + +Define the URL of the ClickStack UI, as users open it in their browser. The alerts link to it. + +## Example + +```golang +package main + +import ( + "github.com/perses/perses/go-sdk/dashboard" + "github.com/perses/perses/go-sdk/http" + + csDs "github.com/perses/plugins/clickhouse/sdk/go/clickstack/datasource" +) + +func main() { + dashboard.New("ClickStack Dashboard", + dashboard.AddDatasource("clickstack", csDs.ClickStack( + csDs.UIURL("https://clickstack.example.com"), + csDs.HTTPProxy("http://clickstack.example.com:8000", + http.AddAllowedEndpoint("GET", "^/api/v2/alerts$"), + http.AddAllowedEndpoint("GET", "^/api/v2$"), + http.Secret("clickstack_api_key"), + ), + )), + ) +} +``` diff --git a/docs/clickhouse/go-sdk/datasource.md b/docs/clickhouse/go-sdk/datasource.md index fad339356..80838a4c3 100644 --- a/docs/clickhouse/go-sdk/datasource.md +++ b/docs/clickhouse/go-sdk/datasource.md @@ -37,6 +37,16 @@ datasource.HTTPProxy("https://current-domain-name.io", httpProxyOptions...) Configure the access to the ClickHouse datasource with a proxy URL. More info at [HTTP Proxy](https://perses.dev/perses/docs/dac/go/helper/http-proxy). +#### Database + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/datasource" + +datasource.Database("otel") +``` + +Define the database the table names without a database are read from. By default, it is the database named `default`. + ## Example ```golang @@ -44,13 +54,21 @@ package main import ( "github.com/perses/perses/go-sdk/dashboard" - + "github.com/perses/perses/go-sdk/http" + chDs "github.com/perses/plugins/clickhouse/sdk/go/datasource" ) func main() { dashboard.New("ClickHouse Dashboard", - dashboard.AddDatasource("clickhouseMain", chDs.ClickHouse(chDs.DirectURL("http://clickhouse.example.com:8123"))), + dashboard.AddDatasource("clickhouseMain", chDs.ClickHouse( + chDs.Database("otel"), + chDs.HTTPProxy("http://clickhouse.example.com:8123", + http.AddAllowedEndpoint("POST", "^/$"), + http.AddAllowedEndpoint("GET", "^/ping$"), + http.Secret("clickhouse_secret_config"), + ), + )), ) } ``` diff --git a/docs/clickhouse/go-sdk/log-query.md b/docs/clickhouse/go-sdk/log-query.md index 1d52a15aa..ea62686df 100644 --- a/docs/clickhouse/go-sdk/log-query.md +++ b/docs/clickhouse/go-sdk/log-query.md @@ -6,10 +6,10 @@ import log "github.com/perses/plugins/clickhouse/sdk/go/query/log" var options []log.Option -log.ClickHouseLogQuery("SELECT timestamp, level, message FROM logs WHERE level = 'ERROR' ORDER BY timestamp DESC", options...) +log.ClickHouseLogQuery("SELECT Timestamp, Body, SeverityText FROM otel_logs WHERE $__timeFilter(Timestamp) ORDER BY Timestamp DESC LIMIT 1000", options...) ``` -Need to provide the SQL query expression and a list of options. +Need to provide the SQL query expression and a list of options. See [Writing log queries](../queries.md#log-queries). ## Default options @@ -22,7 +22,7 @@ Need to provide the SQL query expression and a list of options. ```golang import log "github.com/perses/plugins/clickhouse/sdk/go/query/log" -log.Query("SELECT timestamp, level, message, service FROM application_logs WHERE level IN ('ERROR', 'WARN')") +log.Query("SELECT Timestamp, Body, SeverityText, ServiceName FROM otel_logs WHERE $__timeFilter(Timestamp) AND SeverityText IN ('ERROR', 'WARN')") ``` Define the SQL query expression. @@ -57,20 +57,15 @@ func main() { logstable.LogsTable(), panel.AddQuery( log.ClickHouseLogQuery(` - SELECT - timestamp, - level, - message, - service - FROM application_logs - WHERE level = 'ERROR' - AND timestamp >= now() - INTERVAL 1 HOUR - ORDER BY timestamp DESC + SELECT Timestamp, Body, SeverityText, ServiceName + FROM otel_logs + WHERE $__timeFilter(Timestamp) AND SeverityText = 'ERROR' + ORDER BY Timestamp DESC LIMIT 1000 `), ), ), ), ) -}``` +} ``` diff --git a/docs/clickhouse/go-sdk/profile-query.md b/docs/clickhouse/go-sdk/profile-query.md new file mode 100644 index 000000000..f87f0c3dc --- /dev/null +++ b/docs/clickhouse/go-sdk/profile-query.md @@ -0,0 +1,72 @@ +# ClickHouse Profile Query Go SDK + +## Constructor + +```golang +import profile "github.com/perses/plugins/clickhouse/sdk/go/query/profile" + +var options []profile.Option +profile.ClickHouseProfileQuery("SELECT Timestamp AS time, FunctionNames AS stack, length(TimestampsUnixNano) AS value FROM otel_profiles WHERE $__timeFilter(Timestamp)", options...) +``` + +Need to provide the SQL query expression and a list of options. See [Writing profile queries](../queries.md#profile-queries). + +## Default options + +- [Query()](#query): with the expression provided in the constructor. + +## Available options + +#### Query + +```golang +import profile "github.com/perses/plugins/clickhouse/sdk/go/query/profile" + +profile.Query("SELECT FunctionNames AS stack FROM otel_profiles WHERE $__timeFilter(Timestamp) AND ServiceName = 'checkout'") +``` + +Define the SQL query expression. + +#### Datasource + +```golang +import profile "github.com/perses/plugins/clickhouse/sdk/go/query/profile" + +profile.Datasource("MyClickHouseDatasource") +``` + +Define the datasource the query will use. + +## Example + +```golang +package main + +import ( + "github.com/perses/perses/go-sdk/dashboard" + "github.com/perses/perses/go-sdk/panel" + panelgroup "github.com/perses/perses/go-sdk/panel-group" + profile "github.com/perses/plugins/clickhouse/sdk/go/query/profile" + flamechart "github.com/perses/plugins/flamechart/sdk/go" +) + +func main() { + dashboard.New("ClickHouse Profiles Dashboard", + dashboard.AddPanelGroup("Profiles", + panelgroup.AddPanel("CPU of the checkout service", + flamechart.Chart(), + panel.AddQuery( + profile.ClickHouseProfileQuery(` + SELECT + Timestamp AS time, + arrayMap((name, file) -> if(name != '', name, file), FunctionNames, MappingFileNames) AS stack, + length(TimestampsUnixNano) AS value + FROM otel_profiles + WHERE $__timeFilter(Timestamp) AND ServiceName = 'checkout' + `), + ), + ), + ), + ) +} +``` diff --git a/docs/clickhouse/go-sdk/timeseries-query.md b/docs/clickhouse/go-sdk/timeseries-query.md index 968537328..7b4a6f18d 100644 --- a/docs/clickhouse/go-sdk/timeseries-query.md +++ b/docs/clickhouse/go-sdk/timeseries-query.md @@ -6,10 +6,10 @@ import timeseries "github.com/perses/plugins/clickhouse/sdk/go/query/time-series" var options []timeseries.Option -timeseries.ClickHouseTimeSeriesQuery("SELECT toStartOfMinute(timestamp) as time, count() as requests FROM events GROUP BY time ORDER BY time", options...) +timeseries.ClickHouseTimeSeriesQuery("SELECT $__timeInterval(Timestamp) AS time, count() AS requests FROM otel_traces WHERE $__timeFilter(Timestamp) GROUP BY time ORDER BY time", options...) ``` -Need to provide the SQL query expression and a list of options. +Need to provide the SQL query expression and a list of options. See [Writing time series queries](../queries.md#time-series-queries). ## Default options @@ -22,7 +22,7 @@ Need to provide the SQL query expression and a list of options. ```golang import timeseries "github.com/perses/plugins/clickhouse/sdk/go/query/time-series" -timeseries.Query("SELECT toStartOfHour(timestamp) as time, avg(response_time) FROM requests GROUP BY time ORDER BY time") +timeseries.Query("SELECT $__timeInterval(Timestamp) AS time, avg(Duration) AS duration FROM otel_traces WHERE $__timeFilter(Timestamp) GROUP BY time ORDER BY time") ``` Define the SQL query expression. @@ -37,6 +37,37 @@ timeseries.Datasource("MyClickHouseDatasource") Define the datasource the query will use. +#### SeriesNameFormat + +```golang +import timeseries "github.com/perses/plugins/clickhouse/sdk/go/query/time-series" + +timeseries.SeriesNameFormat("{{ServiceName}} - {{SpanName}}") +``` + +Define the format of the names of the series. Each `{{label}}` is replaced by the value of the label of the series. + +#### ExemplarQuery + +```golang +import timeseries "github.com/perses/plugins/clickhouse/sdk/go/query/time-series" + +timeseries.ExemplarQuery("SELECT Timestamp AS time, Duration / 1e6 AS value, ServiceName, TraceId AS trace_id FROM otel_traces WHERE $__timeFilter(Timestamp) ORDER BY Duration DESC LIMIT 100") +``` + +Define the SQL query expression returning the exemplars of the series. + +#### MinStep + +```golang +import "time" +import timeseries "github.com/perses/plugins/clickhouse/sdk/go/query/time-series" + +timeseries.MinStep(time.Minute) +``` + +Define the lower bound of the interval of the query, which is the value of the `$__interval_s` family of macros. See [Min step](../queries.md#min-step). + ## Example ```golang @@ -57,17 +88,18 @@ func main() { timeseries.Chart(), panel.AddQuery( clickhousequery.ClickHouseTimeSeriesQuery(` - SELECT - toStartOfMinute(timestamp) as time, - count() as requests - FROM http_logs - WHERE timestamp >= now() - INTERVAL 1 HOUR - GROUP BY time + SELECT + $__timeInterval(Timestamp) AS time, + ServiceName, + count() / $__interval_s AS rps + FROM otel_traces + WHERE $__timeFilter(Timestamp) AND SpanKind = 'Server' + GROUP BY time, ServiceName ORDER BY time - `), + `, clickhousequery.SeriesNameFormat("{{ServiceName}}")), ), ), ), ) -}``` +} ``` diff --git a/docs/clickhouse/go-sdk/trace-query.md b/docs/clickhouse/go-sdk/trace-query.md new file mode 100644 index 000000000..5de379e6b --- /dev/null +++ b/docs/clickhouse/go-sdk/trace-query.md @@ -0,0 +1,89 @@ +# ClickHouse Trace Query Go SDK + +## Constructor + +```golang +import trace "github.com/perses/plugins/clickhouse/sdk/go/query/trace" + +var options []trace.Option +trace.ClickHouseTraceQuery("SELECT TraceId, Timestamp FROM otel_traces WHERE $__timeFilter(Timestamp) AND StatusCode = 'Error'", options...) +``` + +Need to provide a trace ID, a variable holding one, or the SQL query expression of a search, and a list of options. See [Writing trace queries](../queries.md#trace-queries). + +## Default options + +- [Query()](#query): with the expression provided in the constructor. + +## Available options + +#### Query + +```golang +import trace "github.com/perses/plugins/clickhouse/sdk/go/query/trace" + +trace.Query("$traceId") +``` + +Define the trace ID, or the SQL query expression of the search. + +#### Datasource + +```golang +import trace "github.com/perses/plugins/clickhouse/sdk/go/query/trace" + +trace.Datasource("MyClickHouseDatasource") +``` + +Define the datasource the query will use. + +#### Table + +```golang +import trace "github.com/perses/plugins/clickhouse/sdk/go/query/trace" + +trace.Table("otel.otel_traces") +``` + +Define the table of the spans, in the schema of the ClickHouse exporter of the OpenTelemetry Collector: `table` or `database.table`. By default, it is `otel_traces`. + +#### Limit + +```golang +import trace "github.com/perses/plugins/clickhouse/sdk/go/query/trace" + +trace.Limit(50) +``` + +Limit the number of traces returned by a search. By default, it is 20. + +## Example + +```golang +package main + +import ( + "github.com/perses/perses/go-sdk/dashboard" + "github.com/perses/perses/go-sdk/panel" + panelgroup "github.com/perses/perses/go-sdk/panel-group" + trace "github.com/perses/plugins/clickhouse/sdk/go/query/trace" + tracetable "github.com/perses/plugins/tracetable/sdk/go" +) + +func main() { + dashboard.New("ClickHouse Traces Dashboard", + dashboard.AddPanelGroup("Traces", + panelgroup.AddPanel("Failed requests", + tracetable.Chart(), + panel.AddQuery( + trace.ClickHouseTraceQuery(` + SELECT TraceId, Timestamp + FROM otel_traces + WHERE $__timeFilter(Timestamp) AND StatusCode = 'Error' + `, trace.Limit(50)), + ), + ), + ), + ) +} +``` diff --git a/docs/clickhouse/go-sdk/variable.md b/docs/clickhouse/go-sdk/variable.md new file mode 100644 index 000000000..67d799818 --- /dev/null +++ b/docs/clickhouse/go-sdk/variable.md @@ -0,0 +1,62 @@ +# ClickHouse SQL Variable Go SDK + +## Constructor + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/variable/sql" + +var options []sql.Option +sql.ClickHouseSQL("SELECT DISTINCT ServiceName FROM otel_traces WHERE $__timeFilter(Timestamp) ORDER BY ServiceName", options...) +``` + +Need to provide the SQL query expression and a list of options. See [Writing variable queries](../queries.md#variable-queries). + +## Default options + +- [Query()](#query): with the expression provided in the constructor. + +## Available options + +#### Query + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/variable/sql" + +sql.Query("SELECT DISTINCT SpanName AS value FROM otel_traces WHERE ServiceName IN (${service:sqlstring})") +``` + +Define the SQL query expression. + +#### Datasource + +```golang +import "github.com/perses/plugins/clickhouse/sdk/go/variable/sql" + +sql.Datasource("MyClickHouseDatasource") +``` + +Define the datasource the query will use. + +## Example + +```golang +package main + +import ( + "github.com/perses/perses/go-sdk/dashboard" + listvariable "github.com/perses/perses/go-sdk/variable/list-variable" + "github.com/perses/plugins/clickhouse/sdk/go/variable/sql" +) + +func main() { + dashboard.New("ClickHouse Dashboard", + dashboard.AddVariable("service", + listvariable.List( + sql.ClickHouseSQL("SELECT DISTINCT ServiceName FROM otel_traces WHERE $__timeFilter(Timestamp) ORDER BY ServiceName"), + listvariable.AllowAllValue(true), + listvariable.AllowMultiple(true), + ), + ), + ) +} +``` diff --git a/docs/clickhouse/model.md b/docs/clickhouse/model.md index aa09a1556..a6941e54b 100644 --- a/docs/clickhouse/model.md +++ b/docs/clickhouse/model.md @@ -1,6 +1,8 @@ # ClickHouse plugin models -This documentation provides the definition of the different plugins related to ClickHouse. +This documentation provides the definition of the different plugins related to ClickHouse and ClickStack. + +See [Writing queries](./queries.md) for the SQL each query expects. ## ClickHouseDatasource @@ -9,15 +11,25 @@ ClickHouse as a datasource is basically an HTTP server. So we need to define an ```yaml kind: "ClickHouseDatasource" spec: - # It is the url of the datasource. + # It is the url of the HTTP interface of ClickHouse. # Leave it empty if you don't want to access the datasource directly from the UI. # You should define a proxy if you want to access the datasource through the Perses' server. directUrl: # Optional # It is the http configuration that will be used by the Perses' server to redirect to the datasource any query sent by the UI. proxy: # Optional + + # The database the table names without a database are read from. + # By default, it is the database named `default`. + database: # Optional ``` +Queries are sent with `POST` on the root path of the HTTP interface, and the connection test calls `GET /ping`: these are the two endpoints a proxy has to allow. A proxy that only allows `GET` on the root path still works: queries are then sent in the URL, which limits their size. Until it allows `GET ^/ping$` too, the connection test of such a datasource fails, and its editor says so. + +The plugin asks ClickHouse to run every query as read-only, but a datasource is only as restricted as its ClickHouse user: use a user that is only granted `SELECT` on the tables to display. + +With a direct URL, the browser calls ClickHouse itself, without credentials: it only works with a ClickHouse user that needs no password. + ### HTTP Proxy specification See [common plugin definitions](https://perses.dev/perses/docs/plugins/common/#http-proxy-specification). @@ -51,14 +63,15 @@ spec: plugin: kind: "ClickHouseDatasource" spec: + database: "otel" proxy: kind: "HTTPProxy" spec: url: "http://clickhouse.example.com:8123" allowedEndpoints: - - endpointPattern: "/?" + - endpointPattern: "^/$" method: "POST" - - endpointPattern: "/ping" + - endpointPattern: "^/ping$" method: "GET" secret: "clickhouse_secret_config" ``` @@ -77,11 +90,20 @@ spec: # See the documentation about the datasources to understand how it is selected. datasource: # Optional - # The output format for the query results - format: # Optional + # The format of the names of the series. Each `{{label}}` is replaced by the value of the label of the series. + seriesNameFormat: # Optional + + # The SQL expression returning the exemplars of the series. + exemplarQuery: # Optional + + # The lower bound of the interval of the query, which is the value of the `$__interval_s` family of macros. + # A duration, such as `1m`, or a variable holding one. + minStep: # Optional ``` - See [ClickHouse Datasource selector](#clickhouse-datasource-selector) +- See [Writing time series queries](./queries.md#time-series-queries) +- See [Min step](./queries.md#min-step) ### Example @@ -93,7 +115,8 @@ spec: plugin: kind: "ClickHouseTimeSeriesQuery" spec: - query: "SELECT toStartOfMinute(timestamp) as time, count() as requests FROM http_logs WHERE timestamp >= now() - INTERVAL 1 HOUR GROUP BY time ORDER BY time" + query: "SELECT $__timeInterval(Timestamp) AS time, ServiceName, count() AS requests FROM otel_traces WHERE $__timeFilter(Timestamp) GROUP BY time, ServiceName ORDER BY time" + seriesNameFormat: "{{ServiceName}}" ``` ## ClickHouseLogQuery @@ -109,12 +132,10 @@ spec: # `datasource` is a datasource selector. If not provided, the default ClickHouseDatasource is used. # See the documentation about the datasources to understand how it is selected. datasource: # Optional - - # The output format for the query results - format: # Optional ``` - See [ClickHouse Datasource selector](#clickhouse-datasource-selector) +- See [Writing log queries](./queries.md#log-queries) ### Example @@ -126,7 +147,288 @@ spec: plugin: kind: "ClickHouseLogQuery" spec: - query: "SELECT timestamp, level, message, service FROM application_logs WHERE level = 'ERROR' AND timestamp >= now() - INTERVAL 1 HOUR ORDER BY timestamp DESC LIMIT 1000" + query: "SELECT Timestamp, Body, SeverityText, ServiceName FROM otel_logs WHERE $__timeFilter(Timestamp) AND SeverityText = 'ERROR' ORDER BY Timestamp DESC LIMIT 1000" +``` + +## ClickHouseTraceQuery + +Perses supports trace queries for ClickHouse: `ClickHouseTraceQuery`. + +```yaml +kind: "ClickHouseTraceQuery" +spec: + # `query` is either a trace ID, or a variable holding one, to read a trace, + # or the SQL expression returning the `TraceId` and `Timestamp` columns of the spans to search for. + query: + + # `datasource` is a datasource selector. If not provided, the default ClickHouseDatasource is used. + # See the documentation about the datasources to understand how it is selected. + datasource: # Optional + + # The table of the spans, in the schema of the ClickHouse exporter of the OpenTelemetry Collector: + # `table` or `database.table`. By default, it is `otel_traces`. + table: # Optional + + # The maximum number of traces returned by a search. By default, it is 20. + limit: # Optional +``` + +- See [ClickHouse Datasource selector](#clickhouse-datasource-selector) +- See [Writing trace queries](./queries.md#trace-queries) + +### Example + +A trace search: + +```yaml +kind: "TraceQuery" +spec: + plugin: + kind: "ClickHouseTraceQuery" + spec: + query: "SELECT TraceId, Timestamp FROM otel_traces WHERE $__timeFilter(Timestamp) AND StatusCode = 'Error'" + limit: 50 +``` + +A trace, whose ID is the value of a variable: + +```yaml +kind: "TraceQuery" +spec: + plugin: + kind: "ClickHouseTraceQuery" + spec: + query: "$traceId" +``` + +## ClickHouseProfileQuery + +Perses supports profile queries for ClickHouse: `ClickHouseProfileQuery`. + +```yaml +kind: "ClickHouseProfileQuery" +spec: + # `query` is the SQL expression returning the samples of the profile, + # with the frames of each sample in a `stack` column. + query: + + # `datasource` is a datasource selector. If not provided, the default ClickHouseDatasource is used. + # See the documentation about the datasources to understand how it is selected. + datasource: # Optional +``` + +- See [ClickHouse Datasource selector](#clickhouse-datasource-selector) +- See [Writing profile queries](./queries.md#profile-queries) + +### Example + +```yaml +kind: "ProfileQuery" +spec: + plugin: + kind: "ClickHouseProfileQuery" + spec: + query: "SELECT Timestamp AS time, FunctionNames AS stack, length(TimestampsUnixNano) AS value FROM otel_profiles WHERE $__timeFilter(Timestamp) AND ServiceName = 'checkout'" +``` + +## ClickHouseSQLVariable + +Perses supports variables listed by a ClickHouse query: `ClickHouseSQLVariable`. + +```yaml +kind: "ClickHouseSQLVariable" +spec: + # `query` is the SQL expression returning the values of the variable. + query: + + # `datasource` is a datasource selector. If not provided, the default ClickHouseDatasource is used. + # See the documentation about the datasources to understand how it is selected. + datasource: # Optional +``` + +- See [ClickHouse Datasource selector](#clickhouse-datasource-selector) +- See [Writing variable queries](./queries.md#variable-queries) + +### Example + +```yaml +kind: "ListVariable" +spec: + name: "service" + allowAllValue: true + allowMultiple: true + plugin: + kind: "ClickHouseSQLVariable" + spec: + query: "SELECT DISTINCT ServiceName FROM otel_traces WHERE $__timeFilter(Timestamp) ORDER BY ServiceName" +``` + +## ClickHouseSQLAnnotation + +Perses supports annotations read by a ClickHouse query: `ClickHouseSQLAnnotation`. + +```yaml +kind: "ClickHouseSQLAnnotation" +spec: + # `query` is the SQL expression returning one row per annotation. + query: + + # `datasource` is a datasource selector. If not provided, the default ClickHouseDatasource is used. + # See the documentation about the datasources to understand how it is selected. + datasource: # Optional +``` + +- See [ClickHouse Datasource selector](#clickhouse-datasource-selector) +- See [Writing annotation queries](./queries.md#annotation-queries) + +### Example + +```yaml +display: + name: "Deployments" +plugin: + kind: "ClickHouseSQLAnnotation" + spec: + query: "SELECT deployed_at AS time, version AS title, service FROM deployments WHERE $__timeFilter(deployed_at)" +``` + +## ClickStackDatasource + +The API of ClickStack (HyperDX) is an HTTP server. So we need to define an HTTP config. + +```yaml +kind: "ClickStackDatasource" +spec: + # It is the url of the API of ClickStack. + # Leave it empty if you don't want to access the datasource directly from the UI. + # You should define a proxy if you want to access the datasource through the Perses' server. + directUrl: # Optional + + # It is the http configuration that will be used by the Perses' server to redirect to the datasource any query sent by the UI. + proxy: # Optional + + # The url of the ClickStack UI, as users open it in their browser. + # The alerts link to it. Without it, the alerts have no link. + uiUrl: # Optional +``` + +The URL is the one of the API of ClickStack, without its `/api/v2` path: `http://:8000`, or `http://:8080/api` when only the port of the UI is reachable. + +ClickStack only accepts the requests of the browsers of its own UI, and requires an API key. Use a proxy, with a [secret](https://perses.dev/perses/docs/api/secret/) holding the API key of ClickStack as a bearer token. The key is an API key of ClickStack, found in its team settings. It is not the ingestion key. + +The plugin calls `GET /api/v2/alerts`, and the connection test `GET /api/v2`: these are the two endpoints a proxy has to allow. + +### Example + +```yaml +kind: "GlobalDatasource" +metadata: + name: "clickstack" +spec: + default: true + plugin: + kind: "ClickStackDatasource" + spec: + uiUrl: "https://clickstack.example.com" + proxy: + kind: "HTTPProxy" + spec: + url: "http://clickstack.example.com:8000" + allowedEndpoints: + - endpointPattern: "^/api/v2/alerts$" + method: "GET" + - endpointPattern: "^/api/v2$" + method: "GET" + secret: "clickstack_api_key" +``` + +With the secret: + +```yaml +kind: "GlobalSecret" +metadata: + name: "clickstack_api_key" +spec: + authorization: + type: "Bearer" + credentials: "" +``` + +## ClickStackAlertsQuery + +Perses supports listing the alerts of ClickStack: `ClickStackAlertsQuery`. + +```yaml +kind: "ClickStackAlertsQuery" +spec: + # `datasource` is a datasource selector. If not provided, the default ClickStackDatasource is used. + # See the documentation about the datasources to understand how it is selected. + datasource: # Optional + + # Only the alerts in one of these states: `ALERT` (firing), `PENDING` or `OK`. + # By default, the firing and the pending alerts are listed. + states: + - # Optional + + # Only the alerts watching one of these kinds of sources: `saved_search`, `tile` or `inline`. + # By default, all the alerts are listed. + sources: + - # Optional + + # Only the alerts with one of these tags. + # Variables are supported: a variable with several values is as many tags. + tags: + - # Optional + + # Only the alerts whose name contains this text. Variables are supported. + search: # Optional +``` + +- See [ClickStack Datasource selector](#clickstack-datasource-selector) + +Each alert of ClickStack is returned with: + +| Field | Value | +|---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `name` | The name of the alert: the one it was given, or else the name of the saved search or of the dashboard tile it watches. | +| `state` | `firing` for `ALERT`, `pending` for `PENDING`, `inactive` otherwise. | +| `labels` | `alertname`, `source`, `interval`, `group_by`, and the tags of the alert: a `key:value` tag is the label `key`, and the other tags are joined in the `tags` label. | +| `severity` | The `severity` label, as set by a `severity:` tag. ClickStack alerts have no severity of their own. | +| `annotations` | `message`, `note`, `condition` (such as `>= 100 over 5m`), `title` (the title of the notifications), `error` (the last execution error) and `silenced_until`. A note that is a link is also the `runbook_url` annotation. | +| `suppressed` | `true` while the alert is silenced. | +| `sourceURL` | The link to the saved search, the dashboard tile or the chart the alert watches, when the datasource has a `uiUrl`. | +| `startsAt` | The time of the last evaluation of the alert. ClickStack does not tell when an alert started firing. | + +An alert grouped by a column is a single alert, in the worst state of its groups. + +### Example + +The alerts of a team, in an alert table: + +```yaml +kind: "Panel" +spec: + display: + name: "ClickStack alerts" + plugin: + kind: "AlertTable" + spec: + # Alerts are silenced in ClickStack: the silence action of the table is for Alertmanager. + allowedActions: ["runbook"] + columns: + - name: "severity" + sortMode: "severity" + labelColorMappings: + - labelKey: "severity" + mode: "severity" + queries: + - kind: "AlertsQuery" + spec: + plugin: + kind: "ClickStackAlertsQuery" + spec: + states: ["ALERT", "PENDING", "OK"] + tags: ["team:$team"] ``` ## Shared definitions @@ -141,3 +443,11 @@ kind: "ClickHouseDatasource" # The name of the datasource regardless its level name: # Optional ``` + +### ClickStack Datasource selector + +```yaml +kind: "ClickStackDatasource" +# The name of the datasource regardless its level +name: # Optional +``` diff --git a/docs/clickhouse/queries.md b/docs/clickhouse/queries.md new file mode 100644 index 000000000..23d0b4e1c --- /dev/null +++ b/docs/clickhouse/queries.md @@ -0,0 +1,318 @@ +# Writing ClickHouse queries + +Every ClickHouse plugin runs a SQL statement that you write. This page describes what the plugins add to SQL, the macros and the variables, and the columns each plugin expects. + +## How queries are run + +- A query is a single `SELECT` statement, sent to the HTTP interface of ClickHouse as read-only. +- The plugins choose the format of the results: a final `FORMAT` clause is ignored. +- Table names without a database are read from the database of the [datasource](./model.md#clickhousedatasource), which is `default` unless the datasource names another one. +- At most 100 000 rows are read. A panel warns when the result of its query was cut. +- The error of a failed query is the one of ClickHouse. + +## Time range and interval + +Macros give a query the time range of the dashboard and an interval suited to it. Their names and their results follow the ClickHouse datasource of Grafana. + +| Macro | Replaced by | +|---------------------------------------------|----------------------------------------------------------------------------------------------| +| `$__timeFilter(column)` | `(column >= toDateTime() AND column <= toDateTime())`, to the second | +| `$__timeFilter_ms(column)` | The same condition, to the millisecond | +| `$__dateFilter(column)` | The same condition on a `Date` column | +| `$__dateTimeFilter(dateColumn, timeColumn)` | The conditions on a `Date` column, widened by a day on each side, and on a `DateTime` column, for tables partitioned by date | +| `$__timeInterval(column)` | `toStartOfInterval(toDateTime(column), INTERVAL second)` | +| `$__timeInterval_ms(column)` | `toStartOfInterval(toDateTime64(column, 3), INTERVAL millisecond)` | +| `$__interval_s`, `$__interval_ms` | The interval, in seconds or in milliseconds | +| `$__fromTime`, `$__toTime` | The start and the end of the time range, as `DateTime` | +| `$__fromTime_ms`, `$__toTime_ms` | The start and the end of the time range, as `DateTime64(3)` | +| `$__conditionalAll(condition, $variable)` | The condition, or `1=1` when "All" is selected for the variable | + +The interval is a round duration, from 1 second to 30 days. For a time series query it is at least the interval between two points the panel can draw, which depends on the width of the panel. For the other queries it splits the time range in about 300 intervals. + +```sql +SELECT + $__timeInterval(Timestamp) AS time, + ServiceName, + count() / $__interval_s AS rps +FROM otel_traces +WHERE $__timeFilter(Timestamp) AND SpanKind = 'Server' +GROUP BY time, ServiceName +ORDER BY time +``` + +The `{start}` and `{end}` placeholders are also replaced by the time range, as `YYYY-MM-DD hh:mm:ss` in UTC: `WHERE Timestamp BETWEEN '{start}' AND '{end}'`. + +Macros are not replaced in comments. Inside a string, only the ones without arguments are: `'$__interval_s'` is, `'%$__timeFilter%'` is not. + +### Min step + +A time series query can set a **min step**, the lower bound of its interval: a duration such as `1m`, or a variable holding one. + +A wide panel on a short time range asks for an interval of a few seconds. When the data is written less often, by sources that do not write at the same time, an interval only holds the points of some of the sources: an aggregate over the sources is wrong, and a chart draws gaps between the points. Set the min step to the interval the data is written at. + +## Variables + +Queries can use the variables of the dashboard: `$name`, `${name}` or `${name:format}`, with the [interpolation formats](https://perses.dev/perses/docs/concepts/variable/#using-variables) of Perses. + +Use the `sqlstring` format wherever a value is a string. It quotes each value as a ClickHouse string literal, and separates several values with commas: + +```sql +WHERE ServiceName IN (${service:sqlstring}) +``` + +A variable with "All" selected holds every value. To drop the condition instead of listing them all, wrap it in `$__conditionalAll`: + +```sql +WHERE $__conditionalAll(ServiceName IN (${service:sqlstring}), $service) +``` + +Variables are not replaced in comments: a value could end the comment. + +## Time series queries + +The columns of the result tell what the rows are: + +- The **time** of a row is its column named `time`, `timestamp` or `TimeUnix`, whatever the case, or else its first `Date` or `DateTime` column. +- **Values** are the numeric columns: integers, floats, decimals and booleans. +- **Labels** are all the other columns. The rows are split in one series per combination of their values. A `Map`, `Tuple` or `JSON` column gives one label per key, named `.`. Array columns are ignored. + +A series is named after its labels, as `{ServiceName="checkout"}`. Without label columns it is named after its value column. With several value columns it is named after both, as `p95{ServiceName="checkout"}`, and the name of its value column is its `__name__` label. Set the **series name format** of the query to choose the names: `{{ServiceName}}` is replaced by the value of the label. + +A query returns at most 1 000 series. + +### Interval of the points + +Charts draw the points of a series at regular intervals, and join the ones that follow each other. This interval is worked out from the rows of the query: + +- When most rows of a series are at about the same interval, it is this interval. A metric written every minute is drawn as a line, even by a query grouping its rows by a shorter interval, and so are the months of a year. +- Otherwise it is the longest interval all the rows are on. A series with more holes than rows keeps its rows where they are, and is drawn with gaps. + +Rows that are not at regular intervals, such as the rows of a table of events, are drawn at the closest place a chart has for them. When several rows of a series are too close to each other to be drawn, only the last one is, and the panel warns about it: aggregate the rows over time. + +### Gaps + +ClickHouse returns no row for an interval without data, which a chart draws as a gap. To get a zero instead, ask ClickHouse to fill the intervals. Order by the label columns first: each series is then filled on its own. + +```sql +SELECT $__timeInterval(Timestamp) AS time, ServiceName, count() AS errors +FROM otel_traces +WHERE $__timeFilter(Timestamp) AND StatusCode = 'Error' +GROUP BY time, ServiceName +ORDER BY ServiceName, time WITH FILL STEP $__interval_s +``` + +### Tables + +A query without a time column is a table: each row is a series of one point, at the end of the time range, even when the labels of two rows are the same, and the series keep the order of the rows. Use it for the stat, gauge, bar and table panels. + +```sql +SELECT ServiceName, count() AS spans, quantile(0.95)(Duration) / 1e6 AS p95_ms +FROM otel_traces +WHERE $__timeFilter(Timestamp) +GROUP BY ServiceName +ORDER BY spans DESC +LIMIT 10 +``` + +In a table panel, each series is a row with the labels of the series and its value. To get one column per value column of the query: + +- When the rows have a single label column, as above, add the `PivotByLabel` transform to the panel, with `__name__` as column label and the label column, here `ServiceName`, as row field. +- Otherwise, use one query per value column and the `MergeSeries` transform. + +### OpenTelemetry metrics + +The rows of the metric tables of the ClickHouse exporter can be read as they are. The names of the service and of the metric, and the resource, scope and data point attributes, are the labels of the series. + +```sql +SELECT * FROM otel_metrics_gauge +WHERE $__timeFilter(TimeUnix) AND MetricName = 'system.memory.utilization' +``` + +Most often a query aggregates them: + +```sql +SELECT + $__timeInterval(TimeUnix) AS time, + Attributes['state'] AS state, + avg(Value) AS value +FROM otel_metrics_gauge +WHERE $__timeFilter(TimeUnix) AND MetricName = 'system.memory.utilization' +GROUP BY time, state +ORDER BY time +``` + +A metric has a point every time it is exported, every minute by default. Set the [min step](#min-step) of the query to this interval when the points of the metric come from several sources, such as the instances of a service. + +OpenTelemetry sums are usually cumulative. Their rate is the increase of each series since its previous point, divided by the time between the two. Dividing by the interval would be wrong when the metric is exported less often: + +```sql +SELECT time, ServiceName, sum(rate) AS value +FROM ( + SELECT + $__timeInterval(TimeUnix) AS time, + ServiceName, + Attributes, + max(Value) AS last, + lagInFrame(last, 1, last) OVER series AS previous, + lagInFrame(time, 1, time) OVER series AS previousTime, + greatest(last - previous, 0) / greatest(dateDiff('second', previousTime, time), 1) AS rate + FROM otel_metrics_sum + WHERE $__timeFilter(TimeUnix) AND MetricName = 'traces.span.metrics.calls' + GROUP BY time, ServiceName, Attributes + WINDOW series AS (PARTITION BY ServiceName, Attributes ORDER BY time) +) +GROUP BY time, ServiceName +ORDER BY time +``` + +### Histograms + +A result with the histogram columns of OpenTelemetry returns histograms, which the heat map and histogram panels display: + +- `BucketCounts` and `ExplicitBounds` for an explicit bucket histogram. +- `Scale`, `ZeroCount`, `PositiveOffset`, `PositiveBucketCounts`, `NegativeOffset` and `NegativeBucketCounts` for an exponential histogram. +- `Count` and `Sum`, optional, for both. + +The histograms of OpenTelemetry are usually cumulative. This query returns the buckets of each interval, for a heat map: + +```sql +SELECT time, sumForEach(delta) AS BucketCounts, any(bounds) AS ExplicitBounds +FROM ( + SELECT + time, + bounds, + arrayMap((count, previous) -> toUInt64(greatest(toInt64(count) - toInt64(previous), 0)), + counts, lagInFrame(counts, 1, counts) OVER (PARTITION BY ServiceName, Attributes ORDER BY time)) AS delta + FROM ( + SELECT + $__timeInterval(TimeUnix) AS time, + ServiceName, + Attributes, + argMax(BucketCounts, TimeUnix) AS counts, + any(ExplicitBounds) AS bounds + FROM otel_metrics_histogram + WHERE $__timeFilter(TimeUnix) AND MetricName = 'traces.span.metrics.duration' + GROUP BY time, ServiceName, Attributes + ) +) +GROUP BY time +ORDER BY time +``` + +### Exemplars + +Exemplars are read from two places: + +- The exemplar columns of the OpenTelemetry metric tables, when the query returns them: `Exemplars.TimeUnix`, `Exemplars.Value`, `Exemplars.TraceId`, `Exemplars.SpanId` and `Exemplars.FilteredAttributes`. +- The **exemplar query** of the time series query. Each of its rows is an exemplar: a time column, a `value` column, the label columns of the series it belongs to, and any other column as a label of the exemplar. When the query returns several value columns, the exemplars belong to the series of the first one: return the name of another one in a `__name__` column to attach them to its series. + +```sql +SELECT Timestamp AS time, Duration / 1e6 AS value, ServiceName, TraceId AS trace_id, SpanId AS span_id +FROM otel_traces +WHERE $__timeFilter(Timestamp) AND SpanKind = 'Server' +ORDER BY Duration DESC +LIMIT 100 +``` + +## Log queries + +Each row is a log: + +- Its **time** is its column named `Timestamp`, `log_time` or `time`, whatever the case, or else its first `Date` or `DateTime` column. +- Its **line** is its column named `Body`, `message`, `msg`, `line` or `log`. A log without a line, such as an OpenTelemetry event, is described by its labels. +- Its **labels** are its other columns. A `Map` column gives one label per key, named `.`. Empty values are left out. +- Its **level**, which colors it, is its `level` label. When the query does not return one, it is taken from the `SeverityText` column, or else from the `SeverityNumber` column. + +```sql +SELECT Timestamp, Body, SeverityText, ServiceName, TraceId, LogAttributes +FROM otel_logs +WHERE $__timeFilter(Timestamp) AND ServiceName IN (${service:sqlstring}) +ORDER BY Timestamp DESC +LIMIT 1000 +``` + +In the log explorer, the volume of the logs is charted above them. It counts, by interval and by level, all the logs matching the query, whatever its `ORDER BY` and `LIMIT` clauses. It is not charted for a query that does not select its time column by name, or that uses `UNION` or `LIMIT BY`. + +## Trace queries + +Traces are read from a table in the schema of the ClickHouse exporter of the OpenTelemetry Collector, which is also the schema of ClickStack: `otel_traces` by default, or the **trace table** of the query. + +The query is either: + +- A **trace ID**, or a variable holding one. It returns the trace, for the Gantt chart. The trace is looked for whatever the time range of the dashboard. +- A **search**: a SQL query returning the `TraceId` and `Timestamp` columns of the spans to search for. It returns the traces of these spans, the most recent ones first, for the trace table and the scatter chart. Each trace is summarized from all its spans, not only the ones the query returns. + +```sql +SELECT TraceId, Timestamp +FROM otel_traces +WHERE $__timeFilter(Timestamp) + AND ServiceName = 'checkout' + AND (StatusCode = 'Error' OR Duration > 1e9) +``` + +A search returns 20 traces by default: change the **limit** of the query for more. + +To open a trace from a trace table, link the table to a dashboard with a text variable and a Gantt chart whose query is the variable, as `$traceId`. + +## Profile queries + +A profile query returns one row per sample, or group of samples: + +- `stack`, required: the array of the frames of the sample, from the leaf to the root, as in the OpenTelemetry profiles. +- `value`: the value of the sample. Without this column, each row counts for 1. +- `time`: the time of the sample, for the timeline above the flame graph. +- `name` and `unit`: the name and the unit of the values, such as `nanoseconds`, `bytes` or `count`. + +ClickHouse adds the samples up by stack and by interval: only the flame graph and the timeline are sent to the browser. + +```sql +SELECT + Timestamp AS time, + arrayMap((name, file) -> if(name != '', name, file), FunctionNames, MappingFileNames) AS stack, + length(TimestampsUnixNano) AS value, + SampleType AS name, + SampleUnit AS unit +FROM otel_profiles +WHERE $__timeFilter(Timestamp) AND SampleType = 'samples' AND ServiceName = 'checkout' +``` + +A query can build its own stacks. This one shows the function on CPU under its service: + +```sql +SELECT + [if(FunctionNames[1] != '', FunctionNames[1], MappingFileNames[1]), ServiceName] AS stack, + length(TimestampsUnixNano) AS value +FROM otel_profiles +WHERE $__timeFilter(Timestamp) AND SampleType = 'samples' +``` + +!!! note + Perses does not give the variables of the dashboard to profile queries yet. A profile query can use the macros, but not variables. + +## Variable queries + +The values of the variable are the `value` column of the result, or else its first column. An optional `label` column holds the text displayed for each value. Empty and repeated values are left out. + +```sql +SELECT DISTINCT SpanName AS value +FROM otel_traces +WHERE $__timeFilter(Timestamp) AND ServiceName IN (${service:sqlstring}) +ORDER BY value +``` + +## Annotation queries + +Each row is an annotation: + +- Its **time** is its column named `start`, `time` or `timestamp`, or else its first `Date` or `DateTime` column. +- An `end` column makes it a time span. +- The `title` and `legend` columns are its texts. +- Its other columns are its tags. + +```sql +SELECT Timestamp AS time, Body AS title, ServiceName +FROM otel_logs +WHERE $__timeFilter(Timestamp) AND SeverityNumber >= 17 +ORDER BY Timestamp +LIMIT 100 +``` diff --git a/docs/nav.yaml b/docs/nav.yaml index 76f592af9..f1e9d15a5 100644 --- a/docs/nav.yaml +++ b/docs/nav.yaml @@ -25,11 +25,18 @@ - Alert Table: alertmanager/go-sdk/alert-table.md - ClickHouse: - Overview: clickhouse/README.md + - Writing queries: clickhouse/queries.md - Model: clickhouse/model.md - Go SDK: - Datasource: clickhouse/go-sdk/datasource.md - Log Query: clickhouse/go-sdk/log-query.md - Time Series Query: clickhouse/go-sdk/timeseries-query.md + - Trace Query: clickhouse/go-sdk/trace-query.md + - Profile Query: clickhouse/go-sdk/profile-query.md + - Variable: clickhouse/go-sdk/variable.md + - Annotation: clickhouse/go-sdk/annotation.md + - ClickStack Datasource: clickhouse/go-sdk/clickstack-datasource.md + - ClickStack Alerts Query: clickhouse/go-sdk/clickstack-alerts-query.md - GreptimeDB: - Overview: greptimedb/README.md - Model: greptimedb/model.md diff --git a/e2e/src/data/clickhouse/clickhouse.json b/e2e/src/data/clickhouse/clickhouse.json new file mode 100644 index 000000000..b745481ff --- /dev/null +++ b/e2e/src/data/clickhouse/clickhouse.json @@ -0,0 +1,148 @@ +[ + { + "kind": "GlobalDatasource", + "metadata": { + "name": "e2e-clickhouse" + }, + "spec": { + "default": true, + "plugin": { + "kind": "ClickHouseDatasource", + "spec": { + "database": "otel", + "proxy": { + "kind": "HTTPProxy", + "spec": { + "url": "http://clickhouse.invalid:8123", + "allowedEndpoints": [ + { + "endpointPattern": "^/$", + "method": "POST" + }, + { + "endpointPattern": "^/ping$", + "method": "GET" + } + ] + } + } + } + } + } + }, + { + "kind": "Dashboard", + "metadata": { + "name": "clickhouse", + "project": "e2eproject" + }, + "spec": { + "display": { + "name": "ClickHouse" + }, + "duration": "1h", + "variables": [ + { + "kind": "ListVariable", + "spec": { + "name": "service", + "allowAllValue": false, + "allowMultiple": true, + "defaultValue": ["checkout"], + "plugin": { + "kind": "ClickHouseSQLVariable", + "spec": { + "query": "SELECT DISTINCT ServiceName FROM otel_traces WHERE $__timeFilter(Timestamp) ORDER BY ServiceName" + } + } + } + } + ], + "panels": { + "requests": { + "kind": "Panel", + "spec": { + "display": { + "name": "Requests" + }, + "plugin": { + "kind": "TimeSeriesChart", + "spec": { + "legend": { + "position": "bottom", + "mode": "list" + } + } + }, + "queries": [ + { + "kind": "TimeSeriesQuery", + "spec": { + "plugin": { + "kind": "ClickHouseTimeSeriesQuery", + "spec": { + "query": "SELECT $__timeInterval(Timestamp) AS time, ServiceName, count() AS requests FROM otel_traces WHERE $__timeFilter(Timestamp) AND ServiceName IN (${service:sqlstring}) GROUP BY time, ServiceName ORDER BY time", + "seriesNameFormat": "requests of {{ServiceName}}" + } + } + } + } + ] + } + }, + "logs": { + "kind": "Panel", + "spec": { + "display": { + "name": "Logs" + }, + "plugin": { + "kind": "LogsTable", + "spec": {} + }, + "queries": [ + { + "kind": "LogQuery", + "spec": { + "plugin": { + "kind": "ClickHouseLogQuery", + "spec": { + "query": "SELECT Timestamp, Body, SeverityText, ServiceName FROM otel_logs WHERE $__timeFilter(Timestamp) ORDER BY Timestamp DESC LIMIT 100" + } + } + } + } + ] + } + } + }, + "layouts": [ + { + "kind": "Grid", + "spec": { + "items": [ + { + "x": 0, + "y": 0, + "width": 12, + "height": 8, + "content": { + "$ref": "#/spec/panels/requests" + } + }, + { + "x": 12, + "y": 0, + "width": 12, + "height": 8, + "content": { + "$ref": "#/spec/panels/logs" + } + } + ] + } + } + ] + } + } +] diff --git a/e2e/src/tests/clickhouse/clickhouse.spec.ts b/e2e/src/tests/clickhouse/clickhouse.spec.ts new file mode 100644 index 000000000..9ebc339f7 --- /dev/null +++ b/e2e/src/tests/clickhouse/clickhouse.spec.ts @@ -0,0 +1,118 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { Page } from '@playwright/test'; +import { expect, test } from '@playwright/test'; + +const DASHBOARD = '/projects/e2eproject/dashboards/clickhouse'; +// The datasource of the dashboard is proxied by Perses: its requests are answered here, in place of ClickHouse. +const PROXY = /\/proxy\/globaldatasources\/e2e-clickhouse/; +const FORMAT = 'JSONCompactEachRowWithNamesAndTypes'; + +type Rows = unknown[][]; + +function minutesAgo(minutes: number): string { + const time = new Date(Date.now() - minutes * 60_000); + time.setUTCSeconds(0, 0); + return time.toISOString().replace('.000Z', 'Z'); +} + +// What ClickHouse would answer to the statements of the dashboard. +function answer(sql: string): Rows { + if (sql.includes('DISTINCT ServiceName')) { + return [['ServiceName'], ['LowCardinality(String)'], ['checkout'], ['frontend']]; + } + if (sql.includes('FROM otel_logs')) { + return [ + ['Timestamp', 'Body', 'SeverityText', 'ServiceName'], + ['DateTime64(9)', 'String', 'LowCardinality(String)', 'LowCardinality(String)'], + [minutesAgo(1), 'payment failed: card declined', 'ERROR', 'checkout'], + [minutesAgo(2), 'order placed', 'INFO', 'checkout'], + ]; + } + return [ + ['time', 'ServiceName', 'requests'], + ['DateTime', 'LowCardinality(String)', 'UInt64'], + [minutesAgo(3), 'checkout', '12'], + [minutesAgo(2), 'checkout', '15'], + [minutesAgo(1), 'checkout', '9'], + ]; +} + +// Answers the queries of the page as ClickHouse does, and returns the statements it receives. +async function mockClickHouse(page: Page): Promise { + const statements: string[] = []; + await page.route(PROXY, async (route) => { + const sql = route.request().postData() ?? ''; + statements.push(sql); + await route.fulfill({ + status: 200, + contentType: 'text/plain; charset=UTF-8', + headers: { 'X-ClickHouse-Format': FORMAT, 'X-ClickHouse-Timezone': 'UTC' }, + body: `${answer(sql) + .map((row) => JSON.stringify(row)) + .join('\n')}\n`, + }); + }); + return statements; +} + +test.describe('ClickHouse plugin', () => { + test('displays the results of its queries on a dashboard', async ({ page }) => { + const statements = await mockClickHouse(page); + + await page.goto(DASHBOARD); + + // The series is named with the format of the query, and the logs are listed with their lines. + await expect(page.getByText('requests of checkout')).toBeVisible(); + await expect(page.getByText('payment failed: card declined')).toBeVisible(); + + // The chart query was sent with its macros and the variable of the dashboard replaced. + const chartQuery = statements.find((sql) => sql.includes('AS requests')) ?? ''; + expect(chartQuery).toMatch(/toStartOfInterval\(toDateTime\(Timestamp\), INTERVAL \d+ second\) AS time/); + expect(chartQuery).toMatch(/\(Timestamp >= toDateTime\(\d+\) AND Timestamp <= toDateTime\(\d+\)\)/); + expect(chartQuery).toContain("ServiceName IN ('checkout')"); + expect(statements.join('\n')).not.toContain('$__'); + }); + + test('lists the values of a variable from its query', async ({ page }) => { + const statements = await mockClickHouse(page); + + await page.goto(DASHBOARD); + await expect(page.getByText('requests of checkout')).toBeVisible(); + + await page.getByRole('combobox', { name: 'service' }).click(); + await page.getByRole('option', { name: 'frontend' }).click(); + + // Selecting a second value runs the chart query again with both of them. + await expect + .poll(() => statements.some((sql) => sql.includes("ServiceName IN ('checkout','frontend')"))) + .toBe(true); + }); + + test('displays the error of ClickHouse when a query fails', async ({ page }) => { + await page.route(PROXY, async (route) => { + await route.fulfill({ + status: 404, + contentType: 'text/plain; charset=UTF-8', + body: "Code: 60. DB::Exception: Unknown table expression identifier 'otel_traces'. (UNKNOWN_TABLE) (version 26.9.1.1 (official build))\n", + }); + }); + + await page.goto(DASHBOARD); + + await expect( + page.getByText('ClickHouse query failed: Code: 60. DB::Exception: Unknown table expression identifier').first(), + ).toBeVisible(); + }); +});